answer
stringlengths 17
10.2M
|
|---|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Compiler {
static Pattern relation_pattern = Pattern.compile("(.+)(>|<|>=|<=|==|!=)+(.+)");
static Pattern expression_pattern = Pattern.compile("([a-zA-Z0-9+-*/()]+)");
Scanner scanner;
int[] memory;
ArrayList<Integer> constants;
HashMap<Integer, Integer> line_numbers;
HashMap<String, Integer> variables;
int line_number, pointer, data_pointer;
public Compiler(File file) throws FileNotFoundException {
scanner = new Scanner(file);
memory = new int[100];
constants = new ArrayList<Integer>();
line_numbers = new HashMap<Integer, Integer>();
variables = new HashMap<String, Integer>();
line_number = 0;
pointer = 0;
data_pointer = 99;
}
public int[] compile() {
while(scanner.hasNextLine()) {
if(pointer >= data_pointer)
throw new OutOfMemoryException();
String[] command = scanner.nextLine().split(" ");
int next_line_number = Integer.parseInt(command[0]);
if(next_line_number <= line_number)
throw new LineNumberException();
line_numbers.put(next_line_number, pointer);
line_number = next_line_number;
if(command[1].equalsIgnoreCase("rem")) //Ingore comment lines
continue;
else if(command[1].equalsIgnoreCase("input")) { //Make a new variable and remember it
if(!Character.isLetter(command[2].charAt(0)))
throw new InvalidVariableException();
variables.put(command[2], data_pointer);
memory[pointer] = 1000 + data_pointer;
data_pointer
}
else if(command[1].equalsIgnoreCase("print")) { //Simply print variable
if(!variables.containsKey(command[2]))
throw new UndefinedVariableException();
memory[pointer] = 1100 + variables.get(command[2]);
}
else if(command[1].equalsIgnoreCase("let")) { //If a variable doesn't exist, create it then parse the expression
if(!variables.containsKey(command[2])) {
variables.put(command[2], data_pointer);
data_pointer
}
parseExpression(command[3], variables.get(command[2]));
}
else if(command[1].equalsIgnoreCase("goto")) { //Put a new goto
memory[pointer] = 4000 + Integer.parseInt(command[2]);
}
else if(command[1].equalsIgnoreCase("if")) { //Yay for if's
if(!command[3].equalsIgnoreCase("goto"))
throw new IllegalArgumentException();
parseRelation(command[2]);//Call parse relation
memory[pointer] = 4100 + Integer.parseInt(command[4]);//Branch 0 to "goto"
}
else if(command[1].equalsIgnoreCase("end")) //Put a halt
memory[pointer] = 4300;
pointer++;
}
}
private void parseRelation(String relation) {
Matcher matcher = relation_pattern.matcher(relation);
if(!matcher.matches())
throw new SyntaxException();
}
private void parseExpression(String expression, int value_pointer) {
Matcher matcher = expression_pattern.matcher(expression);
if(!matcher.matches())
throw new SyntaxException();
}
}
|
package org.javacint.sms;
import com.siemens.icm.io.ATCommand;
import org.javacint.at.ATCommandPooled;
import org.javacint.at.ATCommands;
import org.javacint.logging.Logger;
/**
* The most basic SMS handling class possible.
*/
public class SimpleSMS {
private static final char CTRL_Z = 0x1a;
private static final boolean DEBUG = true;
public static boolean send(String dest, String msg) {
try {
String ret;
ATCommandPooled acp = null;
try {
acp = ATCommands.getATCommand();
acp.send("at+cmgf=1");
ret = acp.send("at+cmgs=" + dest);
ret += acp.send(msg + CTRL_Z);
} finally {
acp.release();
}
if (Logger.BUILD_DEBUG && DEBUG) {
Logger.log("SMSManagement.send.ret = \"" + ret + "\"");
}
} catch (Exception ex) {
if (Logger.BUILD_CRITICAL) {
Logger.log("SMSManagement.send", ex, true);
}
return false;
}
return true;
}
}
|
package io.minecloud;
import io.minecloud.db.Credentials;
import io.minecloud.db.mongo.MongoDatabase;
import io.minecloud.db.redis.RedisDatabase;
import io.minecloud.models.bungee.Bungee;
import io.minecloud.models.bungee.BungeeRepository;
import io.minecloud.models.bungee.type.BungeeType;
import io.minecloud.models.bungee.type.BungeeTypeRepository;
import io.minecloud.models.network.Network;
import io.minecloud.models.network.NetworkRepository;
import io.minecloud.models.nodes.Node;
import io.minecloud.models.nodes.NodeRepository;
import io.minecloud.models.nodes.type.NodeType;
import io.minecloud.models.nodes.type.NodeTypeRepository;
import io.minecloud.models.plugins.PluginType;
import io.minecloud.models.plugins.PluginTypeRepository;
import io.minecloud.models.server.Server;
import io.minecloud.models.server.ServerRepository;
import io.minecloud.models.server.type.ServerType;
import io.minecloud.models.server.type.ServerTypeRepository;
import lombok.Setter;
import org.mongodb.morphia.logging.MorphiaLoggerFactory;
import org.mongodb.morphia.logging.SilentLogger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Properties;
import java.util.Scanner;
import java.util.logging.Logger;
public final class MineCloud {
private static final MineCloud INSTANCE = new MineCloud();
private static final Logger LOGGER = Logger.getLogger("MineCloud");
@Setter
private MongoDatabase mongo;
@Setter
private RedisDatabase redis;
private MineCloud() {}
public static MineCloud instance() {
return INSTANCE;
}
public static Logger logger() {
return LOGGER;
}
public static void environmentSetup() {
Credentials mongoCredentials = new Credentials(getenv("mongo_hosts").split(";"),
getenv("mongo_username"), getenv("mongo_password").toCharArray(),
getenv("mongo_database"));
Credentials redisCredentials = new Credentials(new String[] {getenv("redis_host")},
"", getenv("redis_password").toCharArray());
instance().initiateMongo(mongoCredentials);
instance().initiateRedis(redisCredentials);
}
private static String getenv(String name) {
String env = System.getenv(name);
return env == null ? "" : env;
}
public static void runSetup(Properties properties, File file) throws IOException {
Scanner scanner = new Scanner(System.in);
String[] hosts;
String database;
String username;
String password;
logger().info("I see you either have your details mis-configured or there is none, " +
"we will proceed with performing the initial setup!");
System.out.print("Please enter the hosts for MongoDB (separated by commas): ");
hosts = scanner.nextLine().split(",");
System.out.println();
System.out.print("Please enter the database name: ");
database = scanner.nextLine();
System.out.println();
System.out.print("Please enter the username for auth.:");
username = scanner.nextLine();
System.out.println();
System.out.print("Please enter the password for " + username + ": ");
password = scanner.nextLine();
StringBuilder formattedHosts = new StringBuilder();
for (String s : hosts) {
formattedHosts.append(s)
.append(";");
}
properties.setProperty("mongo-hosts", formattedHosts.toString());
properties.setProperty("mongo-database", database);
properties.setProperty("mongo-username", username);
properties.setProperty("mongo-password", password);
Credentials mongo = new Credentials(hosts, username, password.toCharArray(), database);
MineCloud.instance().initiateMongo(mongo);
System.out.println();
System.out.print("Great! Please enter the host for the Redis server: ");
hosts = new String[] {scanner.nextLine()};
System.out.println();
System.out.print("Please enter the password for " + username + ":");
password = scanner.nextLine();
properties.setProperty("redis-host", hosts[0]);
properties.setProperty("redis-password", password);
Credentials redis = new Credentials(hosts, "", password.toCharArray());
MineCloud.instance().initiateRedis(redis);
System.out.print("Lastly, please enter the name of this node: ");
properties.setProperty("node-name", scanner.nextLine());
logger().info("Finished setup!");
logger().info("You can modify the database details in " + file.getAbsolutePath());
properties.store(new FileOutputStream(file), "");
}
public MongoDatabase mongo() {
return mongo;
}
public RedisDatabase redis() {
return redis;
}
public void initiateMongo(Credentials credentials) {
mongo = MongoDatabase.createDatabase(credentials);
mongo.setup();
mongo.loadRepository(NetworkRepository.create(mongo.datastore()), Network.class);
mongo.loadRepository(NodeTypeRepository.create(mongo.datastore()), NodeType.class);
mongo.loadRepository(NodeRepository.create(mongo.datastore()), Node.class);
mongo.loadRepository(BungeeTypeRepository.create(mongo.datastore()), BungeeType.class);
mongo.loadRepository(BungeeRepository.create(mongo.datastore()), Bungee.class);
mongo.loadRepository(ServerTypeRepository.create(mongo.datastore()), ServerType.class);
mongo.loadRepository(ServerRepository.create(mongo.datastore()), Server.class);
mongo.loadRepository(PluginTypeRepository.create(mongo.datastore()), PluginType.class);
try {
Class<?> cls = Class.forName("org.mongodb.morphia.query.QueryValidator");
Field log = cls.getDeclaredField("LOG");
Field modifiersField = Field.class.getDeclaredField("modifiers");
log.setAccessible(true);
modifiersField.setAccessible(true);
modifiersField.setInt(log, log.getModifiers() & ~Modifier.FINAL);
log.set(null, new SilentLogger());
} catch (Exception e) {
logger().info("Unable to override query validator logger!");
e.printStackTrace();
}
}
public void initiateRedis(Credentials credentials) {
redis = RedisDatabase.create(credentials);
redis.setup();
}
}
|
package therian.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import therian.Operation;
import therian.TypeLiteral;
import therian.operation.Convert;
import therian.operation.Copy;
import therian.operation.Size;
import therian.operation.Transform;
import therian.operator.FromSourceToTarget.FromSource;
import therian.operator.FromSourceToTarget.ToTarget;
import therian.operator.convert.CopyingConverter;
import therian.operator.convert.IterableToIterator;
import therian.operator.size.SizeOfCollection;
import therian.operator.size.SizeOfIterable;
import therian.operator.size.SizeOfIterator;
import therian.testfixture.Book;
import therian.testfixture.MetasyntacticVariable;
public class TypesTest {
@Test
public void testGetSimpleType() {
assertEquals(new TypeLiteral<ArrayList<String>>() {}.value, Types.resolveAt(
Size.of(Positions.<ArrayList<String>> readWrite(new TypeLiteral<ArrayList<String>>() {})),
Size.class.getTypeParameters()[0]));
}
@Test
public void testGetInheritedType() {
final Copy<Integer, String> copy =
Copy.to(Positions.<String> readWrite(String.class), Positions.readOnly(Integer.valueOf(666)));
assertEquals(Integer.class, Types.resolveAt(copy, Transform.class.getTypeParameters()[0]));
assertEquals(String.class, Types.resolveAt(copy, Transform.class.getTypeParameters()[1]));
assertEquals(Integer.class, Types.resolveAt(copy, Copy.class.getTypeParameters()[0]));
assertEquals(String.class, Types.resolveAt(copy, Copy.class.getTypeParameters()[1]));
final Convert<Integer, String> convert = Convert.to(String.class, Positions.readOnly(Integer.valueOf(666)));
assertEquals(Integer.class, Types.resolveAt(convert, Transform.class.getTypeParameters()[0]));
assertEquals(String.class, Types.resolveAt(convert, Transform.class.getTypeParameters()[1]));
assertEquals(Integer.class, Types.resolveAt(convert, Convert.class.getTypeParameters()[0]));
assertEquals(String.class, Types.resolveAt(convert, Convert.class.getTypeParameters()[1]));
}
@Test
public void testGetInterfaceType() {
final IterableToIterator iterableToIterator = new IterableToIterator();
assertTrue(Types.equals(Types.parameterize(Iterable.class, Types.WILDCARD_ALL),
Types.resolveAt(iterableToIterator, FromSource.class.getTypeParameters()[0])));
assertEquals(Iterator.class, Types.resolveAt(iterableToIterator, ToTarget.class.getTypeParameters()[0]));
final CopyingConverter<Object, Book> forBook = CopyingConverter.forTargetType(Book.class);
assertEquals(Object.class, Types.resolveAt(forBook, FromSource.class.getTypeParameters()[0]));
assertEquals(Book.class, Types.resolveAt(forBook, ToTarget.class.getTypeParameters()[0]));
assertEquals(Object.class,
Types.resolveAt(CopyingConverter.IMPLEMENTING_COLLECTION, FromSource.class.getTypeParameters()[0]));
assertEquals(Collection.class,
Types.resolveAt(CopyingConverter.IMPLEMENTING_COLLECTION, ToTarget.class.getTypeParameters()[0]));
}
public void testNonTyped() {
Assert.assertNull(Types.resolveAt(
Copy.to(Positions.<String> readWrite(String.class), Positions.readOnly(Integer.valueOf(666))),
Operation.class.getTypeParameters()[0]));
}
@Test(expected = IllegalArgumentException.class)
public void testBadTypeVariable() throws Exception {
Types.resolveAt(Convert.to(String.class, Positions.readOnly(Integer.valueOf(666))), getClass()
.getDeclaredMethod("foo").getTypeParameters()[0]);
}
@Test(expected = IllegalArgumentException.class)
public void testNotAssignableTypeVariable() {
Types.resolveAt(Convert.to(String.class, Positions.readOnly(Integer.valueOf(666))),
Copy.class.getTypeParameters()[0]);
}
@Test
public void testMatchesOperator() {
final Size<List<MetasyntacticVariable>> size =
Size.of(Positions.<List<MetasyntacticVariable>> readOnly(Arrays.asList(MetasyntacticVariable.values())));
assertTrue(size.matches(new SizeOfCollection()));
assertTrue(size.matches(new SizeOfIterable()));
assertFalse(size.matches(new SizeOfIterator()));
}
@SuppressWarnings("unused")
private <T> void foo() {
}
}
|
package thwack.and.bash.game.level;
import java.util.ArrayList;
import thwack.and.bash.game.entity.Entity;
import thwack.and.bash.game.entity.mob.Player;
import thwack.and.bash.game.util.Util.Objects;
import thwack.and.bash.game.util.Util.Pixels;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Array;
/*
* THIS IS NOT THE FINAL VERSION,
*/
public class Level {
private Level () {
}
private static World world;
private static OrthogonalTiledMapRenderer mapRenderer;
private static TiledMap tiledMap;
private static Player player;
private static Array<Entity> entities;
public static void update (float delta) {
world.step(1 / 60f, 6, 2);
for(int i = 0; i < entities.size; i++){
entities.get(i).update(delta);
}
}
public static void render (SpriteBatch batch) {
mapRenderer.setView(Objects.GAME_CAMERA);
mapRenderer.render();
boolean needToEnd = false;
if(!batch.isDrawing()) {
batch.begin();
needToEnd = true;
}
for(int i = 0; i < entities.size; i++){
entities.get(i).draw(batch);
}
if(needToEnd){
batch.end();
}
}
public static void load (String tmxLevel, World world) {
Level.world = world;
tiledMap = new TmxMapLoader().load("levels/" + tmxLevel);
mapRenderer = new OrthogonalTiledMapRenderer(tiledMap);
addBox2D();
setContactListener();
entities = new Array<Entity>();
}
public static void addEntity(Entity e){
checkIfPlayer(e);
entities.add(e);
}
public static void addEntities(Entity[] e){
checkIfPlayer(e);
entities.addAll(e);
}
public static void addEntities(Array<Entity> e){
checkIfPlayer(e);
entities.addAll(e);
}
public static void removeEntity(Entity e){
entities.removeValue(e, true);
}
public static void removeEntities(Entity[] e2){
for(Entity e : e2) {
entities.removeValue(e, true);
}
}
public static void removeEntities(Array<Entity> e){
entities.removeAll(e, true);
}
public static World getWorld () {
return world;
}
private static void checkIfPlayer(Entity e){
if(e instanceof Player){
player = (Player) e;
}
}
private static void checkIfPlayer(Entity[] e2){
for(Entity e : e2){
if(e instanceof Player){
player = (Player)e;
}
}
}
private static void checkIfPlayer(Array<Entity> e2){
for(int i = 0; i < e2.size; i++){
if(e2.get(i) instanceof Player) {
player = (Player) e2.get(i);
}
}
}
// Shall fix this
private static void addBox2D () {
float tileSize = 0;
ArrayList<Box2DCell> cells = new ArrayList<Box2DCell>();
MapLayer mapLayer = tiledMap.getLayers().get("collision");
TiledMapTileLayer layer = (TiledMapTileLayer)mapLayer;
tileSize = layer.getTileWidth();
for (int y = 0; y < layer.getHeight(); y++) {
for (int x = 0; x < layer.getWidth(); x++) {
Cell cell = layer.getCell(x, y);
if (cell == null) {
continue;
}
if (cell.getTile() == null) {
continue;
}
cells.add(new Box2DCell(cell, x, y));
}
}
// l J
int i = cells.size() - 1;
ArrayList<Box2DCell> yCells = new ArrayList<Box2DCell>();
while (true) {
Box2DCell c = cells.get(0);
float x = c.x;
while (true) {
Box2DCell c2 = findCellToRight(cells, c, x);
if (c2 != null) {
cells.remove(c2);
x++;
i
} else {
break;
}
}
float x2 = x - c.x + 1;
if (x2 - 1 >= 1) {
BodyDef bodyDef = new BodyDef();
bodyDef.position.x = Pixels.toMeters(c.x * tileSize + x2 * tileSize / 2);
bodyDef.position.y = Pixels.toMeters(c.y * tileSize + tileSize / 2);
bodyDef.type = BodyType.StaticBody;
Body body = world.createBody(bodyDef);
body.setUserData("tile");
PolygonShape shape = new PolygonShape();
shape.setAsBox(Pixels.toMeters(x2 * tileSize / 2), Pixels.toMeters(tileSize / 2));
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.friction = 0;
Fixture f = body.createFixture(fixtureDef);
f.setUserData("tile");
}
if (x2 - 1 == 0) {
yCells.add(c);
}
cells.remove(c);
if (cells.size() <= 0) {
break;
}
}
// l l
// l l
// L _J
if (yCells.size() != 0) {
while (true) {
Box2DCell c = yCells.get(0);
float y = c.y;
while (true) {
Box2DCell c2 = findCellToDown(yCells, c, y);
if (c2 != null) {
yCells.remove(c2);
y++;
} else {
break;
}
}
float y2 = y - c.y + 1;
if (y2 == 0) {
y2 = 1;
}
BodyDef bodyDef = new BodyDef();
bodyDef.position.x = Pixels.toMeters(c.x * tileSize + tileSize / 2);
bodyDef.position.y = Pixels.toMeters(c.y * tileSize + y2 * tileSize / 2);
bodyDef.type = BodyType.StaticBody;
Body body = world.createBody(bodyDef);
body.setUserData("tile");
PolygonShape shape = new PolygonShape();
shape.setAsBox(Pixels.toMeters(tileSize / 2), Pixels.toMeters(y2 * tileSize / 2));
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.friction = 0;
Fixture f = body.createFixture(fixtureDef);
f.setUserData("tile");
yCells.remove(c);
if (yCells.size() <= 0) {
break;
}
}
}
}
private static Box2DCell findCellToRight (ArrayList<Box2DCell> cells, Box2DCell c, float x) {
for (int i = 0; i < cells.size(); i++) {
if (cells.get(i) == c) {
continue;
}
if (cells.get(i).y == c.y && cells.get(i).x == x + 1) {
Box2DCell c2 = cells.get(i);
cells.remove(i);
return c2;
}
}
return null;
}
private static Box2DCell findCellToDown (ArrayList<Box2DCell> cells, Box2DCell c, float y) {
for (int i = 0; i < cells.size(); i++) {
if (cells.get(i) == c) {
continue;
}
if (cells.get(i).y == y + 1 && cells.get(i).x == c.x) {
Box2DCell c2 = cells.get(i);
cells.remove(i);
return c2;
}
}
return null;
}
private static void setContactListener () {
world.setContactListener(new ContactListener() {
@Override
public void beginContact (Contact contact) {
}
@Override
public void endContact (Contact contact) {
}
@Override
public void preSolve (Contact contact, Manifold oldManifold) {
}
@Override
public void postSolve (Contact contact, ContactImpulse impulse) {
}
});
}
private static boolean check (Entity e, Contact c) {
Fixture a = c.getFixtureA();
Fixture b = c.getFixtureB();
if (a.getUserData() == null) {
// System.out.println("A fixture you just collied with or you's user data == null, fix this");
return false;
}
if (b.getUserData() == null) {
// System.out.println("B fixture you just collied with or you's user data == null, fix this");
return false;
}
if (a.getUserData().equals(e.getFixture().getUserData())) {
return true;
} else if (b.getUserData().equals(e.getFixture().getUserData())) {
return true;
}
return false;
}
}
|
package org.python.types;
import java.util.Locale;
public class Float extends org.python.types.Object {
private static final long NEGATIVE_ZERO_RAW_BITS = Double.doubleToRawLongBits(-0.0);
public double value;
/**
* A utility method to update the internal value of this object.
*
* Used by __i*__ operations to do an in-place operation.
* obj must be of type org.python.types.Float
*/
void setValue(org.python.Object obj) {
this.value = ((org.python.types.Float) obj).value;
}
public java.lang.Object toJava() {
return this.value;
}
public org.python.Object byValue() {
return new org.python.types.Float(this.value);
}
public int hashCode() {
return new java.lang.Double(this.value).hashCode();
}
public Float(float value) {
super();
this.value = (double) value;
}
public Float(double value) {
super();
this.value = value;
}
// public org.python.Object __new__() {
// throw new org.python.exceptions.NotImplementedError("float.__new__() has not been implemented.");
// public org.python.Object __init__() {
// throw new org.python.exceptions.NotImplementedError("float.__init__() has not been implemented.");
@org.python.Method(
__doc__ = ""
)
public org.python.types.Str __repr__() {
double value = this.value;
String result;
if (Double.isNaN(value)) {
result = "nan";
} else if (Double.isInfinite(value)) {
if (value > 0) {
result = "inf";
} else {
result = "-inf";
}
} else {
result = java.lang.Double.toString(this.value);
String format = "%.17g";
result = String.format(Locale.US, format, value);
int dot_pos = result.indexOf(".");
int e_pos = result.indexOf("e");
if (dot_pos != -1) {
// Remove trailing zeroes in the fractional part
int last_zero = -1;
int i;
for (i = dot_pos + 1; i < result.length(); i++) {
char c = result.charAt(i);
if (i == e_pos) {
break;
} else if (c == '0') {
if (last_zero == -1) {
last_zero = i;
}
} else {
last_zero = -1;
}
}
if (last_zero != -1) {
if (last_zero == dot_pos + 1) {
// Everything after the dot is zeros
if (e_pos == -1) {
// If there's no "e", leave ".0" at the end
last_zero += 1;
} else {
// If there is an "e", nuke the dot as well
last_zero -= 1;
}
}
result = result.substring(0, last_zero) + result.substring(i);
}
}
}
return new org.python.types.Str(result);
}
@org.python.Method(
__doc__ = ""
)
public org.python.types.Str __format__(org.python.Object format_string) {
throw new org.python.exceptions.NotImplementedError("float.__format__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __lt__(org.python.Object other) {
if (other instanceof org.python.types.Int) {
long other_val = ((org.python.types.Int) other).value;
return new org.python.types.Bool(this.value < ((double) other_val));
} else if (other instanceof org.python.types.Float) {
double other_val = ((org.python.types.Float) other).value;
return new org.python.types.Bool(this.value < other_val);
} else if (other instanceof org.python.types.Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Bool(this.value < 1.0);
} else {
return new org.python.types.Bool(this.value < 0.0);
}
}
throw new org.python.exceptions.TypeError("unorderable types: float() < " + other.typeName() + "()");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __le__(org.python.Object other) {
if (other instanceof org.python.types.Int) {
return new org.python.types.Bool(this.value <= ((double)((org.python.types.Int) other).value));
} else if (other instanceof Float) {
return new org.python.types.Bool(this.value <= ((org.python.types.Float) other).value);
} else if (other instanceof Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Bool(this.value <= 1.0);
} else {
return new org.python.types.Bool(this.value <= 0.0);
}
}
throw new org.python.exceptions.TypeError("unorderable types: float() <= " + other.typeName() + "()");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __eq__(org.python.Object other) {
if (other instanceof org.python.types.Int) {
return new org.python.types.Bool(this.value == ((double)((org.python.types.Int) other).value));
} else if (other instanceof org.python.types.Float) {
return new org.python.types.Bool(this.value == ((org.python.types.Float) other).value);
} else if (other instanceof org.python.types.Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Bool(this.value == 1.0);
} else {
return new org.python.types.Bool(this.value == 0.0);
}
} else if (other instanceof org.python.types.NoneType) {
return new org.python.types.Bool(false);
} else if (other instanceof org.python.types.List) {
return new org.python.types.Bool(false);
} else if (other instanceof org.python.types.Str) {
return new org.python.types.Bool(false);
}
throw new org.python.exceptions.TypeError("unorderable types: float() == " + other.typeName() + "()");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __ne__(org.python.Object other) {
if (other instanceof org.python.types.Int || other instanceof org.python.types.Float ||
other instanceof org.python.types.Bool || other instanceof org.python.types.NoneType ||
other instanceof org.python.types.Str) {
if (((org.python.types.Bool) this.__eq__((org.python.Object) other)).value) {
return new org.python.types.Bool(false);
} else if (!((org.python.types.Bool) this.__eq__((org.python.Object) other)).value) {
return new org.python.types.Bool(true);
}
}
throw new org.python.exceptions.TypeError("unorderable types: float() == " + other.typeName() + "()");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __gt__(org.python.Object other) {
if (other instanceof org.python.types.Int) {
return new org.python.types.Bool(this.value > ((double)((org.python.types.Int) other).value));
} else if (other instanceof Float) {
return new org.python.types.Bool(this.value > ((org.python.types.Float) other).value);
} else if (other instanceof Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Bool(this.value > 1.0);
} else {
return new org.python.types.Bool(this.value > 0.0);
}
}
throw new org.python.exceptions.TypeError("unorderable types: float() > " + other.typeName() + "()");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __ge__(org.python.Object other) {
if (other instanceof org.python.types.Int) {
return new org.python.types.Bool(this.value >= ((double)((org.python.types.Int) other).value));
} else if (other instanceof Float) {
return new org.python.types.Bool(this.value >= ((org.python.types.Float) other).value);
} else if (other instanceof Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Bool(this.value >= 1.0);
} else {
return new org.python.types.Bool(this.value >= 0.0);
}
}
throw new org.python.exceptions.TypeError("unorderable types: float() >= " + other.typeName() + "()");
}
@org.python.Method(
__doc__ = ""
)
public org.python.types.Bool __bool__() {
return new org.python.types.Bool(this.value != 0.0);
}
public boolean __setattr_null(java.lang.String name, org.python.Object value) {
// Builtin types can't have attributes set on them.
return false;
}
@org.python.Method(
__doc__ = ""
)
public org.python.types.List __dir__() {
throw new org.python.exceptions.NotImplementedError("float.__dir__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __add__(org.python.Object other) {
if (other instanceof org.python.types.Int) {
long other_val = ((org.python.types.Int) other).value;
return new org.python.types.Float(this.value + ((double) other_val));
} else if (other instanceof org.python.types.Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Float(this.value + 1.0);
}
return new org.python.types.Float(this.value);
} else if (other instanceof org.python.types.Float) {
double other_val = ((org.python.types.Float) other).value;
return new org.python.types.Float(this.value + other_val);
}
throw new org.python.exceptions.TypeError("unsupported operand type(s) for +: 'float' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __sub__(org.python.Object other) {
if (other instanceof org.python.types.Int) {
long other_val = ((org.python.types.Int) other).value;
return new org.python.types.Float(this.value - ((double) other_val));
} else if (other instanceof org.python.types.Float) {
double other_val = ((org.python.types.Float) other).value;
return new org.python.types.Float(this.value - other_val);
} else if (other instanceof org.python.types.Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Float(this.value - 1.0);
}
return new org.python.types.Float(this.value);
}
throw new org.python.exceptions.TypeError("unsupported operand type(s) for -: 'float' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __mul__(org.python.Object other) {
if (other instanceof org.python.types.Str) {
throw new org.python.exceptions.TypeError("can't multiply sequence by non-int of type '" + "float" + "'");
} else if (other instanceof org.python.types.Int) {
return new org.python.types.Float(this.value * ((org.python.types.Int) other).value);
} else if (other instanceof org.python.types.Float) {
return new org.python.types.Float(((double) this.value) * ((org.python.types.Float) other).value);
} else if (other instanceof org.python.types.Bool) {
return new org.python.types.Float(this.value * (((org.python.types.Bool) other).value ? 1 : 0));
} else if (other instanceof org.python.types.Dict) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for *: 'float' and '" + other.typeName() + "'");
} else if (other instanceof org.python.types.NoneType) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for *: 'float' and '" + other.typeName() + "'");
} else if (other instanceof org.python.types.Set) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for *: 'float' and '" + other.typeName() + "'");
}
throw new org.python.exceptions.NotImplementedError("float.__mul__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __truediv__(org.python.Object other) {
if (other instanceof org.python.types.Int) {
long other_val = ((org.python.types.Int) other).value;
if (other_val == 0) {
throw new org.python.exceptions.ZeroDivisionError("float division by zero");
}
return new org.python.types.Float(this.value / ((double) other_val));
} else if (other instanceof org.python.types.Float) {
double other_val = ((org.python.types.Float) other).value;
if (other_val == 0.0) {
throw new org.python.exceptions.ZeroDivisionError("float division by zero");
}
return new org.python.types.Float(this.value / other_val);
} else if (other instanceof org.python.types.Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Float(this.value);
} else {
throw new org.python.exceptions.ZeroDivisionError("float division by zero");
}
}
throw new org.python.exceptions.TypeError("unsupported operand type(s) for /: 'float' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __floordiv__(org.python.Object other) {
if (other instanceof org.python.types.Int) {
if (((org.python.types.Int) other).value == 0) {
throw new org.python.exceptions.ZeroDivisionError("float divmod()");
}
return new org.python.types.Float(Math.floor((double) this.value / ((org.python.types.Int) other).value));
} else if (other instanceof org.python.types.Float) {
if (((org.python.types.Float) other).value == 0.0) {
throw new org.python.exceptions.ZeroDivisionError("float divmod()");
}
return new org.python.types.Float(Math.floor(this.value / ((org.python.types.Float) other).value));
} else if (other instanceof org.python.types.Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Float(Math.floor(this.value));
} else {
throw new org.python.exceptions.ZeroDivisionError("float divmod()");
}
}
throw new org.python.exceptions.TypeError("unsupported operand type(s) for //: 'float' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __mod__(org.python.Object other) {
try {
if (other instanceof org.python.types.Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Float(this.value - Math.floor(this.value));
} else {
throw new org.python.exceptions.ZeroDivisionError("float modulo");
}
} else if (other instanceof org.python.types.Int) {
long other_val = ((org.python.types.Int) other).value;
if (other_val == 0) {
throw new org.python.exceptions.ZeroDivisionError("float modulo");
} else {
// This translates to (a % b + b) %b
// This expression works as the result of (a % b) is necessarily lower than b,
// no matter if a is positive or negative. Adding b takes care of the negative
// values of a, since (a % b) is a negative value between -b and 0, (a % b + b)
// is necessarily lower than b and positive. The last modulo is there in case a
// was positive to begin with, since if a is positive (a % b + b) would become
// larger than b. Therefore, (a % b + b) % b turns it into smaller than b again
// (and doesn't affect negative a values).
double result = (((((double) this.value) % other_val) + other_val) % other_val);
return new org.python.types.Float(result);
}
} else if (other instanceof org.python.types.Float) {
double other_val = ((org.python.types.Float) other).value;
if (other_val == 0.0) {
throw new org.python.exceptions.ZeroDivisionError("float modulo");
} else {
double result = (((((double) this.value) % other_val) + other_val) % other_val);
return new org.python.types.Float(result);
}
}
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for %: 'float' and '" + other.typeName() + "'");
}
throw new org.python.exceptions.TypeError("unsupported operand type(s) for %: 'float' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __divmod__(org.python.Object other) {
try {
java.util.List<org.python.Object> data = new java.util.ArrayList<org.python.Object>();
data.add(this.__floordiv__(other));
data.add(this.__mod__(other));
return new org.python.types.Tuple(data);
} catch (org.python.exceptions.TypeError ae) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for divmod(): '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __pow__(org.python.Object other, org.python.Object modulo) {
if (modulo != null) {
throw new org.python.exceptions.NotImplementedError("float.__pow__() with modulo has not been implemented");
}
if (other instanceof org.python.types.Int) {
long other_val = ((org.python.types.Int) other).value;
if (other_val < 0) {
if (this.value == 0) {
throw new org.python.exceptions.ZeroDivisionError("0.0 cannot be raised to a negative power");
}
double result = 1.0;
for (long count = 0; count < -other_val; count++) {
result *= this.value;
}
return new org.python.types.Float(1.0 / result);
} else {
return new org.python.types.Float(java.lang.Math.pow(this.value, other_val));
}
} else if (other instanceof org.python.types.Float) {
double other_val = ((org.python.types.Float) other).value;
if (this.value == 0 && other_val < 0.0) {
throw new org.python.exceptions.ZeroDivisionError("0.0 cannot be raised to a negative power");
}
// TODO: if this.value < 0 && other_val is not an integer, this will be a Complex result, so change this.value to Complex and delegate it out
// return (new org.python.types.Complex(this.value, 0)).__pow__(other, modulo);
return new org.python.types.Float(java.lang.Math.pow(this.value, other_val));
} else if (other instanceof org.python.types.Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Float(this.value);
} else {
return new org.python.types.Float(1);
}
}
throw new org.python.exceptions.TypeError("unsupported operand type(s) for ** or pow(): 'float' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __radd__(org.python.Object other) {
throw new org.python.exceptions.NotImplementedError("float.__radd__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __rsub__(org.python.Object other) {
throw new org.python.exceptions.NotImplementedError("float.__rsub__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __rmul__(org.python.Object other) {
throw new org.python.exceptions.NotImplementedError("float.__rmul__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __rtruediv__(org.python.Object other) {
throw new org.python.exceptions.NotImplementedError("float.__rtruediv__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __rfloordiv__(org.python.Object other) {
throw new org.python.exceptions.NotImplementedError("float.__rfloordiv__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __rmod__(org.python.Object other) {
throw new org.python.exceptions.NotImplementedError("float.__rmod__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __rdivmod__(org.python.Object other) {
throw new org.python.exceptions.NotImplementedError("float.__rdivmod__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __rpow__(org.python.Object other) {
throw new org.python.exceptions.NotImplementedError("float.__rpow__() has not been implemented.");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __iadd__(org.python.Object other) {
if (other instanceof org.python.types.Int) {
long other_val = ((org.python.types.Int) other).value;
return new org.python.types.Float(this.value += ((double) other_val));
} else if (other instanceof org.python.types.Bool) {
if (((org.python.types.Bool) other).value) {
return new org.python.types.Float(this.value += 1.0);
}
return new org.python.types.Float(this.value);
} else if (other instanceof org.python.types.Float) {
double other_val = ((org.python.types.Float) other).value;
return new org.python.types.Float(this.value + other_val);
}
throw new org.python.exceptions.TypeError("unsupported operand type(s) for +=: 'float' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __ilshift__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for <<=: 'float' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __irshift__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for >>=: 'float' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __neg__() {
return new org.python.types.Float(-this.value);
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __pos__() {
return new org.python.types.Float(this.value);
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __abs__() {
if (this.value < 0.0) {
return new org.python.types.Float(-this.value);
} else {
return new org.python.types.Float(this.value);
}
}
@org.python.Method(
__doc__ = ""
)
public org.python.types.Int __int__() {
return new org.python.types.Int((int) this.value);
}
@org.python.Method(
__doc__ = ""
)
public org.python.types.Float __float__() {
return new org.python.types.Float(this.value);
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __round__(org.python.Object ndigits) {
if(ndigits instanceof org.python.types.Int) {
long wholeNumber;
double fractionalPart;
if (((org.python.types.Int)ndigits).value != 0) {
throw new org.python.exceptions.NotImplementedError("float.__round__() with ndigits has not been implemented");
} else {
wholeNumber = (long) this.value;
fractionalPart = this.value - wholeNumber;
}
int sign;
if (wholeNumber >= 0) {
sign = 1;
} else {
sign = -1;
}
if (Math.abs(fractionalPart) < 0.5) {
return new org.python.types.Int(sign * Math.abs(wholeNumber));
} else if (Math.abs(fractionalPart) > 0.5) {
return new org.python.types.Int(sign * (Math.abs(wholeNumber) + 1));
} else {
if (wholeNumber % 2 == 0) {
return new org.python.types.Int(sign * Math.abs(wholeNumber));
} else {
return new org.python.types.Int(sign * (Math.abs(wholeNumber) + 1));
}
}
} else {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for round(): 'float' and '" + ndigits.typeName() + "'");
}
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __invert__() {
throw new org.python.exceptions.TypeError("bad operand type for unary ~: 'float'");
}
@org.python.Method(
__doc__ = ""
)
public org.python.types.Str hex() {
String result;
if (Double.isNaN(this.value)) {
result = "nan";
} else if (Double.isInfinite(this.value)) {
if (this.value > 0) {
result = "inf";
} else {
result = "-inf";
}
} else {
long bits = Double.doubleToLongBits(this.value);
StringBuilder buffer = new StringBuilder();
boolean sign = (bits >> 63) != 0;
long exponent = (bits >> 52) & 0x7ffL;
long mantissa = bits & 0x000fffffffffffffL;
if (sign) {
buffer.append("-");
}
buffer.append("0x");
String hexMantissa = Long.toHexString(mantissa);
if (exponent == 0) {
buffer.append("0.");
} else {
buffer.append("1.");
}
if (exponent == 0 && mantissa == 0) {
// for some reason the matissa is not padded in this case
buffer.append(hexMantissa);
buffer.append("p+0");
} else {
buffer.append("0000000000000".substring(hexMantissa.length()));
buffer.append(hexMantissa);
if (exponent == 0) {
exponent = -1022;
} else {
exponent -= 1023;
}
if (exponent >= 0) {
buffer.append("p+");
buffer.append(Long.toString(exponent));
} else {
buffer.append("p-");
buffer.append(Long.toString(-exponent));
}
}
result = buffer.toString();
}
return new org.python.types.Str(result);
}
}
|
package aQute.bnd.osgi;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;
import java.util.jar.*;
import java.util.regex.*;
import aQute.bnd.header.*;
import aQute.bnd.service.*;
import aQute.bnd.service.url.*;
import aQute.bnd.version.*;
import aQute.lib.collections.*;
import aQute.lib.hex.*;
import aQute.lib.io.*;
import aQute.lib.strings.*;
import aQute.lib.utf8properties.*;
import aQute.libg.cryptography.*;
import aQute.libg.generics.*;
import aQute.service.reporter.*;
public class Processor extends Domain implements Reporter, Registry, Constants, Closeable {
static final int BUFFER_SIZE = IOConstants.PAGE_SIZE * 1;
static Pattern PACKAGES_IGNORED = Pattern.compile("(java\\.lang\\.reflect|sun\\.reflect).*");
static ThreadLocal<Processor> current = new ThreadLocal<Processor>();
static ExecutorService executor = Executors.newCachedThreadPool();
static Random random = new Random();
// TODO handle include files out of date
// TODO make splitter skip eagerly whitespace so trim is not necessary
public final static String LIST_SPLITTER = "\\s*,\\s*";
final List<String> errors = new ArrayList<String>();
final List<String> warnings = new ArrayList<String>();
final Set<Object> basicPlugins = new HashSet<Object>();
private final Set<Closeable> toBeClosed = new HashSet<Closeable>();
Set<Object> plugins;
boolean pedantic;
boolean trace;
boolean exceptions;
boolean fileMustExist = true;
private File base = new File("").getAbsoluteFile();
Properties properties;
String profile;
private Macro replacer;
private long lastModified;
private File propertiesFile;
private boolean fixup = true;
long modified;
Processor parent;
List<File> included;
CL pluginLoader;
Collection<String> filter;
HashSet<String> missingCommand;
Boolean strict;
boolean fixupMessages;
public static class FileLine {
public static final FileLine DUMMY = new FileLine(null, 0, 0);
final public File file;
final public int line;
final public int length;
public FileLine(File file, int line, int length) {
this.file = file;
this.line = line;
this.length = length;
}
public void set(SetLocation sl) {
sl.file(file.getAbsolutePath());
sl.line(line);
sl.length(length);
}
}
public Processor() {
properties = new UTF8Properties();
}
public Processor(Properties parent) {
properties = new UTF8Properties(parent);
}
public Processor(Processor child) {
this(child.properties);
this.parent = child;
}
public void setParent(Processor processor) {
this.parent = processor;
Properties ext = new UTF8Properties(processor.properties);
ext.putAll(this.properties);
this.properties = ext;
}
public Processor getParent() {
return parent;
}
public Processor getTop() {
if (parent == null)
return this;
return parent.getTop();
}
public void getInfo(Reporter processor, String prefix) {
if (prefix == null)
prefix = getBase() + " :";
if (isFailOk())
addAll(warnings, processor.getErrors(), prefix, processor);
else
addAll(errors, processor.getErrors(), prefix, processor);
addAll(warnings, processor.getWarnings(), prefix, processor);
processor.getErrors().clear();
processor.getWarnings().clear();
}
public void getInfo(Reporter processor) {
getInfo(processor, "");
}
private void addAll(List<String> to, List<String> from, String prefix, Reporter reporter) {
try {
for (String message : from) {
String newMessage = prefix + message;
to.add(newMessage);
Location location = reporter.getLocation(message);
if (location != null) {
SetLocation newer = location(newMessage);
for (Field f : newer.getClass().getFields()) {
if (!"message".equals(f.getName())) {
f.set(newer, f.get(location));
}
}
}
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* A processor can mark itself current for a thread.
*
* @return
*/
private Processor current() {
Processor p = current.get();
if (p == null)
return this;
return p;
}
public SetLocation warning(String string, Object... args) {
fixupMessages = false;
Processor p = current();
String s = formatArrays(string, args);
if (!p.warnings.contains(s))
p.warnings.add(s);
p.signal();
return location(s);
}
public SetLocation error(String string, Object... args) {
fixupMessages = false;
Processor p = current();
try {
if (p.isFailOk())
return p.warning(string, args);
String s = formatArrays(string, args == null ? new Object[0] : args);
if (!p.errors.contains(s))
p.errors.add(s);
return location(s);
}
finally {
p.signal();
}
}
public void progress(float progress, String format, Object... args) {
if (progress > 0)
format = String.format("[%2d] %s%n", (int) progress, format);
else
format = String.format("%s%n", format);
System.err.printf(format, args);
}
public void progress(String format, Object... args) {
progress(-1f, format, args);
}
public SetLocation exception(Throwable t, String format, Object... args) {
return error(format, t, args);
}
public SetLocation error(String string, Throwable t, Object... args) {
Processor p = current();
try {
if (p.exceptions) {
printExceptionSummary(t, System.err);
}
if (p.isFailOk()) {
return p.warning(string + ": " + t, args);
}
p.errors.add("Exception: " + t.getMessage());
String s = formatArrays(string, args == null ? new Object[0] : args);
if (!p.errors.contains(s))
p.errors.add(s);
return location(s);
}
finally {
p.signal();
}
}
public int printExceptionSummary(Throwable e, PrintStream out) {
if (e == null) {
return 0;
}
int count = 10;
int n = printExceptionSummary(e.getCause(), out);
if (n == 0) {
out.println("Root cause: " + e.getMessage() + " :" + e.getClass().getName());
count = Integer.MAX_VALUE;
} else {
out.println("Rethrown from: " + e.toString());
}
out.println();
printStackTrace(e, count, out);
System.err.println();
return n + 1;
}
public void printStackTrace(Throwable e, int count, PrintStream out) {
StackTraceElement st[] = e.getStackTrace();
String previousPkg = null;
boolean shorted = false;
if (count < st.length) {
shorted = true;
count
}
for (int i = 0; i < count && i < st.length; i++) {
String cname = st[i].getClassName();
String file = st[i].getFileName();
String method = st[i].getMethodName();
int line = st[i].getLineNumber();
String pkg = Descriptors.getPackage(cname);
if (PACKAGES_IGNORED.matcher(pkg).matches())
continue;
String shortName = Descriptors.getShortName(cname);
if (pkg.equals(previousPkg))
pkg = "''";
else
pkg += "";
if (file.equals(shortName + ".java"))
file = "";
else
file = " (" + file + ")";
String l;
if (st[i].isNativeMethod())
l = "native";
else if (line > 0)
l = "" + line;
else
l = "";
out.printf(" %10s %-40s %s %s%n", l, shortName + "." + method, pkg, file);
previousPkg = pkg;
}
if (shorted)
out.println("...");
}
public void signal() {}
public List<String> getWarnings() {
fixupMessages();
return warnings;
}
public List<String> getErrors() {
fixupMessages();
return errors;
}
/**
* Standard OSGi header parser.
*
* @param value
* @return
*/
static public Parameters parseHeader(String value, Processor logger) {
return new Parameters(value, logger);
}
public Parameters parseHeader(String value) {
return new Parameters(value, this);
}
public void addClose(Closeable jar) {
assert jar != null;
toBeClosed.add(jar);
}
public void removeClose(Closeable jar) {
assert jar != null;
toBeClosed.remove(jar);
}
public boolean isPedantic() {
return current().pedantic;
}
public void setPedantic(boolean pedantic) {
this.pedantic = pedantic;
}
public void use(Processor reporter) {
setPedantic(reporter.isPedantic());
setTrace(reporter.isTrace());
setFailOk(reporter.isFailOk());
}
public static File getFile(File base, String file) {
return IO.getFile(base, file);
}
public File getFile(String file) {
return getFile(base, file);
}
/**
* Return a list of plugins that implement the given class.
*
* @param clazz
* Each returned plugin implements this class/interface
* @return A list of plugins
*/
public <T> List<T> getPlugins(Class<T> clazz) {
List<T> l = new ArrayList<T>();
Set<Object> all = getPlugins();
for (Object plugin : all) {
if (clazz.isInstance(plugin))
l.add(clazz.cast(plugin));
}
return l;
}
/**
* Returns the first plugin it can find of the given type.
*
* @param <T>
* @param clazz
* @return
*/
public <T> T getPlugin(Class<T> clazz) {
Set<Object> all = getPlugins();
for (Object plugin : all) {
if (clazz.isInstance(plugin))
return clazz.cast(plugin);
}
return null;
}
/**
* Return a list of plugins. Plugins are defined with the -plugin command.
* They are class names, optionally associated with attributes. Plugins can
* implement the Plugin interface to see these attributes. Any object can be
* a plugin.
*
* @return
*/
public Set<Object> getPlugins() {
synchronized (this) {
if (this.plugins != null)
return this.plugins;
plugins = new LinkedHashSet<Object>();
missingCommand = new HashSet<String>();
}
// The owner of the plugin is always in there.
plugins.add(this);
setTypeSpecificPlugins(plugins);
if (parent != null)
plugins.addAll(parent.getPlugins());
// We only use plugins now when they are defined on our level
// and not if it is in our parent. We inherit from our parent
// through the previous block.
String spe = getProperty(PLUGIN);
if (NONE.equals(spe))
return new LinkedHashSet<Object>();
spe = mergeProperties(PLUGIN);
String pluginPath = mergeProperties(PLUGINPATH);
loadPlugins(plugins, spe, pluginPath);
addExtensions(plugins);
for (RegistryDonePlugin rdp : getPlugins(RegistryDonePlugin.class)) {
try {
rdp.done();
}
catch (Exception e) {
error("Calling done on %s, gives an exception %s", rdp, e);
}
}
return this.plugins;
}
/**
* Is called when all plugins are loaded
*
* @param plugins
*/
protected void addExtensions(Set<Object> plugins) {
}
/**
* Magic to load the plugins. This is quite tricky actually since we allow
* plugins to be downloaded (this is mainly intended for repositories since
* in general plugins should use extensions, however to bootstrap the
* extensions we need more). Since downloads might need plugins for
* passwords and protocols we need to first load the paths specified on the
* plugin clause, then check if there are any local plugins (starting with
* aQute.bnd and be able to load from our own class loader).
* <p>
* After that, we load the plugin paths, these can use the built in
* connectors.
* <p>
* Last but not least, we load the remaining plugins.
*
* @param instances
* @param pluginString
*/
protected void loadPlugins(Set<Object> instances, String pluginString, String pluginPathString) {
Parameters plugins = new Parameters(pluginString);
CL loader = getLoader();
// First add the plugin-specific paths from their path: directives
for (Entry<String,Attrs> entry : plugins.entrySet()) {
String key = removeDuplicateMarker(entry.getKey());
String path = entry.getValue().get(PATH_DIRECTIVE);
if (path != null) {
String parts[] = path.split("\\s*,\\s*");
try {
for (String p : parts) {
File f = getFile(p).getAbsoluteFile();
loader.add(f.toURI().toURL());
}
}
catch (Exception e) {
error("Problem adding path %s to loader for plugin %s. Exception: (%s)", path, key, e);
}
}
}
// Try to load any plugins that are local
// these must start with aQute.bnd.* and
// and be possible to load. The main intention
// of this code is to load the URL connectors so that
// any access to remote plugins can use the connector
// model.
Set<String> loaded = new HashSet<String>();
for (Entry<String,Attrs> entry : plugins.entrySet()) {
String className = removeDuplicateMarker(entry.getKey());
Attrs attrs = entry.getValue();
trace("Trying pre-plugin %s", className);
Object plugin = loadPlugin(getClass().getClassLoader(), attrs, className, true);
if (plugin != null) {
// with the marker!!
loaded.add(entry.getKey());
instances.add(plugin);
}
}
// Make sure we load each plugin only once
// by removing the entries that were successfully loaded
plugins.keySet().removeAll(loaded);
loadPluginPath(instances, pluginPathString, loader);
// Load the remaining plugins
for (Entry<String,Attrs> entry : plugins.entrySet()) {
String className = removeDuplicateMarker(entry.getKey());
Attrs attrs = entry.getValue();
trace("Loading secondary plugin %s", className);
// We can defer the error if the plugin specifies
// a command name. In that case, we'll verify that
// a bnd file does not contain any references to a
// plugin
// command. The reason this feature was added was
// to compile plugin classes with the same build.
String commands = attrs.get(COMMAND_DIRECTIVE);
Object plugin = loadPlugin(loader, attrs, className, commands != null);
if (plugin != null)
instances.add(plugin);
else {
if (commands == null)
error("Cannot load the plugin %s", className);
else {
Collection<String> cs = split(commands);
missingCommand.addAll(cs);
}
}
}
}
/**
* Add the @link {@link Constants#PLUGINPATH} entries (which are file names)
* to the class loader. If this file does not exist, and there is a
* {@link Constants#PLUGINPATH_URL_ATTR} attribute then we download it first
* from that url. You can then also specify a
* {@link Constants#PLUGINPATH_SHA1_ATTR} attribute to verify the file.
*
* @see PLUGINPATH
* @param pluginPath
* the clauses for the plugin path
* @param loader
* The class loader to extend
*/
private void loadPluginPath(Set<Object> instances, String pluginPath, CL loader) {
Parameters pluginpath = new Parameters(pluginPath);
nextClause: for (Entry<String,Attrs> entry : pluginpath.entrySet()) {
File f = getFile(entry.getKey()).getAbsoluteFile();
if (!f.isFile()) {
// File does not exist! Check if we need to download
String url = entry.getValue().get(PLUGINPATH_URL_ATTR);
if (url != null) {
try {
trace("downloading %s to %s", url, f.getAbsoluteFile());
URL u = new URL(url);
URLConnection connection = u.openConnection();
// Allow the URLCOnnectionHandlers to interact with the
// connection so they can sign it or decorate it with
// a password etc.
for (Object plugin : instances) {
if (plugin instanceof URLConnectionHandler) {
URLConnectionHandler handler = (URLConnectionHandler) plugin;
if (handler.matches(u))
handler.handle(connection);
}
}
// Copy the url to the file
f.getParentFile().mkdirs();
IO.copy(connection.getInputStream(), f);
// If there is a sha specified, we verify the download
// of the
// the file.
String digest = entry.getValue().get(PLUGINPATH_SHA1_ATTR);
if (digest != null) {
if (Hex.isHex(digest.trim())) {
byte[] sha1 = Hex.toByteArray(digest);
byte[] filesha1 = SHA1.digest(f).digest();
if (!Arrays.equals(sha1, filesha1)) {
error("Plugin path: %s, specified url %s and a sha1 but the file does not match the sha",
entry.getKey(), url);
}
} else {
error("Plugin path: %s, specified url %s and a sha1 '%s' but this is not a hexadecimal",
entry.getKey(), url, digest);
}
}
}
catch (Exception e) {
error("Failed to download plugin %s from %s, error %s", entry.getKey(), url, e);
continue nextClause;
}
} else {
error("No such file %s from %s and no 'url' attribute on the path so it can be downloaded",
entry.getKey(), this);
continue nextClause;
}
}
trace("Adding %s to loader for plugins", f);
try {
loader.add(f.toURI().toURL());
}
catch (MalformedURLException e) {
// Cannot happen since every file has a correct url
}
}
}
/**
* Load a plugin and customize it. If the plugin cannot be loaded then we
* return null.
*
* @param loader
* Name of the loader
* @param attrs
* @param className
* @return
*/
private Object loadPlugin(ClassLoader loader, Attrs attrs, String className, boolean ignoreError) {
try {
Class< ? > c = loader.loadClass(className);
Object plugin = c.newInstance();
customize(plugin, attrs);
if (plugin instanceof Closeable) {
addClose((Closeable) plugin);
}
return plugin;
}
catch (NoClassDefFoundError e) {
if (!ignoreError)
error("Failed to load plugin %s;%s, error: %s ", className, attrs, e.getMessage());
}
catch (ClassNotFoundException e) {
if (!ignoreError)
error("Failed to load plugin %s;%s, error: %s ", className, attrs, e.getMessage());
}
catch (Exception e) {
error("Unexpected error loading plugin %s-%s: %s", className, attrs, e);
}
return null;
}
protected void setTypeSpecificPlugins(Set<Object> list) {
list.add(executor);
list.add(random);
list.addAll(basicPlugins);
}
/**
* Set the initial parameters of a plugin
*
* @param plugin
* @param entry
*/
protected <T> T customize(T plugin, Attrs map) {
if (plugin instanceof Plugin) {
((Plugin) plugin).setReporter(this);
try {
if (map == null)
map = Attrs.EMPTY_ATTRS;
((Plugin) plugin).setProperties(map);
}
catch (Exception e) {
error("While setting properties %s on plugin %s, %s", map, plugin, e);
}
}
if (plugin instanceof RegistryPlugin) {
((RegistryPlugin) plugin).setRegistry(this);
}
return plugin;
}
/**
* Indicates that this run should ignore errors and succeed anyway
*
* @return true if this processor should return errors
*/
@Override
public boolean isFailOk() {
String v = getProperty(Analyzer.FAIL_OK, null);
return v != null && v.equalsIgnoreCase("true");
}
public File getBase() {
return base;
}
public void setBase(File base) {
this.base = base;
}
public void clear() {
errors.clear();
warnings.clear();
locations.clear();
fixupMessages = false;
}
public void trace(String msg, Object... parms) {
Processor p = current();
if (p.trace) {
System.err.printf("# " + msg + "%n", parms);
}
}
public <T> List<T> newList() {
return new ArrayList<T>();
}
public <T> Set<T> newSet() {
return new TreeSet<T>();
}
public static <K, V> Map<K,V> newMap() {
return new LinkedHashMap<K,V>();
}
public static <K, V> Map<K,V> newHashMap() {
return new LinkedHashMap<K,V>();
}
public <T> List<T> newList(Collection<T> t) {
return new ArrayList<T>(t);
}
public <T> Set<T> newSet(Collection<T> t) {
return new TreeSet<T>(t);
}
public <K, V> Map<K,V> newMap(Map<K,V> t) {
return new LinkedHashMap<K,V>(t);
}
public void close() {
for (Closeable c : toBeClosed) {
try {
c.close();
}
catch (IOException e) {
// Who cares?
}
}
if (pluginLoader != null)
pluginLoader.closex();
toBeClosed.clear();
}
public String _basedir(@SuppressWarnings("unused") String args[]) {
if (base == null)
throw new IllegalArgumentException("No base dir set");
return base.getAbsolutePath();
}
public String _propertiesname(String[] args) {
if (args.length > 1) {
error("propertiesname does not take arguments");
return null;
}
File pf = getPropertiesFile();
if (pf == null)
return "";
return pf.getName();
}
public String _propertiesdir(String[] args) {
if (args.length > 1) {
error("propertiesdir does not take arguments");
return null;
}
File pf = getPropertiesFile();
if (pf == null)
return "";
return pf.getParentFile().getAbsolutePath();
}
/**
* Property handling ...
*
* @return
*/
public Properties getProperties() {
if (fixup) {
fixup = false;
begin();
}
fixupMessages = false;
return properties;
}
public String getProperty(String key) {
return getProperty(key, null);
}
public void mergeProperties(File file, boolean override) {
if (file.isFile()) {
try {
Properties properties = loadProperties(file);
mergeProperties(properties, override);
}
catch (Exception e) {
error("Error loading properties file: " + file);
}
} else {
if (!file.exists())
error("Properties file does not exist: " + file);
else
error("Properties file must a file, not a directory: " + file);
}
}
public void mergeProperties(Properties properties, boolean override) {
for (Enumeration< ? > e = properties.propertyNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
String value = properties.getProperty(key);
if (override || !getProperties().containsKey(key))
setProperty(key, value);
}
}
public void setProperties(Properties properties) {
doIncludes(getBase(), properties);
this.properties.putAll(properties);
}
public void setProperties(File base, Properties properties) {
doIncludes(base, properties);
this.properties.putAll(properties);
}
public void addProperties(File file) throws Exception {
addIncluded(file);
Properties p = loadProperties(file);
setProperties(p);
}
public void addProperties(Map< ? , ? > properties) {
for (Entry< ? , ? > entry : properties.entrySet()) {
setProperty(entry.getKey().toString(), entry.getValue() + "");
}
}
public synchronized void addIncluded(File file) {
if (included == null)
included = new ArrayList<File>();
included.add(file);
}
/**
* Inspect the properties and if you find -includes parse the line included
* manifest files or properties files. The files are relative from the given
* base, this is normally the base for the analyzer.
*
* @param ubase
* @param p
* @param done
* @throws IOException
* @throws IOException
*/
private void doIncludes(File ubase, Properties p) {
String includes = p.getProperty(INCLUDE);
if (includes != null) {
includes = getReplacer().process(includes);
p.remove(INCLUDE);
Collection<String> clauses = new Parameters(includes).keySet();
for (String value : clauses) {
boolean fileMustExist = true;
boolean overwrite = true;
while (true) {
if (value.startsWith("-")) {
fileMustExist = false;
value = value.substring(1).trim();
} else if (value.startsWith("~")) {
// Overwrite properties!
overwrite = false;
value = value.substring(1).trim();
} else
break;
}
try {
File file = getFile(ubase, value).getAbsoluteFile();
if (!file.isFile()) {
try {
URL url = new URL(value);
int n = value.lastIndexOf('.');
String ext = ".jar";
if (n >= 0)
ext = value.substring(n);
File tmp = File.createTempFile("url", ext);
try {
IO.copy(url.openStream(), tmp);
doIncludeFile(tmp, overwrite, p);
}
finally {
tmp.delete();
}
}
catch (Exception mue) {
// ignore
}
if (fileMustExist)
error("Included file " + file + (file.isDirectory() ? " is directory" : " does not exist"));
} else
doIncludeFile(file, overwrite, p);
}
catch (Exception e) {
if (fileMustExist)
error("Error in processing included file: " + value, e);
}
}
}
}
/**
* @param file
* @param parent
* @param done
* @param overwrite
* @throws FileNotFoundException
* @throws IOException
*/
public void doIncludeFile(File file, boolean overwrite, Properties target) throws Exception {
doIncludeFile(file, overwrite, target, null);
}
/**
* @param file
* @param parent
* @param done
* @param overwrite
* @param extensionName
* @throws FileNotFoundException
* @throws IOException
*/
public void doIncludeFile(File file, boolean overwrite, Properties target, String extensionName) throws Exception {
if (included != null && included.contains(file)) {
error("Cyclic or multiple include of " + file);
} else {
addIncluded(file);
updateModified(file.lastModified(), file.toString());
InputStream in = new FileInputStream(file);
try {
Properties sub;
if (file.getName().toLowerCase().endsWith(".mf")) {
sub = getManifestAsProperties(in);
} else
sub = loadProperties(in, file.getAbsolutePath());
doIncludes(file.getParentFile(), sub);
// make sure we do not override properties
for (Map.Entry< ? , ? > entry : sub.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (overwrite || !target.containsKey(key)) {
target.setProperty(key, value);
} else if (extensionName != null) {
String extensionKey = extensionName + "." + key;
if (!target.containsKey(extensionKey))
target.setProperty(extensionKey, value);
}
}
}
finally {
IO.close(in);
}
}
}
public void unsetProperty(String string) {
getProperties().remove(string);
}
public boolean refresh() {
plugins = null; // We always refresh our plugins
if (propertiesFile == null)
return false;
boolean changed = updateModified(propertiesFile.lastModified(), "properties file");
if (included != null) {
for (File file : included) {
if (changed)
break;
changed |= !file.exists() || updateModified(file.lastModified(), "include file: " + file);
}
}
profile = getProperty(PROFILE); // Used in property access
if (changed) {
forceRefresh();
return true;
}
return false;
}
/**
* If strict is true, then extra verification is done.
*/
boolean isStrict() {
if (strict == null)
strict = isTrue(getProperty(STRICT)); // Used in property access
return strict;
}
public void forceRefresh() {
included = null;
properties.clear();
setProperties(propertiesFile, base);
propertiesChanged();
}
public void propertiesChanged() {}
/**
* Set the properties by file. Setting the properties this way will also set
* the base for this analyzer. After reading the properties, this will call
* setProperties(Properties) which will handle the includes.
*
* @param propertiesFile
* @throws FileNotFoundException
* @throws IOException
*/
public void setProperties(File propertiesFile) throws IOException {
propertiesFile = propertiesFile.getAbsoluteFile();
setProperties(propertiesFile, propertiesFile.getParentFile());
}
public void setProperties(File propertiesFile, File base) {
this.propertiesFile = propertiesFile.getAbsoluteFile();
setBase(base);
try {
if (propertiesFile.isFile()) {
// System.err.println("Loading properties " + propertiesFile);
long modified = propertiesFile.lastModified();
if (modified > System.currentTimeMillis() + 100) {
System.err.println("Huh? This is in the future " + propertiesFile);
this.modified = System.currentTimeMillis();
} else
this.modified = modified;
included = null;
Properties p = loadProperties(propertiesFile);
setProperties(p);
} else {
if (fileMustExist) {
error("No such properties file: " + propertiesFile);
}
}
}
catch (IOException e) {
error("Could not load properties " + propertiesFile);
}
}
protected void begin() {
if (isTrue(getProperty(PEDANTIC)))
setPedantic(true);
}
public static boolean isTrue(String value) {
if (value == null)
return false;
if ("false".equalsIgnoreCase(value))
return false;
if ("off".equalsIgnoreCase(value))
return false;
if ("not".equalsIgnoreCase(value))
return false;
return true;
}
/**
* Get a property without preprocessing it with a proper default
*
* @param headerName
* @param deflt
* @return
*/
public String getUnprocessedProperty(String key, String deflt) {
return getProperties().getProperty(key, deflt);
}
/**
* Get a property with preprocessing it with a proper default
*
* @param headerName
* @param deflt
* @return
*/
public String getProperty(String key, String deflt) {
return getProperty(key, deflt, ",");
}
public String getProperty(String key, String deflt, String separator) {
String value = null;
Instruction ins = new Instruction(key);
if (!ins.isLiteral()) {
// Handle a wildcard key, make sure they're sorted
// for consistency
SortedList<String> sortedList = SortedList.fromIterator(iterator());
StringBuilder sb = new StringBuilder();
String del = "";
for (String k : sortedList) {
if (ins.matches(k)) {
String v = getProperty(k, null);
if (v != null) {
sb.append(del);
del = separator;
sb.append(v);
}
}
}
if (sb.length() == 0)
return deflt;
return sb.toString();
}
@SuppressWarnings("resource")
Processor source = this;
// Use the key as is first, if found ok
if (filter != null && filter.contains(key)) {
value = (String) getProperties().get(key);
} else {
while (source != null) {
value = (String) source.getProperties().get(key);
if (value != null)
break;
source = source.getParent();
}
// Check if we can find a replacement through the
// replacer, which takes profiles into account
if (value == null) {
value = getReplacer().getMacro(key, null);
}
}
if (value != null)
return getReplacer().process(value, source);
else if (deflt != null)
return getReplacer().process(deflt, this);
else
return null;
}
/**
* Helper to load a properties file from disk.
*
* @param file
* @return
* @throws IOException
*/
public Properties loadProperties(File file) throws IOException {
updateModified(file.lastModified(), "Properties file: " + file);
InputStream in = new FileInputStream(file);
try {
Properties p = loadProperties(in, file.getAbsolutePath());
return p;
}
finally {
in.close();
}
}
/**
* Load Properties from disk. The default encoding is ISO-8859-1 but
* nowadays all files are encoded with UTF-8. So we try to load it first as
* UTF-8 and if this fails we fail back to ISO-8859-1
*
* @param in
* The stream to load from
* @param name
* The name of the file for doc reasons
* @return a Properties
* @throws IOException
*/
Properties loadProperties(InputStream in, String name) throws IOException {
int n = name.lastIndexOf('/');
if (n > 0)
name = name.substring(0, n);
if (name.length() == 0)
name = ".";
try {
Properties p = new UTF8Properties();
p.load(in);
return replaceAll(p, "\\$\\{\\.\\}", name);
}
catch (Exception e) {
error("Error during loading properties file: " + name + ", error:" + e);
return new UTF8Properties();
}
}
/**
* Replace a string in all the values of the map. This can be used to
* preassign variables that change. I.e. the base directory ${.} for a
* loaded properties
*/
public static Properties replaceAll(Properties p, String pattern, String replacement) {
Properties result = new UTF8Properties();
for (Iterator<Map.Entry<Object,Object>> i = p.entrySet().iterator(); i.hasNext();) {
Map.Entry<Object,Object> entry = i.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
value = value.replaceAll(pattern, replacement);
result.put(key, value);
}
return result;
}
/**
* Print a standard Map based OSGi header.
*
* @param exports
* map { name => Map { attribute|directive => value } }
* @return the clauses
* @throws IOException
*/
public static String printClauses(Map< ? , ? extends Map< ? , ? >> exports) throws IOException {
return printClauses(exports, false);
}
public static String printClauses(Map< ? , ? extends Map< ? , ? >> exports,
@SuppressWarnings("unused") boolean checkMultipleVersions) throws IOException {
StringBuilder sb = new StringBuilder();
String del = "";
for (Entry< ? , ? extends Map< ? , ? >> entry : exports.entrySet()) {
String name = entry.getKey().toString();
Map< ? , ? > clause = entry.getValue();
// We allow names to be duplicated in the input
// by ending them with '~'. This is necessary to use
// the package names as keys. However, we remove these
// suffixes in the output so that you can set multiple
// exports with different attributes.
String outname = removeDuplicateMarker(name);
sb.append(del);
sb.append(outname);
printClause(clause, sb);
del = ",";
}
return sb.toString();
}
public static void printClause(Map< ? , ? > map, StringBuilder sb) throws IOException {
for (Entry< ? , ? > entry : map.entrySet()) {
Object key = entry.getKey();
// Skip directives we do not recognize
if (key.equals(INTERNAL_SOURCE_DIRECTIVE) ||key.equals(INTERNAL_EXPORTED_DIRECTIVE) ||key.equals(NO_IMPORT_DIRECTIVE) || key.equals(PROVIDE_DIRECTIVE) || key.equals(SPLIT_PACKAGE_DIRECTIVE)
|| key.equals(FROM_DIRECTIVE))
continue;
String value = ((String) entry.getValue()).trim();
sb.append(";");
sb.append(key);
sb.append("=");
quote(sb, value);
}
}
/**
* @param sb
* @param value
* @return
* @throws IOException
*/
public static boolean quote(Appendable sb, String value) throws IOException {
if (value.startsWith("\\\""))
value = value.substring(2);
if (value.endsWith("\\\""))
value = value.substring(0, value.length() - 2);
if (value.startsWith("\"") && value.endsWith("\""))
value = value.substring(1, value.length() - 1);
boolean clean = (value.length() >= 2 && value.charAt(0) == '"' && value.charAt(value.length() - 1) == '"')
|| Verifier.TOKEN.matcher(value).matches();
if (!clean)
sb.append("\"");
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '"' :
sb.append('\\').append('"');
break;
default :
sb.append(c);
}
}
if (!clean)
sb.append("\"");
return clean;
}
public Macro getReplacer() {
if (replacer == null)
return replacer = new Macro(this, getMacroDomains());
return replacer;
}
/**
* This should be overridden by subclasses to add extra macro command
* domains on the search list.
*
* @return
*/
protected Object[] getMacroDomains() {
return new Object[] {};
}
/**
* Return the properties but expand all macros. This always returns a new
* Properties object that can be used in any way.
*
* @return
*/
public Properties getFlattenedProperties() {
return getReplacer().getFlattenedProperties();
}
/**
* Return the properties but expand all macros. This always returns a new
* Properties object that can be used in any way.
*
* @return
*/
public Properties getFlattenedProperties(boolean ignoreInstructions) {
return getReplacer().getFlattenedProperties(ignoreInstructions);
}
/**
* Return all inherited property keys
*
* @return
*/
public Set<String> getPropertyKeys(boolean inherit) {
Set<String> result;
if (parent == null || !inherit) {
result = Create.set();
} else
result = parent.getPropertyKeys(inherit);
for (Object o : properties.keySet())
result.add(o.toString());
return result;
}
public boolean updateModified(long time, @SuppressWarnings("unused") String reason) {
if (time > lastModified) {
lastModified = time;
return true;
}
return false;
}
public long lastModified() {
return lastModified;
}
/**
* Add or override a new property.
*
* @param key
* @param value
*/
public void setProperty(String key, String value) {
checkheader: for (int i = 0; i < headers.length; i++) {
if (headers[i].equalsIgnoreCase(value)) {
value = headers[i];
break checkheader;
}
}
getProperties().put(key, value);
}
/**
* Read a manifest but return a properties object.
*
* @param in
* @return
* @throws IOException
*/
public static Properties getManifestAsProperties(InputStream in) throws IOException {
Properties p = new UTF8Properties();
Manifest manifest = new Manifest(in);
for (Iterator<Object> it = manifest.getMainAttributes().keySet().iterator(); it.hasNext();) {
Attributes.Name key = (Attributes.Name) it.next();
String value = manifest.getMainAttributes().getValue(key);
p.put(key.toString(), value);
}
return p;
}
public File getPropertiesFile() {
return propertiesFile;
}
public void setFileMustExist(boolean mustexist) {
fileMustExist = mustexist;
}
static public String read(InputStream in) throws Exception {
InputStreamReader ir = new InputStreamReader(in, "UTF8");
StringBuilder sb = new StringBuilder();
try {
char chars[] = new char[BUFFER_SIZE];
int size = ir.read(chars);
while (size > 0) {
sb.append(chars, 0, size);
size = ir.read(chars);
}
}
finally {
ir.close();
}
return sb.toString();
}
/**
* Join a list.
*
* @param args
* @return
*/
public static String join(Collection< ? > list, String delimeter) {
return join(delimeter, list);
}
public static String join(String delimeter, Collection< ? >... list) {
StringBuilder sb = new StringBuilder();
String del = "";
if (list != null) {
for (Collection< ? > l : list) {
for (Object item : l) {
sb.append(del);
sb.append(item);
del = delimeter;
}
}
}
return sb.toString();
}
public static String join(Object[] list, String delimeter) {
if (list == null)
return "";
StringBuilder sb = new StringBuilder();
String del = "";
for (Object item : list) {
sb.append(del);
sb.append(item);
del = delimeter;
}
return sb.toString();
}
public static String join(Collection< ? >... list) {
return join(",", list);
}
public static <T> String join(T list[]) {
return join(list, ",");
}
public static void split(String s, Collection<String> set) {
String elements[] = s.trim().split(LIST_SPLITTER);
for (String element : elements) {
if (element.length() > 0)
set.add(element);
}
}
public static Collection<String> split(String s) {
return split(s, LIST_SPLITTER);
}
public static Collection<String> split(String s, String splitter) {
if (s != null)
s = s.trim();
if (s == null || s.trim().length() == 0)
return Collections.emptyList();
return Arrays.asList(s.split(splitter));
}
public static String merge(String... strings) {
ArrayList<String> result = new ArrayList<String>();
for (String s : strings) {
if (s != null)
split(s, result);
}
return join(result);
}
public boolean isExceptions() {
return exceptions;
}
public void setExceptions(boolean exceptions) {
this.exceptions = exceptions;
}
/**
* Make the file short if it is inside our base directory, otherwise long.
*
* @param f
* @return
*/
public String normalize(String f) {
if (f.startsWith(base.getAbsolutePath() + "/"))
return f.substring(base.getAbsolutePath().length() + 1);
return f;
}
public String normalize(File f) {
return normalize(f.getAbsolutePath());
}
public static String removeDuplicateMarker(String key) {
int i = key.length() - 1;
while (i >= 0 && key.charAt(i) == DUPLICATE_MARKER)
--i;
return key.substring(0, i + 1);
}
public static boolean isDuplicate(String name) {
return name.length() > 0 && name.charAt(name.length() - 1) == DUPLICATE_MARKER;
}
public void setTrace(boolean x) {
trace = x;
}
public static class CL extends URLClassLoader {
CL() {
super(new URL[0], Processor.class.getClassLoader());
}
void closex() {
Class<URLClassLoader> clazz = URLClassLoader.class;
try {
// Java 7 is a good boy, it has a close method
clazz.getMethod("close").invoke(this);
return;
}
catch (Exception e) {
// ignore
}
// On Java 6, we're screwed and have to much around
// This is best effort, likely fails on non-SUN vms
try {
Field ucpField = clazz.getDeclaredField("ucp");
ucpField.setAccessible(true);
Object cp = ucpField.get(this);
Field loadersField = cp.getClass().getDeclaredField("loaders");
loadersField.setAccessible(true);
Collection< ? > loaders = (Collection< ? >) loadersField.get(cp);
for (Object loader : loaders) {
try {
Field loaderField = loader.getClass().getDeclaredField("jar");
loaderField.setAccessible(true);
JarFile jarFile = (JarFile) loaderField.get(loader);
jarFile.close();
}
catch (Throwable t) {
// if we got this far, this is probably not a JAR loader
// so skip it
}
}
}
catch (Throwable t) {
// probably not a SUN VM
}
}
void add(URL url) {
URL urls[] = getURLs();
for (URL u : urls) {
if (u.equals(url))
return;
}
super.addURL(url);
}
@Override
public Class< ? > loadClass(String name) throws ClassNotFoundException {
try {
Class< ? > c = super.loadClass(name);
return c;
}
catch (Throwable t) {
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append(" not found, parent: ");
sb.append(getParent());
sb.append(" urls:");
sb.append(Arrays.toString(getURLs()));
sb.append(" exception:");
sb.append(t);
throw new ClassNotFoundException(sb.toString(), t);
}
}
}
protected CL getLoader() {
if (pluginLoader == null) {
pluginLoader = new CL();
}
return pluginLoader;
}
/*
* Check if this is a valid project.
*/
public boolean exists() {
return base != null && base.isDirectory() && propertiesFile != null && propertiesFile.isFile();
}
public boolean isOk() {
return isFailOk() || (getErrors().size() == 0);
}
/**
* Move errors and warnings to their proper place by scanning the fixup
* messages property.
*/
private void fixupMessages() {
if (fixupMessages)
return;
fixupMessages = true;
Parameters fixup = getMergedParameters(Constants.FIXUPMESSAGES);
if (fixup.isEmpty())
return;
Instructions instrs = new Instructions(fixup);
doFixup(instrs, errors, warnings, FIXUPMESSAGES_IS_ERROR);
doFixup(instrs, warnings, errors, FIXUPMESSAGES_IS_WARNING);
}
private void doFixup(Instructions instrs, List<String> messages, List<String> other, String type) {
for (int i = 0; i < messages.size(); i++) {
String message = messages.get(i);
Instruction matcher = instrs.finder(message);
if (matcher == null || matcher.isNegated())
continue;
Attrs attrs = instrs.get(matcher);
// Default the pattern applies to the errors and warnings
// but we can restrict it: e.g. restrict:=error
String restrict = attrs.get(FIXUPMESSAGES_RESTRICT_DIRECTIVE);
if (restrict != null && !FIXUPMESSAGES_IS_ERROR.equals(restrict))
continue;
// We can optionally replace the message with another text. E.g.
// replace:"hello world". This can use macro expansion, the ${@}
// macro is set to the old message.
String replace = attrs.get(FIXUPMESSAGES_REPLACE_DIRECTIVE);
if (replace != null) {
trace("replacing %s with %s", message, replace);
setProperty("@", message);
message = getReplacer().process(replace);
messages.set(i, message);
unsetProperty("@");
}
String is = attrs.get(FIXUPMESSAGES_IS_DIRECTIVE);
if (attrs.isEmpty() || FIXUPMESSAGES_IS_IGNORE.equals(is)) {
messages.remove(i
} else {
if (is != null && !type.equals(is)) {
messages.remove(i
other.add(message);
}
}
}
}
public boolean check(String... pattern) throws IOException {
Set<String> missed = Create.set();
if (pattern != null) {
for (String p : pattern) {
boolean match = false;
Pattern pat = Pattern.compile(p);
for (Iterator<String> i = errors.iterator(); i.hasNext();) {
if (pat.matcher(i.next()).find()) {
i.remove();
match = true;
}
}
for (Iterator<String> i = warnings.iterator(); i.hasNext();) {
if (pat.matcher(i.next()).find()) {
i.remove();
match = true;
}
}
if (!match)
missed.add(p);
}
}
if (missed.isEmpty() && isPerfect())
return true;
if (!missed.isEmpty())
System.err.println("Missed the following patterns in the warnings or errors: " + missed);
report(System.err);
return false;
}
protected void report(Appendable out) throws IOException {
if (errors.size() > 0) {
out.append(String.format("
for (int i = 0; i < errors.size(); i++) {
out.append(String.format("%03d: %s%n", i, errors.get(i)));
}
}
if (warnings.size() > 0) {
out.append(String.format("
for (int i = 0; i < warnings.size(); i++) {
out.append(String.format("%03d: %s%n", i, warnings.get(i)));
}
}
}
public boolean isPerfect() {
return getErrors().size() == 0 && getWarnings().size() == 0;
}
public void setForceLocal(Collection<String> local) {
filter = local;
}
/**
* Answer if the name is a missing plugin's command name. If a bnd file
* contains the command name of a plugin, and that plugin is not available,
* then an error is reported during manifest calculation. This allows the
* plugin to fail to load when it is not needed. We first get the plugins to
* ensure it is properly initialized.
*
* @param name
* @return
*/
public boolean isMissingPlugin(String name) {
getPlugins();
return missingCommand != null && missingCommand.contains(name);
}
/**
* Append two strings to for a path in a ZIP or JAR file. It is guaranteed
* to return a string that does not start, nor ends with a '/', while it is
* properly separated with slashes. Double slashes are properly removed.
*
* <pre>
* "/" + "abc/def/" becomes "abc/def"
*
* @param prefix
* @param suffix
* @return
*/
public static String appendPath(String... parts) {
StringBuilder sb = new StringBuilder();
boolean lastSlash = true;
for (String part : parts) {
for (int i = 0; i < part.length(); i++) {
char c = part.charAt(i);
if (c == '/') {
if (!lastSlash)
sb.append('/');
lastSlash = true;
} else {
sb.append(c);
lastSlash = false;
}
}
if (!lastSlash && sb.length() > 0) {
sb.append('/');
lastSlash = true;
}
}
if (lastSlash && sb.length() > 0)
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
/**
* Parse the a=b strings and return a map of them.
*
* @param attrs
* @param clazz
* @return
*/
public static Attrs doAttrbutes(Object[] attrs, Clazz clazz, Macro macro) {
Attrs map = new Attrs();
if (attrs == null || attrs.length == 0)
return map;
for (Object a : attrs) {
String attr = (String) a;
int n = attr.indexOf("=");
if (n > 0) {
map.put(attr.substring(0, n), macro.process(attr.substring(n + 1)));
} else
throw new IllegalArgumentException(formatArrays(
"Invalid attribute on package-info.java in %s , %s. Must be <key>=<name> ", clazz, attr));
}
return map;
}
/**
* This method is the same as String.format but it makes sure that any
* arrays are transformed to strings.
*
* @param string
* @param parms
* @return
*/
public static String formatArrays(String string, Object... parms) {
Object[] parms2 = parms;
Object[] output = new Object[parms.length];
for (int i = 0; i < parms.length; i++) {
output[i] = makePrintable(parms[i]);
}
return String.format(string, parms2);
}
/**
* Check if the object is an array and turn it into a string if it is,
* otherwise unchanged.
*
* @param object
* the object to make printable
* @return a string if it was an array or the original object
*/
public static Object makePrintable(Object object) {
if (object == null)
return object;
if (object.getClass().isArray()) {
Object[] array = (Object[]) object;
Object[] output = new Object[array.length];
for (int i = 0; i < array.length; i++) {
output[i] = makePrintable(array[i]);
}
return Arrays.toString(output);
}
return object;
}
public static String append(String... strings) {
List<String> result = Create.list();
for (String s : strings) {
result.addAll(split(s));
}
return join(result);
}
public synchronized Class< ? > getClass(String type, File jar) throws Exception {
CL cl = getLoader();
cl.add(jar.toURI().toURL());
return cl.loadClass(type);
}
public boolean isTrace() {
return current().trace;
}
public static long getDuration(String tm, long dflt) {
if (tm == null)
return dflt;
tm = tm.toUpperCase();
TimeUnit unit = TimeUnit.MILLISECONDS;
Matcher m = Pattern
.compile("\\s*(\\d+)\\s*(NANOSECONDS|MICROSECONDS|MILLISECONDS|SECONDS|MINUTES|HOURS|DAYS)?").matcher(
tm);
if (m.matches()) {
long duration = Long.parseLong(tm);
String u = m.group(2);
if (u != null)
unit = TimeUnit.valueOf(u);
duration = TimeUnit.MILLISECONDS.convert(duration, unit);
return duration;
}
return dflt;
}
/**
* Generate a random string, which is guaranteed to be a valid Java
* identifier (first character is an ASCII letter, subsequent characters are
* ASCII letters or numbers). Takes an optional parameter for the length of
* string to generate; default is 8 characters.
*/
public String _random(String[] args) {
int numchars = 8;
if (args.length > 1) {
try {
numchars = Integer.parseInt(args[1]);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid character count parameter in ${random} macro.");
}
}
synchronized (Processor.class) {
if (random == null)
random = new Random();
}
char[] letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
char[] alphanums = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
char[] array = new char[numchars];
for (int i = 0; i < numchars; i++) {
char c;
if (i == 0)
c = letters[random.nextInt(letters.length)];
else
c = alphanums[random.nextInt(alphanums.length)];
array[i] = c;
}
return new String(array);
}
private static final String OSGI_NATIVE = "osgi.native";
private static final String OS_NAME = "osname";
private static final String OS_VERSION = "osversion";
private static final String OS_PROCESSOR = "processor";
public String _native_capability(String[] args) throws IllegalArgumentException {
StringBuilder builder = new StringBuilder().append(OSGI_NATIVE);
String processorNames = null;
OSInformation osInformation = null;
IllegalArgumentException osInformationException = null;
/*
* Determine the processor information
*/
String[] aliases = OSInformation.getProcessorAliases(System.getProperty("os.arch"));
if (aliases != null)
processorNames = Strings.join(aliases);
/*
* Determine the OS information
*/
try {
osInformation = new OSInformation();
}
catch (IllegalArgumentException e) {
osInformationException = e;
}
/*
* Determine overrides
*/
String osnameOverride = null;
Version osversionOverride = null;
String processorNamesOverride = null;
if (args.length > 1) {
assert ("native_capability".equals(args[0]));
for (int i = 1; i < args.length; i++) {
String arg = args[i];
String[] fields = arg.split("=", 2);
if (fields.length != 2) {
throw new IllegalArgumentException("Illegal property syntax in \"" + arg + "\", use \"key=value\"");
}
String key = fields[0];
String value = fields[1];
if (OS_NAME.equals(key)) {
osnameOverride = value;
} else if (OS_VERSION.equals(key)) {
osversionOverride = new Version(value);
} else if (OS_PROCESSOR.equals(key)) {
processorNamesOverride = value;
} else {
throw new IllegalArgumentException("Unrecognised/unsupported property. Supported: " + OS_NAME
+ ", " + OS_VERSION + ", " + OS_PROCESSOR + ".");
}
}
}
/*
* Determine effective values: put determined value into override if
* there is no override
*/
if (osnameOverride == null && osInformation != null) {
osnameOverride = osInformation.osnames;
}
if (osversionOverride == null && osInformation != null) {
osversionOverride = osInformation.osversion;
}
if (processorNamesOverride == null && processorNames != null) {
processorNamesOverride = processorNames;
}
/*
* Construct result string
*/
builder.append(";" + OSGI_NATIVE + "." + OS_NAME + ":List<String>=\"").append(osnameOverride).append('"');
builder.append(";" + OSGI_NATIVE + "." + OS_VERSION + ":Version=").append(osversionOverride);
builder.append(";" + OSGI_NATIVE + "." + OS_PROCESSOR + ":List<String>=\"").append(processorNamesOverride)
.append('"');
/*
* Report error if needed
*/
if (osnameOverride == null || osversionOverride == null || processorNamesOverride == null) {
throw new IllegalArgumentException(
"At least one of the required parameters could not be detected; specify an override. Detected: "
+ builder.toString(), osInformationException);
}
return builder.toString();
}
/**
* Set the current command thread. This must be balanced with the
* {@link #end(Processor)} method. The method returns the previous command
* owner or null. The command owner will receive all warnings and error
* reports.
*/
protected Processor beginHandleErrors(String message) {
trace("begin %s", message);
Processor previous = current.get();
current.set(this);
return previous;
}
/**
* End a command. Will restore the previous command owner.
*
* @param previous
*/
protected void endHandleErrors(Processor previous) {
trace("end");
current.set(previous);
}
public static Executor getExecutor() {
return executor;
}
/**
* These plugins are added to the total list of plugins. The separation is
* necessary because the list of plugins is refreshed now and then so we
* need to be able to add them at any moment in time.
*
* @param plugin
*/
public synchronized void addBasicPlugin(Object plugin) {
basicPlugins.add(plugin);
if (plugins != null)
plugins.add(plugin);
}
public synchronized void removeBasicPlugin(Object plugin) {
basicPlugins.remove(plugin);
if (plugins != null)
plugins.remove(plugin);
}
public List<File> getIncluded() {
return included;
}
/**
* Overrides for the Domain class
*/
@Override
public String get(String key) {
return getProperty(key);
}
@Override
public String get(String key, String deflt) {
return getProperty(key, deflt);
}
@Override
public void set(String key, String value) {
getProperties().setProperty(key, value);
}
@Override
public Iterator<String> iterator() {
Set<String> keys = keySet();
final Iterator<String> it = keys.iterator();
return new Iterator<String>() {
String current;
public boolean hasNext() {
return it.hasNext();
}
public String next() {
return current = it.next().toString();
}
public void remove() {
getProperties().remove(current);
}
};
}
public Set<String> keySet() {
Set<String> set;
if (parent == null)
set = Create.set();
else
set = parent.keySet();
for (Object o : properties.keySet())
set.add(o.toString());
return set;
}
/**
* Printout of the status of this processor for toString()
*/
@Override
public String toString() {
try {
StringBuilder sb = new StringBuilder();
report(sb);
return sb.toString();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Utiltity to replace an extension
*
* @param s
* @param extension
* @param newExtension
* @return
*/
public String replaceExtension(String s, String extension, String newExtension) {
if (s.endsWith(extension))
s = s.substring(0, s.length() - extension.length());
return s + newExtension;
}
/**
* Create a location object and add it to the locations
*
* @param s
* @return
*/
List<Location> locations = new ArrayList<Location>();
static class SetLocationImpl extends Location implements SetLocation {
public SetLocationImpl(String s) {
this.message = s;
}
public SetLocation file(String file) {
this.file = file;
return this;
}
public SetLocation header(String header) {
this.header = header;
return this;
}
public SetLocation context(String context) {
this.context = context;
return this;
}
public SetLocation method(String methodName) {
this.methodName = methodName;
return this;
}
public SetLocation line(int n) {
this.line = n;
return this;
}
public SetLocation reference(String reference) {
this.reference = reference;
return this;
}
public SetLocation details(Object details) {
this.details = details;
return this;
}
public Location location() {
return this;
}
public SetLocation length(int length) {
this.length = length;
return this;
}
}
private SetLocation location(String s) {
SetLocationImpl loc = new SetLocationImpl(s);
locations.add(loc);
return loc;
}
public Location getLocation(String msg) {
for (Location l : locations)
if ((l.message != null) && l.message.equals(msg))
return l;
return null;
}
/**
* Get a header relative to this processor, tking its parents and includes
* into account.
*
* @param location
* @param header
* @return
* @throws IOException
*/
public FileLine getHeader(String header) throws Exception {
return getHeader(Pattern.compile("^[ \t]*" + Pattern.quote(header), Pattern.MULTILINE
+ Pattern.CASE_INSENSITIVE));
}
public FileLine getHeader(Pattern header) throws Exception {
FileLine fl = getHeader0(header);
if (fl != null)
return fl;
@SuppressWarnings("resource")
Processor rover = this;
while (rover.getPropertiesFile() == null)
if (rover.parent == null) {
return new FileLine(new File("ANONYMOUS"), 0, 0);
} else
rover = rover.parent;
return new FileLine(rover.getPropertiesFile(), 0, 0);
}
private FileLine getHeader0(Pattern header) throws Exception {
FileLine fl;
File f = getPropertiesFile();
if (f != null) {
// Find in "our" local file
fl = findHeader(f, header);
if (fl != null)
return fl;
// Get the includes (actually should parse the header
// to see if they override or only provide defaults?
List<File> result = getIncluded();
if (result != null) {
ExtList<File> reversed = new ExtList<File>(result);
Collections.reverse(reversed);
for (File included : reversed) {
fl = findHeader(included, header);
if (fl != null)
return fl;
}
}
}
// Ok, not on this level ...
if (getParent() != null) {
fl = getParent().getHeader(header);
if (fl != null)
return fl;
}
// Ok, report the error on the sub file
// Sometimes we do not have a file ...
if (f == null && parent != null)
f = parent.getPropertiesFile();
if (f == null)
return null;
return new FileLine(f, 0, 0);
}
public static FileLine findHeader(File f, String header) throws IOException {
return findHeader(f,
Pattern.compile("^[ \t]*" + Pattern.quote(header), Pattern.MULTILINE + Pattern.CASE_INSENSITIVE));
}
public static FileLine findHeader(File f, Pattern header) throws IOException {
String s = IO.collect(f);
Matcher matcher = header.matcher(s);
if (!matcher.find())
return null;
return new FileLine(f, getLine(s, matcher.start(0)), matcher.group().length());
}
public static int getLine(String s, int index) {
int n = 0;
while (--index > 0) {
char c = s.charAt(index);
if (c == '\n') {
n++;
}
}
return n;
}
/**
* This method is about compatibility. New behavior can be conditionally
* introduced by calling this method and passing what version this behavior
* was introduced. This allows users of bnd to set the -upto instructions to
* the version that they want to be compatible with. If this instruction is
* not set, we assume the latest version.
*/
Version upto = null;
public boolean since(Version introduced) {
if (upto == null) {
String uptov = getProperty(UPTO);
if (uptov == null) {
upto = Version.HIGHEST;
return true;
}
if (!Version.VERSION.matcher(uptov).matches()) {
error("The %s given version is not a version: %s", UPTO, uptov);
upto = Version.HIGHEST;
return true;
}
upto = new Version(uptov);
}
return upto.compareTo(introduced) >= 0;
}
/**
* Report the details of this processor. Should in general be overridden
*
* @param table
* @throws Exception
*/
public void report(Map<String,Object> table) throws Exception {
table.put("Included Files", getIncluded());
table.put("Base", getBase());
table.put("Properties", properties.entrySet());
}
/**
* Simplified way to check booleans
*/
public boolean is(String propertyName) {
return isTrue(getProperty(propertyName));
}
/**
* Return merged properties. The parameters provide a list of property names
* which are concatenated in the output, separated by a comma. Not only are
* those property names looked for, also all property names that have that
* constant as a prefix, a '.', and then whatever (.*). The result is either
* null if nothing was found or a list of properties
*/
public String mergeProperties(String key) {
return mergeProperties(key, ",");
}
public String mergeProperties(String key, String separator) {
if (since(About._2_4))
return getProperty(key + "|" + key + ".*", null, separator);
else
return getProperty(key);
}
/**
* Get a Parameters from merged properties
*/
public Parameters getMergedParameters(String key) {
return new Parameters(mergeProperties(key));
}
/**
* Add an element to an array, creating a new one if necessary
*/
public <T> T[] concat(Class<T> type, T[] prefix, T suffix) {
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(type, (prefix != null ? prefix.length : 0) + 1);
if (result.length > 1) {
System.arraycopy(prefix, 0, result, 0, result.length - 1);
}
result[result.length - 1] = suffix;
return result;
}
/**
* Try to get a Jar from a file name/path or a url, or in last resort from
* the classpath name part of their files.
*
* @param name
* URL or filename relative to the base
* @param from
* Message identifying the caller for errors
* @return null or a Jar with the contents for the name
*/
public Jar getJarFromName(String name, String from) {
File file = new File(name);
if (!file.isAbsolute())
file = new File(getBase(), name);
if (file.exists())
try {
Jar jar = new Jar(file);
addClose(jar);
return jar;
}
catch (Exception e) {
error("Exception in parsing jar file for " + from + ": " + name + " " + e);
}
// It is not a file ...
try {
// Lets try a URL
URL url = new URL(name);
Jar jar = new Jar(fileName(url.getPath()));
addClose(jar);
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
long lastModified = connection.getLastModified();
if (lastModified == 0)
// We assume the worst :-(
lastModified = System.currentTimeMillis();
EmbeddedResource.build(jar, in, lastModified);
in.close();
return jar;
}
catch (IOException ee) {
// ignore
}
return null;
}
private String fileName(String path) {
int n = path.lastIndexOf('/');
if (n > 0)
return path.substring(n + 1);
return path;
}
/**
* Return the name of the properties file
*/
public String _thisfile(String[] args) {
if ( propertiesFile == null) {
error("${thisfile} executed on a processor without a properties file");
return null;
}
return propertiesFile.getAbsolutePath().replaceAll("\\\\", "/");
}
}
|
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("all")
public class LO_Sample {
// tag LO_SUSPECT_LOG_CLASS
private static Logger l1 = Logger.getLogger(String.class);
// tag LO_SUSPECT_LOG_CLASS
private static Logger l2 = Logger.getLogger("com.foo.LO_Sample");
// no tag
private static final org.slf4j.Logger l3 = LoggerFactory.getLogger(LO_Sample.class);
// tag LO_SUSPECT_LOG_CLASS
private static Logger l4 = Logger.getLogger(ActionEvent.class.getName());
// no tag
private static Logger l5 = Logger.getLogger(LO_Sample.class.getName());
// no tag
private static Logger l6 = Logger.getLogger("my.nasty.logger.LOGGER");
// no tag
private Logger someLocalLogger;
// no tag
public LO_Sample() {
this(Logger.getRootLogger());
someLocalLogger.info("Why am I using a local logger?");
}
// tag LO_SUSPECT_LOG_PARAMETER
public LO_Sample(Logger someLogger) {
this.someLocalLogger = someLogger;
}
public void testStutter() throws IOException {
InputStream is = null;
try {
File f = new File("Foo");
is = new FileInputStream(f);
} catch (Exception e) {
// tag LO_STUTTERED_MESSAGE
l1.error(e.getMessage(), e);
} finally {
is.close();
}
}
public void testParmInExMessage() throws Exception {
try {
InputStream is = new FileInputStream("foo/bar");
} catch (IOException e) {
// tag LO_EXCEPTION_WITH_LOGGER_PARMS
throw new Exception("Failed to parse {}", e);
}
}
public void testInvalidSLF4jParm() {
// tag LO_INVALID_FORMATTING_ANCHOR
l3.error("This is a problem {0}", "hello");
}
public void testInvalidSLF4jParm2() {
// tag LO_INVALID_FORMATTING_ANCHOR
l3.error("This is a problem %s", "hello");
l3.error("This is a problem %i", 1);
l3.error("This is a problem %d", 3.1);
}
public void testLogAppending(String s) {
try {
// tag LO_APPENDED_STRING_IN_FORMAT_STRING
l3.info("Got an error with: " + s);
} catch (Exception e) {
l3.warn("Go a bad error with: " + s, e);
}
}
public void testWrongNumberOfParms() {
// tag LO_INCORRECT_NUMBER_OF_ANCHOR_PARAMETERS
l3.error("This is a problem {}", "hello", "hello");
// tag LO_INCORRECT_NUMBER_OF_ANCHOR_PARAMETERS
l3.error("This is a problem {} and this {}", "hello");
// tag LO_INCORRECT_NUMBER_OF_ANCHOR_PARAMETERS
l3.error("This is a problem {} and this {} and this {}", "hello", "world");
// tag LO_INCORRECT_NUMBER_OF_ANCHOR_PARAMETERS
l3.error("This is a problem {} and this {} and this {} and this {}", "hello", "hello", "hello");
// no tag
l3.error("This is a problem {} and this {} and this {} and this {}", "hello", "hello", "hello", "hello");
}
public void testFPWrongNumberOfParms() {
// no tag An additional exception argument is allowed if found
l3.error("This is a problem {}", "hello", new IOException("Yikes"));
// no tag An additional exception argument is allowed if found
l3.error("This is a problem {} and this {} and this {} and this {}", "hello", "hello", "hello", "hello", new RuntimeException("yikes"));
// no tag
l3.error("This is a problem {} and this {}", "hello", new RuntimeException("yikes"));
}
public void testFPRealStringBuilderUser(List<String> l) {
StringBuilder sb = new StringBuilder();
for (String s : l) {
sb.append(s).append(":");
}
l3.warn(sb.toString());
}
public class Inner {
public void fpUseAnon() {
ActionListener l = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// no tag
Logger.getLogger(Inner.class).error("fp");
// tag LO_SUSPECT_LOG_CLASS
Logger.getLogger(LO_Sample.class).error("not fp");
}
};
}
}
}
|
package blahbot;
import battlecode.common.*;
public class Headquarter
{
private static boolean spawn(RobotController rc) throws GameActionException
{
if (rc.senseRobotCount() == GameConstants.MAX_ROBOTS) return false;
Direction spawnDir = Utils.myHq.directionTo(Utils.hisHq);
for (int i = spawnDir.ordinal(); i < 8; i++) {
Direction dir = Utils.dirs[i % 8];
if (!rc.canMove(dir)) continue;
rc.spawn(dir);
return true;
}
return false;
}
private static void shoot(RobotController rc) throws GameActionException
{
final int SplashRd = 2;
final int AttackRd = RobotType.HQ.attackRadiusMaxSquared;
Robot objs[] = rc.senseNearbyGameObjects(Robot.class, AttackRd, Utils.him);
Robot bestTarget = null;
double bestScore = 50;
for (int i = 0; i < objs.length; ++i) {
double score = RobotType.HQ.attackPower;
Robot dmg[] = rc.senseNearbyGameObjects(Robot.class, SplashRd, Utils.him);
score += dmg.length * RobotType.HQ.splashPower;
Robot ff[] = rc.senseNearbyGameObjects(Robot.class, SplashRd, Utils.me);
score -= ff.length * RobotType.HQ.splashPower;
if (score < bestScore) continue;
bestTarget = objs[i];
bestScore = score;
}
if (bestTarget == null) return;
rc.attackSquare(rc.senseLocationOf(bestTarget));
}
public static void run(RobotController rc) throws GameActionException
{
ProgressQuest pq = new ProgressQuest(rc);
while (true) {
ByteCode.Check bcCheck = new ByteCode.Check(rc);
if (rc.isActive() && spawn(rc));
else shoot(rc);
pq.update();
bcCheck.debug_check("Headquarter.end");
rc.yield();
}
}
}
|
package com.kii.thingif.internal.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.kii.thingif.TypedID;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class TypedIDAdapterTest {
@Test
public void serializationTest() {
TypedID[] typedIDs = {
new TypedID(TypedID.Types.USER, "id1"),
new TypedID(TypedID.Types.GROUP, "id2"),
new TypedID(TypedID.Types.THING, "id3")};
String[] expectedStrings = {
"user:id1",
"group:id2",
"thing:id3"};
Gson gson = new GsonBuilder()
.registerTypeAdapter(
TypedID.class,
new TypedIDAdapter())
.create();
Assert.assertEquals(
"size should be same",
expectedStrings.length,
typedIDs.length);
for (int i=0; i < expectedStrings.length; i++) {
String expectedString = expectedStrings[i];
Assert.assertEquals(
"failed on ["+i+"]",
expectedString,
gson.toJsonTree(typedIDs[i]).getAsString());
}
}
@Test
public void deserializationTest() {
TypedID[] expectedTypedIDs = {
new TypedID(TypedID.Types.USER, "id1"),
new TypedID(TypedID.Types.GROUP, "id2"),
new TypedID(TypedID.Types.THING, "id3")};
JsonElement[] jsons = {
new JsonPrimitive("user:id1"),
new JsonPrimitive("group:id2"),
new JsonPrimitive("thing:id3")};
Gson gson = new GsonBuilder()
.registerTypeAdapter(
TypedID.class,
new TypedIDAdapter())
.create();
for (int i=0; i<expectedTypedIDs.length; i++){
TypedID expectedTypedID = expectedTypedIDs[i];
TypedID deserializedTypedID = gson.fromJson(jsons[i], TypedID.class);
Assert.assertEquals(expectedTypedID.getType(), deserializedTypedID.getType());
Assert.assertEquals(expectedTypedID.getID(), deserializedTypedID.getID());
}
}
}
|
package mafiaserver;
/**
*
* @author Ryan Snell <ryansnell@me.com>
*/
public class ServerTurnController {
ServerTurnSequencer turnSequencer;
private boolean gameOver = false;
private boolean isDayTime = false;
private int dayCount = 0;
private int nightCount = 0;
public ServerTurnController(ServerTurnSequencer sts) {
this.turnSequencer = sts;
}
/**
* daySequence() Run the day sequence
*/
public void daySequence() {
// Reenable chat for all
for(Participant p : this.turnSequencer.getClients()) {
synchronized(p) {
p.changeSeeChatStatus(true);
p.changeTalkStatus(true);
p.changeVoteStatus(true);
}
}
this.promptDaytime();
this.promptTownspeople();
this.isDayTime = false;
this.dayCount++;
}
/**
* nightSequence() Run the night sequence
*/
public void nightSequence() {
/** In order to go to the next time of day, call turnSequencer.interrupt(); **/
this.promptNighttime();
if (this.nightCount == 0) {
// first night
// get mafia list
String mafiaList = "The following players are part of the mafia:\n"
+ this.turnSequencer.server.getMafiaList();
// output mafia list to all mafia
for(Participant p : this.turnSequencer.getClients())
{
if(p.hasRole() && p.isAlive())
{
if(p.getRole() != null && p.getRole().isMafia())
{
p.pushOutput(mafiaList);
}
}
}
this.promptMafia();
this.promptSheriff();
} else {
// regular night
this.promptMafia();
this.promptSheriff();
}
this.isDayTime = true;
this.nightCount++;
}
/**
* endGame() Mark the game as ended
*/
public void endGame() {
this.gameOver = true;
}
/**
* isGameOver()
*
* @return gameOver
*/
public boolean isGameOver() {
int mafiaCount = 0;
int townspeopleCount = 0;
for(Participant p : this.turnSequencer.getClients()) {
if(p.getRole() != null && p.isAlive() && p.isConnected()) {
if(p.getRole().isMafia()) {
mafiaCount++;
} else {
townspeopleCount++;
}
}
}
if(mafiaCount == 0 || mafiaCount > townspeopleCount)
this.gameOver = true;
else
this.gameOver = false;
return this.gameOver;
}
/**
* isDayTime()
*
* @return isDayTime
*/
public boolean isDayTime() {
return this.isDayTime;
}
/**
* promptMafia()
* Prompt the mafia to vote on murdering someone
*/
public void promptMafia() {
String prompt = "Mafia, it is your turn to nominate a person "
+ "to be killed.\nTo vote for a person, type and enter"
+ " `MURDER username`.\n";
for(Participant p : this.turnSequencer.getClients())
{
synchronized(p) {
if(p.getRole() != null && p.getRole().isMafia())
{
p.changeSeeChatStatus(true);
p.changeTalkStatus(true);
p.changeVoteStatus(true);
p.pushOutput(prompt);
}
else {
p.changeSeeChatStatus(false);
p.changeTalkStatus(false);
p.changeVoteStatus(false);
}
}
}
}
/**
* promptSheriff()
* Prompt the sheriff to accuse people of being members of the mafia
*/
public void promptSheriff() {
String prompt = "Sheriff, it is your turn to accuse a person "
+ "of being the mafia.\nTo accuse a person, type and enter"
+ " `ACCUSE username`.\n";
for(Participant p : this.turnSequencer.getClients())
{
synchronized(p) {
if(p.getRole() != null && p.getRole().getName().equals("Sheriff"))
{
p.changeSeeChatStatus(true);
p.changeTalkStatus(true);
p.changeVoteStatus(true);
p.pushOutput(prompt);
}
else {
p.changeSeeChatStatus(false);
p.changeTalkStatus(false);
p.changeVoteStatus(false);
}
}
}
}
/**
* broadcastSheriffs()
* Broadcast a message to all sheriffs
* @param s Message
*/
public void broadcastSheriffs(String s) {
for(Participant p : this.turnSequencer.getClients())
{
synchronized(p) {
if(p.getRole() != null && p.getRole().getName().equals("Sheriff"))
{
p.pushOutput("(NARRATOR) " + s);
}
}
}
}
/**
* promptTownspeople()
* Prompt the townspeople to vote for someone to be lynched
*/
public void promptTownspeople() {
String prompt = "Townspeople, it is your turn to accuse someone "
+ "of being part of the mafia.\nTo accuse a person, type and enter"
+ " `VOTE username`.\n";
this.blastPrompt(prompt);
}
/**
* promptNighttime()
* Prompt the townspeople that it is night time
*/
public void promptNighttime() {
String prompt = "Night has fallen upon us.\n";
this.blastPrompt(prompt);
}
/**
* promptDaytime()
* Prompt the townspeople that it is day time
*/
public void promptDaytime() {
String prompt = "The sun has risen.\n";
this.blastPrompt(prompt);
}
/**
* blastPrompt()
* Send a prompt to all connected clients
* @param s Message to broadcast
*/
public void blastPrompt(String s) {
ServerMessageBroadcaster broadcast =
new ServerMessageBroadcaster(
this.turnSequencer.server.clients.get(0),
this.turnSequencer.server.clients,
s);
broadcast.start();
}
}
|
package org.sakaiproject.evaluation.tool.renderers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.sakaiproject.evaluation.constant.EvalConstants;
import org.sakaiproject.evaluation.logic.EvalAuthoringService;
import org.sakaiproject.evaluation.model.EvalItem;
import org.sakaiproject.evaluation.model.EvalScale;
import org.sakaiproject.evaluation.model.EvalTemplateItem;
import org.sakaiproject.evaluation.tool.EvalToolConstants;
import org.sakaiproject.evaluation.tool.utils.RenderingUtils;
import org.sakaiproject.evaluation.utils.ArrayUtils;
import uk.org.ponder.arrayutil.MapUtil;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIJointContainer;
import uk.org.ponder.rsf.components.UILink;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.components.UISelectLabel;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.components.decorators.DecoratorList;
import uk.org.ponder.rsf.components.decorators.UIDisabledDecorator;
import uk.org.ponder.rsf.components.decorators.UIFreeAttributeDecorator;
import uk.org.ponder.rsf.components.decorators.UIStyleDecorator;
/**
* This handles the rendering of scaled type items
*
* @author Aaron Zeckoski (aaronz@vt.edu)
*/
public class BlockRenderer implements ItemRenderer {
private EvalAuthoringService authoringService;
public void setAuthoringService(EvalAuthoringService authoringService) {
this.authoringService = authoringService;
}
/**
* This identifies the template component associated with this renderer
*/
public static final String COMPONENT_ID = "render-block-item:";
/* (non-Javadoc)
* @see org.sakaiproject.evaluation.tool.renderers.ItemRenderer#renderItem(uk.org.ponder.rsf.components.UIContainer, java.lang.String, org.sakaiproject.evaluation.model.EvalTemplateItem, int, boolean)
*/
@SuppressWarnings("unchecked")
public UIJointContainer renderItem(UIContainer parent, String ID, String[] bindings, EvalTemplateItem templateItem, int displayNumber, boolean disabled, Map<String, Object> renderProperties) {
// check to make sure we are only dealing with block parents
if (templateItem.getBlockParent() == null) {
throw new IllegalArgumentException("Block renderer can only work for block items, this templateItem ("+templateItem.getId()+") has a null block parent");
} else if (! templateItem.getBlockParent().booleanValue() ||
templateItem.getBlockId() != null) {
throw new IllegalArgumentException("Block renderer can only work for block parents, this templateItem ("+templateItem.getId()+") is a block child");
}
List<EvalTemplateItem> childList = templateItem.childTemplateItems;
if (childList == null || childList.isEmpty()) {
// get the list of children the slow way if we have to
childList = authoringService.getBlockChildTemplateItemsForBlockParent(templateItem.getId(), false);
}
// check that the child count matches the bindings count
if ( ! disabled && (childList.size() != bindings.length) ) {
throw new IllegalArgumentException("The bindings array ("+bindings.length+") must match the size of the block child count ("+childList.size()+")");
}
UIJointContainer container = new UIJointContainer(parent, ID, COMPONENT_ID);
if (displayNumber <= 0) displayNumber = 0;
String initValue = null;
if (bindings[0] == null) initValue = "";
EvalScale scale = templateItem.getItem().getScale();
String[] scaleOptions = scale.getOptions();
int optionCount = scaleOptions.length;
// handle NA
boolean usesNA = templateItem.getUsesNA().booleanValue();
String scaleValues[] = new String[optionCount];
String scaleLabels[] = new String[optionCount];
String scaleDisplaySetting = templateItem.getScaleDisplaySetting();
// matrix block
if (templateItem.getScaleDisplaySetting().equals(EvalConstants.ITEM_SCALE_DISPLAY_MATRIX) ||
templateItem.getScaleDisplaySetting().equals(EvalConstants.ITEM_SCALE_DISPLAY_MATRIX_COLORED)) {
for (int count = 1; count <= optionCount; count++) {
scaleValues[optionCount - count] = new Integer(optionCount - count).toString();
scaleLabels[optionCount - count] = scaleOptions[count-1];
}
if (usesNA) {
scaleValues = ArrayUtils.appendArray(scaleValues, EvalConstants.NA_VALUE.toString());
scaleLabels = ArrayUtils.appendArray(scaleLabels, "");
}
UIBranchContainer matrixGroup = UIBranchContainer.make(container, "matrixGroupDisplay:");
if (usesNA) {
matrixGroup.decorate( new UIStyleDecorator("use-na") );
}
// display header labels
List<String> headerLabels = RenderingUtils.getMatrixLabels(scaleOptions);
UIOutput.make(matrixGroup, "label-start", headerLabels.get(0));
UIOutput.make(matrixGroup, "label-end", headerLabels.get(1));
if (headerLabels.size() == 3) {
UIOutput.make(matrixGroup, "label-middle", headerLabels.get(2));
}
UIOutput.make(matrixGroup,"label-na", "NA");
UIVerbatim.make(matrixGroup, "matrixGroupTitle", templateItem.getItem().getItemText());
// iterate through each question in the block
for (int j = 0; j < childList.size(); j++) {
// build the question row container and apply decorations
UIBranchContainer matrix = UIBranchContainer.make(matrixGroup, "matrixDisplay:", j+"");
if (usesNA) {
matrix.decorate( new UIStyleDecorator("use-na") );
}
// get the child item
EvalTemplateItem childTemplateItem = (EvalTemplateItem) childList.get(j);
EvalItem childItem = childTemplateItem.getItem();
Map<String, Object> childRenderProperties = (Map<String, Object>) renderProperties.get("child-" + childTemplateItem.getId());
if (childRenderProperties.containsKey(ItemRenderer.EVAL_PROP_RENDER_INVALID)) {
matrix.decorate( new UIStyleDecorator("validFail") ); // must match the existing CSS class
} else if ( childRenderProperties.containsKey(ItemRenderer.EVAL_PROP_ANSWER_REQUIRED) ) {
matrix.decorate( new UIStyleDecorator("compulsory") ); // must match the existing CSS class
}
// display question text
UIOutput.make(matrix, "itemNum", Integer.valueOf(displayNumber + j).toString() ); //$NON-NLS-2$
UIVerbatim.make(matrix, "itemText", childItem.getItemText());
UIBranchContainer rowBranch = UIBranchContainer.make(matrix, "response-list:");
// Bind the answers to a list of answers in evaluation bean (if enabled)
String childBinding = null;
if (! disabled && bindings != null) {
childBinding = bindings[j];
}
UISelect childRadios = UISelect.make(rowBranch, "childRadio", scaleValues, scaleLabels, childBinding, initValue);
String selectID = childRadios.getFullID();
if (disabled) {
childRadios.selection.willinput = false;
childRadios.selection.fossilize = false;
}
int scaleLength = scaleValues.length;
int limit = usesNA ? scaleLength - 1: scaleLength; // skip the NA value at the end
for (int k = 0; k < limit; ++k) {
UIBranchContainer radioBranchSecond = UIBranchContainer.make(rowBranch, "scaleOption:", k+"");
UISelectChoice.make(radioBranchSecond, "radioValue", selectID, k);
// scaleLabels are in reverse order, indexed from (end - 1) to 0. If usesNA,
// an empty label is appended; ignore that one too
int labelIndex = scaleLabels.length - k - (usesNA ? 2 : 1);
UIVerbatim.make(radioBranchSecond, "radioValueLabel", scaleLabels[labelIndex]);
}
// display the N/A radio button always; use CSS to hide if not needed (via the "use-na" class (above)
UIBranchContainer labelContainer = UIBranchContainer.make(rowBranch, "na-input-label:");
UISelectChoice naChoice = UISelectChoice.make(labelContainer, "na-input", selectID, scaleLength - 1);
if (!usesNA) {
naChoice.decorate( new UIDisabledDecorator());
}
UIMessage.make(rowBranch, "radioValueLabelNa", "viewitem.na.desc");
}
// stepped block
} else {
UIBranchContainer blockStepped = UIBranchContainer.make(container, "blockStepped:");
// setup simple variables to make code more clear
boolean colored = EvalConstants.ITEM_SCALE_DISPLAY_STEPPED_COLORED.equals(scaleDisplaySetting) ||
EvalConstants.ITEM_SCALE_DISPLAY_MATRIX_COLORED.equals(scaleDisplaySetting);
for (int count = 1; count <= optionCount; count++) {
scaleValues[optionCount - count] = Integer.toString(optionCount - count);
scaleLabels[optionCount - count] = scaleOptions[count-1];
}
// handle ideal coloring
String idealImage = "";
if (colored) {
String ideal = scale.getIdeal();
// Get the scale ideal value (none, low, mid, high )
if (ideal == null) {
// When no ideal is specified then just plain blue for both start and end
idealImage = EvalToolConstants.COLORED_IMAGE_URLS[0];
} else if (EvalConstants.SCALE_IDEAL_LOW.equals(ideal)) {
idealImage = EvalToolConstants.COLORED_IMAGE_URLS[1];
} else if (EvalConstants.SCALE_IDEAL_MID.equals(ideal)) {
idealImage = EvalToolConstants.COLORED_IMAGE_URLS[2];
} else if (EvalConstants.SCALE_IDEAL_HIGH.equals(ideal)) {
idealImage = EvalToolConstants.COLORED_IMAGE_URLS[3];
} else if (EvalConstants.SCALE_IDEAL_OUTSIDE.equals(ideal)) {
idealImage = EvalToolConstants.COLORED_IMAGE_URLS[4];
} else {
// use no decorators
}
}
// Radio Buttons
UISelect radioLabel = UISelect.make(blockStepped, "radioLabel", scaleValues, scaleLabels, null, false);
String selectIDLabel = radioLabel.getFullID();
if (usesNA) {
scaleValues = ArrayUtils.appendArray(scaleValues, EvalConstants.NA_VALUE.toString());
scaleLabels = ArrayUtils.appendArray(scaleLabels, "");
UIMessage.make(blockStepped, "na-desc", "viewitem.na.desc");
}
// render the stepped labels and images
int scaleLength = scaleValues.length;
int limit = usesNA ? scaleLength - 1: scaleLength; // skip the NA value at the end
for (int j = 0; j < limit; ++j) {
UIBranchContainer rowBranch = UIBranchContainer.make(blockStepped, "blockRowBranch:", j+"");
// put in the block header text (only once)
if (j == 0) {
UIVerbatim headerText = UIVerbatim.make(rowBranch, "itemText", templateItem.getItem().getItemText());
headerText.decorators =
new DecoratorList(new UIFreeAttributeDecorator( MapUtil.make("rowspan", (optionCount + 1) + "") ));
// add render markers if they are set for this block parent
if ( renderProperties.containsKey(ItemRenderer.EVAL_PROP_RENDER_INVALID) ) {
rowBranch.decorate( new UIStyleDecorator("validFail") ); // must match the existing CSS class
} else if ( renderProperties.containsKey(ItemRenderer.EVAL_PROP_ANSWER_REQUIRED) ) {
rowBranch.decorate( new UIStyleDecorator("compulsory") ); // must match the existing CSS class
}
}
// Actual label
UISelectLabel.make(rowBranch, "topLabel", selectIDLabel, j);
// Corner Image
UILink.make(rowBranch, "cornerImage", EvalToolConstants.STEPPED_IMAGE_URLS[0]);
// This branch container is created to help in creating the middle images after the LABEL
for (int k = 0; k < j; ++k) {
UIBranchContainer afterTopLabelBranch = UIBranchContainer.make(rowBranch, "blockAfterTopLabelBranch:", k+"");
UILink.make(afterTopLabelBranch, "middleImage", EvalToolConstants.STEPPED_IMAGE_URLS[1]);
}
// the down arrow images
UIBranchContainer bottomLabelBranch = UIBranchContainer.make(blockStepped, "blockBottomLabelBranch:", j+"");
UILink.make(bottomLabelBranch, "bottomImage", EvalToolConstants.STEPPED_IMAGE_URLS[2]);
}
// the child items rendering loop
for (int j = 0; j < childList.size(); j++) {
// get the child item
EvalTemplateItem childTemplateItem = (EvalTemplateItem) childList.get(j);
EvalItem childItem = childTemplateItem.getItem();
// get mapping props for the child
Map<String, Object> childRenderProps = (Map<String, Object>) renderProperties.get("child-"+childTemplateItem.getId());
if (childRenderProps == null) {
childRenderProps = new HashMap<String, Object>(0);
}
// For the radio buttons
UIBranchContainer childRow = UIBranchContainer.make(blockStepped, "childRow:", j+"" );
if ( childRenderProps.containsKey(ItemRenderer.EVAL_PROP_RENDER_INVALID) ) {
childRow.decorate( new UIStyleDecorator("validFail") ); // must match the existing CSS class
} else if ( childRenderProps.containsKey(ItemRenderer.EVAL_PROP_ANSWER_REQUIRED) ) {
childRow.decorate( new UIStyleDecorator("compulsory") ); // must match the existing CSS class
}
if (colored) {
UILink.make(childRow, "idealImage", idealImage);
}
// put in the item information (number and text)
UIOutput.make(childRow, "childNum", new Integer(displayNumber + j).toString() );
UIVerbatim.make(childRow, "childText", childItem.getItemText());
// Bind the answers to a list of answers in evaluation bean (if enabled)
String childBinding = null;
if (! disabled && bindings != null) {
childBinding = bindings[j];
}
UISelect childRadios = UISelect.make(childRow, "childRadio", scaleValues, scaleLabels, childBinding, initValue);
String selectID = childRadios.getFullID();
if (disabled) {
childRadios.selection.willinput = false;
childRadios.selection.fossilize = false;
}
if (usesNA) {
UIBranchContainer na = UIBranchContainer.make(childRow, "na-parent:");
UISelectChoice.make(childRow, "na-input", selectID, scaleLength - 1);
}
// render child radio choices
for (int k = 0; k < limit; ++k) {
if (colored) {
UIBranchContainer radioBranchFirst = UIBranchContainer.make(childRow, "scaleOptionColored:", k+"");
UISelectChoice.make(radioBranchFirst, "radioValueColored", selectID, k);
// this is confusing but this is now the one underneath
UIBranchContainer radioBranchSecond = UIBranchContainer.make(childRow, "scaleOption:", k+"");
UIOutput.make(radioBranchSecond, "radioValue");
} else {
UIBranchContainer radioBranchSecond = UIBranchContainer.make(childRow, "scaleOption:", k+"");
UISelectChoice.make(radioBranchSecond, "radioValue", selectID, k);
}
}
}
}
return container;
}
/* (non-Javadoc)
* @see org.sakaiproject.evaluation.tool.renderers.ItemRenderer#getRenderType()
*/
public String getRenderType() {
return EvalConstants.ITEM_TYPE_BLOCK_PARENT;
}
}
|
package org.sakaiproject.profilewow.tool.producers;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.common.edu.person.SakaiPerson;
import org.sakaiproject.api.common.edu.person.SakaiPersonManager;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.profilewow.tool.params.ImageViewParamaters;
import org.sakaiproject.profilewow.tool.producers.templates.ProfilePicRenderer;
import org.sakaiproject.profilewow.tool.util.ResourceUtil;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.user.api.UserDirectoryService;
import uk.org.ponder.messageutil.TargettedMessageList;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.components.UILink;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.flow.ARIResult;
import uk.org.ponder.rsf.flow.ActionResultInterceptor;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.stringutil.StringList;
public class ChangePicture implements ViewComponentProducer, ActionResultInterceptor {
private static Log log = LogFactory.getLog(ChangePicture.class);
private static final String NO_PIC_URL = ProfilePicRenderer.NO_PIC_URL;
public static final String VIEW_ID="changepic";
public String getViewID() {
// TODO Auto-generated method stub
return VIEW_ID;
}
private SakaiPersonManager spm;
public void setSakaiPersonManager(SakaiPersonManager in) {
spm = in;
}
private ResourceUtil resourceUtil;
public void setResourceUtil(ResourceUtil ru) {
resourceUtil = ru;
}
private TargettedMessageList tml;
public void setTargettedMessageList(TargettedMessageList tml) {
this.tml = tml;
}
public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
// TODO Auto-generated method stub
ContentCollection pCollection = resourceUtil.getUserCollection();
log.debug("got a collection with " + pCollection.getMemberCount() + " objects");
SakaiPerson sPerson = spm.getSakaiPerson(spm.getUserMutableType());
//picture stuff
String picUrl = sPerson.getPictureUrl();
if (picUrl == null || picUrl.trim().length() == 0)
picUrl = NO_PIC_URL;
else
picUrl = sPerson.getPictureUrl();
if (sPerson.isSystemPicturePreferred() != null && sPerson.isSystemPicturePreferred().booleanValue()) {
//System pic present and set to active
//UIOutput.make(tofill, "remove-image-link");
UIBranchContainer uib = UIBranchContainer.make(tofill, "selected-image:");
UIInternalLink.make(uib, "selected-image", new ImageViewParamaters("imageServlet", sPerson.getAgentUuid()));
UIBranchContainer uib2 = UIBranchContainer.make(tofill, "no-image:");
UIInternalLink.make(uib2, "no-image", NO_PIC_URL);
//UIMessage.make(tofill, "current-pic-title", "current.picture.title.official");
} else if (sPerson.isSystemPicturePreferred() == null || !sPerson.isSystemPicturePreferred().booleanValue() ) {
UIBranchContainer uib = UIBranchContainer.make(tofill, "selected-image:");
UILink.make(uib, "selected-image", picUrl);
if (!picUrl.equals(NO_PIC_URL)) {
//UIOutput.make(tofill, "remove-image-link");
//UIMessage.make(tofill, "current-pic-title", "current.picture.title");
UIBranchContainer uib2 = UIBranchContainer.make(tofill, "no-image:");
UIInternalLink.make(uib2, "no-image", NO_PIC_URL);
}else{
//no profile image at all
//UIMessage.make(tofill, "warning-no-image", "warning.picture.set");
//UIMessage.make(tofill, "current-pic-title", "current.picture.title.noimage");
//UIBranchContainer uib2 = UIBranchContainer.make(tofill, "no-image:");
//UIInternalLink.make(uib2, "no-image", NO_PIC_URL);
}
//should only display if there is an official pic
if (hasProfilePic()) {
UIBranchContainer op = UIBranchContainer.make(tofill, "official-pic:");
UIMessage.make(op, "official-pic-title", "official.picture.title");
UIInternalLink.make(op, "official-pic-image", new ImageViewParamaters("imageServlet", sPerson.getAgentUuid() ));
UIBranchContainer op2 = UIBranchContainer.make(tofill, "official-pic-form:");
UIForm form = UIForm.make(op2, "official-pic-form");
UICommand.make(form, "official-pic-field", UIMessage.make("useOfficialSub"),"uploadBean.useOfficial");
}
}
UIForm formUpload = UIForm.make(tofill, "upload-pic-form");
//UIInput.make(form,"file-upload", "uploadBean")
UICommand.make(formUpload,"submit","uploadBean.processUpload");
UIForm form = UIForm.make(tofill,"form");
List<ContentResource> resources = pCollection.getMemberResources();
UISelect selectPic = UISelect.makeMultiple(form, "select-pic",
null, "uploadBean.picUrl", new String[] {});
StringList selections = new StringList();
for (int i = 0; i < resources.size(); i++) {
//UIBranchContainer row = UIBranchContainer.make(form, "pic-row:");
//for (int q =0; q < 5 && i< resources.size(); q++) {
ContentResource resource = (ContentResource)resources.get(i);
String rUrl = resource.getUrl();
if(!rUrl.equals(picUrl)){
UIBranchContainer cell = UIBranchContainer.make(tofill, "pic-cell:");
selections.add(rUrl);
UISelectChoice choice = UISelectChoice.make(cell, "select", selectPic.getFullID(), (selections.size() -1 ));
UILink.make(cell, "pic", rUrl);
}
}
selectPic.optionlist.setValue(selections.toStringArray());
UICommand.make(form, "submit","Change picture","uploadBean.changePicture");
}
private boolean hasProfilePic() {
SakaiPerson sp = spm.getSakaiPerson(spm.getSystemMutableType());
if (sp == null)
return false;
else if (sp.getJpegPhoto() != null)
return true;
return false;
}
public void interceptActionResult(ARIResult result,
ViewParameters incoming, Object actionReturn) {
// TODO Auto-generated method stub
result.resultingView = new SimpleViewParameters(MainProducer.VIEW_ID);
log.warn("intecept object.");
}
}
|
package ascenseur.traitement;
import java.util.*;
public class Etage {
public Etage(int numE) {
numEtage=numE;
}
private Integer numEtage;
public Integer getNumEtage() {
return numEtage;
}
public int compareEtage(Etage etageCourant) {
return numEtage.compareTo(etageCourant.getNumEtage());
}
}
|
package com.intellij.uiDesigner.designSurface;
import com.intellij.uiDesigner.radComponents.RadContainer;
import com.intellij.uiDesigner.radComponents.RadComponent;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.reference.SoftReference;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import java.awt.*;
/**
* @author yole
*/
public class CachedGridImage {
private static final Object CACHED_GRID_IMAGE_KEY = new Object();
private static float[] ourDashes = new float[] { 3.0f, 1.0f };
private Image myImage;
private int[] myHorzGridLines;
private int[] myVertGridLines;
private int[] myRows;
private int[] myRowSpans;
private int[] myCols;
private int[] myColSpans;
private CachedGridImage(final RadContainer container) {
final GraphicsConfiguration graphicsConfiguration =
WindowManagerEx.getInstanceEx().getFrame(container.getModule().getProject()).getGraphicsConfiguration();
if (container.getWidth() * container.getHeight() < 4096*4096) {
myImage = graphicsConfiguration.createCompatibleImage(container.getWidth(), container.getHeight(),
Transparency.BITMASK);
update(container);
}
else {
// create fake image for insanely large containers
myImage = graphicsConfiguration.createCompatibleImage(16, 16, Transparency.BITMASK);
}
}
private void update(final RadContainer container) {
if (container.getWidth() * container.getHeight() >= 4096*4096) return;
int count = container.getComponentCount();
int[] rows = new int[count];
int[] rowSpans = new int[count];
int[] cols = new int[count];
int[] colSpans = new int[count];
for(int i=0; i<count; i++) {
GridConstraints c = container.getComponent(i).getConstraints();
rows [i] = c.getRow();
rowSpans [i] = c.getRowSpan();
cols [i] = c.getColumn();
colSpans [i] = c.getColSpan();
}
int[] horzGridLines = container.getGridLayoutManager().getHorizontalGridLines(container);
int[] vertGridLines = container.getGridLayoutManager().getVerticalGridLines(container);
if (!arraysEqual(horzGridLines, myHorzGridLines) ||
!arraysEqual(vertGridLines, myVertGridLines) ||
!arraysEqual(rows, myRows) ||
!arraysEqual(rowSpans, myRowSpans) ||
!arraysEqual(cols, myCols) ||
!arraysEqual(colSpans, myColSpans)) {
myHorzGridLines = horzGridLines;
myVertGridLines = vertGridLines;
myRows = rows;
myRowSpans = rowSpans;
myCols = cols;
myColSpans = colSpans;
repaint(container);
}
}
private void repaint(final RadContainer container) {
final int width = container.getWidth();
final int height = container.getHeight();
if (width * height >= 4096*4096) return;
Graphics2D g2d = (Graphics2D) myImage.getGraphics();
try {
g2d.setComposite(AlphaComposite.Clear);
g2d.fillRect(0, 0, width, height);
g2d.setComposite(AlphaComposite.Src);
if (container.isSelected()) {
g2d.setColor(Painter.SELECTED_GRID_COLOR);
}
else {
g2d.setColor(Painter.NON_SELECTED_GRID_COLOR);
}
g2d.setStroke(new BasicStroke(1.0f, 0, 0, 1.0f, ourDashes, 0.0f));
if (myHorzGridLines.length > 0) {
int lastLine = (container.getDelegee().getHeight() - myHorzGridLines [myHorzGridLines.length-1] > 4)
? myHorzGridLines.length
: myHorzGridLines.length-1;
for (int i = 1; i < lastLine; i++) {
final int y = myHorzGridLines [i];
g2d.drawLine(0, y, width, y);
}
}
if (myVertGridLines.length > 0) {
// Vertical lines
int lastLine = (container.getDelegee().getWidth() - myVertGridLines [myVertGridLines.length-1] > 4)
? myVertGridLines.length
: myVertGridLines.length-1;
for (int i = 1; i < lastLine; i++) {
final int x = myVertGridLines [i];
g2d.drawLine(x, 0, x, height);
}
}
g2d.setComposite(AlphaComposite.Clear);
g2d.setStroke(new BasicStroke(1.0f));
for(RadComponent childComponent: container.getComponents()) {
final GridConstraints constraints = childComponent.getConstraints();
if (constraints.getColSpan() > 1) {
for(int col = constraints.getColumn()+1; col < constraints.getColumn() + constraints.getColSpan(); col++) {
g2d.drawLine(myVertGridLines [col],
myHorzGridLines [constraints.getRow()]+4,
myVertGridLines [col],
myHorzGridLines [constraints.getRow() + constraints.getRowSpan()]-4);
}
}
if (constraints.getRowSpan() > 1) {
for(int row = constraints.getRow()+1; row < constraints.getRow() + constraints.getRowSpan(); row++) {
g2d.drawLine(myVertGridLines [constraints.getColumn()]+4,
myHorzGridLines [row],
myVertGridLines [constraints.getColumn() + constraints.getColSpan()]-4,
myHorzGridLines [row]);
}
}
}
}
finally {
g2d.dispose();
}
}
private static boolean arraysEqual(final int[] newArray, final int[] oldArray) {
if (oldArray == null || newArray.length != oldArray.length) {
return false;
}
for(int i=0; i<oldArray.length; i++) {
if (newArray [i] != oldArray [i]) {
return false;
}
}
return true;
}
private boolean sizeEquals(final RadContainer container) {
return myImage.getWidth(null) == container.getWidth() &&
myImage.getHeight(null) == container.getHeight();
}
private Image getImage() {
return myImage;
}
public static Image getGridImage(final RadContainer container) {
CachedGridImage gridImage = null;
//noinspection unchecked
SoftReference<CachedGridImage> imageRef = (SoftReference<CachedGridImage>) container.getDelegee().getClientProperty(CACHED_GRID_IMAGE_KEY);
if (imageRef != null) {
gridImage = imageRef.get();
}
if (gridImage != null && gridImage.sizeEquals(container)) {
gridImage.update(container);
}
else {
gridImage = new CachedGridImage(container);
container.getDelegee().putClientProperty(CACHED_GRID_IMAGE_KEY,
new SoftReference<CachedGridImage>(gridImage));
}
return gridImage.getImage();
}
}
|
package io.vertx.ext.web.handler.impl;
import java.util.List;
import java.util.Objects;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.MIMEHeader;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.ErrorHandler;
import io.vertx.ext.web.impl.HeaderTooLongException;
import io.vertx.ext.web.impl.Utils;
public class ErrorHandlerImpl implements ErrorHandler {
/**
* Flag to enable/disable printing the full stack trace of exceptions.
*/
private final boolean displayExceptionDetails;
/**
* Cached template for rendering the html errors
*/
private final String errorTemplate;
public ErrorHandlerImpl(String errorTemplateName, boolean displayExceptionDetails) {
Objects.requireNonNull(errorTemplateName);
this.displayExceptionDetails = displayExceptionDetails;
this.errorTemplate = Utils.readResourceToBuffer(errorTemplateName).toString();
}
@Override
public void handle(RoutingContext context) {
HttpServerResponse response = context.response();
Throwable failure = context.failure();
if(answerWithKnownFailure(context)){
return;
}
int errorCode = context.statusCode();
String errorMessage = null;
if (errorCode != -1) {
context.response().setStatusCode(errorCode);
errorMessage = context.response().getStatusMessage();
} else {
errorCode = 500;
if (displayExceptionDetails) {
errorMessage = failure.getMessage();
}
if (errorMessage == null) {
errorMessage = "Internal Server Error";
}
// no new lines are allowed in the status message
response.setStatusMessage(errorMessage.replaceAll("\\r|\\n", " "));
}
answerWithError(context, errorCode, errorMessage);
}
private boolean answerWithKnownFailure(RoutingContext context) {
Throwable failure = context.failure();
if(failure instanceof HeaderTooLongException){
answerWithError(context, 400, "A header was too long to process");
return true;
}
return false;
}
private void answerWithError(RoutingContext context, int errorCode, String errorMessage){
context.response().setStatusCode(errorCode);
if( !sendErrorResponseMIME(context, errorCode, errorMessage) &&
!sendErrorAcceptMIME(context, errorCode, errorMessage)
){
// fallback plain/text
sendError(context, "text/plain", errorCode, errorMessage);
}
}
private boolean sendErrorResponseMIME(RoutingContext context, int errorCode, String errorMessage){
// does the response already set the mime type?
String mime = context.response().headers().get(HttpHeaders.CONTENT_TYPE);
return mime != null && sendError(context, mime, errorCode, errorMessage);
}
private boolean sendErrorAcceptMIME(RoutingContext context, int errorCode, String errorMessage){
// respect the client accept order
List<MIMEHeader> acceptableMimes = context.parsedHeaders().accept();
for (MIMEHeader accept : acceptableMimes) {
if (sendError(context, accept.value(), errorCode, errorMessage)) {
return true;
}
}
return false;
}
private boolean sendError(RoutingContext context, String mime, int errorCode, String errorMessage) {
final String title = "Matron!";
HttpServerResponse response = context.response();
if (mime.startsWith("text/html")) {
StringBuilder stack = new StringBuilder();
if (context.failure() != null && displayExceptionDetails) {
for (StackTraceElement elem: context.failure().getStackTrace()) {
stack.append("<li>").append(elem).append("</li>");
}
}
response.putHeader(HttpHeaders.CONTENT_TYPE,"text/html");
response.end(
errorTemplate.replace("{title}", title)
.replace("{errorCode}", Integer.toString(errorCode))
.replace("{errorMessage}", errorMessage)
.replace("{stackTrace}", stack.toString())
);
return true;
}
if (mime.startsWith("application/json")) {
JsonObject jsonError = new JsonObject();
jsonError.put("error", new JsonObject().put("code", errorCode).put("message", errorMessage));
if (context.failure() != null && displayExceptionDetails) {
JsonArray stack = new JsonArray();
for (StackTraceElement elem: context.failure().getStackTrace()) {
stack.add(elem.toString());
}
jsonError.put("stack", stack);
}
response.putHeader(HttpHeaders.CONTENT_TYPE, "application/json");
response.end(jsonError.encode());
return true;
}
if (mime.startsWith("text/plain")) {
response.putHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
StringBuilder sb = new StringBuilder();
sb.append("Error ");
sb.append(errorCode);
sb.append(": ");
sb.append(errorMessage);
if (context.failure() != null && displayExceptionDetails) {
for (StackTraceElement elem: context.failure().getStackTrace()) {
sb.append("\tat ").append(elem).append("\n");
}
}
response.end(sb.toString());
return true;
}
return false;
}
}
|
package edu.cornell.mannlib.vitro.webapp.auth.policy;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.IsRootUser;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount.Status;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
/**
* If the user has an IsRootUser identifier, they can do anything!
*
* On setup, check to see that there is a root user. If not, create one. If we
* can't create one, abort.
*/
public class RootUserPolicy implements PolicyIface {
private static final Log log = LogFactory.getLog(RootUserPolicy.class);
private static final String PROPERTY_ROOT_USER_EMAIL = "rootUser.emailAddress";
private static final String ROOT_USER_INITIAL_PASSWORD = "rootPassword";
/**
* This is the entire policy. If you are a root user, you are authorized.
*/
@Override
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
RequestedAction whatToAuth) {
if (IsRootUser.isRootUser(whoToAuth)) {
return new BasicPolicyDecision(Authorization.AUTHORIZED,
"RootUserPolicy: approved");
} else {
return new BasicPolicyDecision(Authorization.INCONCLUSIVE,
"not root user");
}
}
@Override
public String toString() {
return "RootUserPolicy - " + hashCode();
}
// Setup class
public static class Setup implements ServletContextListener {
private ServletContext ctx;
private StartupStatus ss;
private String configRootEmail;
private UserAccountsDao uaDao;
@Override
public void contextInitialized(ServletContextEvent sce) {
ctx = sce.getServletContext();
ss = StartupStatus.getBean(ctx);
try {
uaDao = getUserAccountsDao();
configRootEmail = getRootEmailFromConfig();
checkForWrongRootUser();
if (rootUserExists()) {
ss.info(this, "root user is " + configRootEmail);
} else {
createRootUser();
}
ServletPolicyList.addPolicy(ctx, new RootUserPolicy());
} catch (Exception e) {
ss.fatal(this, "Failed to set up the RootUserPolicy", e);
}
}
private UserAccountsDao getUserAccountsDao() {
WebappDaoFactory wadf = (WebappDaoFactory) ctx
.getAttribute("webappDaoFactory");
if (wadf == null) {
throw new IllegalStateException(
"No webappDaoFactory on the servlet context");
}
return wadf.getUserAccountsDao();
}
private String getRootEmailFromConfig() {
String email = ConfigurationProperties.getBean(ctx).getProperty(
PROPERTY_ROOT_USER_EMAIL);
if (email == null) {
throw new IllegalStateException(
"deploy.properties must contain a value for '"
+ PROPERTY_ROOT_USER_EMAIL + "'");
} else {
return email;
}
}
private void checkForWrongRootUser() {
UserAccount root = getRootUser();
if (root == null) {
return;
}
String actualRootEmail = root.getEmailAddress();
if (actualRootEmail.equals(configRootEmail)) {
return;
}
ss.warning(
this,
"The deploy.properties file specifies a root user of '"
+ configRootEmail
+ "', but the system already contains a root user named '"
+ actualRootEmail + "'. The user '"
+ configRootEmail + "' will not be created.");
}
private boolean rootUserExists() {
return (getRootUser() != null);
}
private UserAccount getRootUser() {
for (UserAccount ua : uaDao.getAllUserAccounts()) {
if (ua.isRootUser()) {
return ua;
}
}
return null;
}
/**
* TODO The first and last name should be left blank, so the user will
* be forced to edit them. However, that's not in place yet.
*/
private void createRootUser() {
String emailAddress = ConfigurationProperties.getBean(ctx)
.getProperty(PROPERTY_ROOT_USER_EMAIL);
if (emailAddress == null) {
throw new IllegalStateException(
"deploy.properties must contain a value for '"
+ PROPERTY_ROOT_USER_EMAIL + "'");
}
if (!Authenticator.isValidEmailAddress(emailAddress)) {
throw new IllegalStateException("Value for '"
+ PROPERTY_ROOT_USER_EMAIL
+ "' is not a valid email address: '" + emailAddress
+ "'");
}
if (null != uaDao.getUserAccountByEmail(emailAddress)) {
throw new IllegalStateException("Can't create root user - "
+ "an account already exists with email address '"
+ emailAddress + "'");
}
UserAccount ua = new UserAccount();
ua.setEmailAddress(emailAddress);
ua.setFirstName("root");
ua.setLastName("user");
ua.setMd5Password(Authenticator
.applyMd5Encoding(ROOT_USER_INITIAL_PASSWORD));
ua.setPasswordChangeRequired(true);
ua.setStatus(Status.ACTIVE);
ua.setRootUser(true);
uaDao.insertUserAccount(ua);
StartupStatus.getBean(ctx).info(this,
"Created root user as '" + emailAddress + "'");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Nothing to destroy
}
}
}
|
package foam.dao;
import foam.core.ClassInfo;
import foam.core.Detachable;
import foam.core.FObject;
import foam.core.X;
import foam.lib.json.JournalParser;
import foam.lib.json.Outputter;
import foam.mlang.order.Comparator;
import foam.mlang.predicate.Predicate;
import java.io.*;
public class JDAO
extends ProxyDAO
{
protected final File file_;
protected final Outputter outputter_ = new Outputter();
protected final BufferedWriter out_;
public JDAO(ClassInfo classInfo, String filename)
throws IOException
{
this(new MapDAO().setOf(classInfo), filename);
}
public JDAO(DAO delegate, String filename) throws IOException {
file_ = new File(filename).getAbsoluteFile();
if ( ! file_.exists() ) file_.createNewFile();
setDelegate(delegate);
loadJournal();
out_ = new BufferedWriter(new FileWriter(file_, true));
}
protected void loadJournal()
throws IOException
{
JournalParser journalParser = new JournalParser();
BufferedReader br = new BufferedReader(new FileReader(file_));
for ( String line ; ( line = br.readLine() ) != null ; ) {
if ( line.isEmpty() ) continue;
try {
char operation = line.charAt(0);
switch ( operation ) {
case 'p':
FObject object = journalParser.parseObject(line);
if ( object == null ) {
System.err.println("Journal Error, unable to parse: " + line);
} else {
getDelegate().put(object);
}
break;
case 'r':
Object id = journalParser.parseObjectId(line);
if ( id == null ) {
System.err.println("Journal Error, unable to parse: " + line);
} else {
getDelegate().remove(getDelegate().find(id));
}
}
} catch (Throwable t) {
System.err.println("Error reading journal line: " + line);
t.printStackTrace();
}
}
br.close();
}
/**
* persists data into FileJournal then calls the delegated DAO.
*
* @param obj
* @returns FObject
*/
@Override
public FObject put_(X x, FObject obj) {
try {
// TODO(drish): supress class name from output
out_.write("p(" + outputter_.stringify(obj) + ")");
out_.newLine();
out_.flush();
} catch (Throwable e) {
e.printStackTrace();
}
return getDelegate().put_(x, obj);
}
@Override
public FObject remove_(X x, FObject obj) {
Object id = ((AbstractDAO) getDelegate()).getPrimaryKey().get(obj);
try {
// TODO: User Property toJSON() support when ready, since
// this code doesn't support multi-part keys or escaping "'s in the id.
if ( id instanceof String ) {
out_.write("r({\"id\":\"" + id + "\"})");
} else {
out_.write("r({\"id\":" + id + "})");
}
out_.newLine();
out_.flush();
} catch (IOException e) {
e.printStackTrace();
}
return getDelegate().remove_(x, obj);
}
@Override
public void removeAll_(final X x, long skip, final long limit, Comparator order, Predicate predicate) {
// file.delete();
getDelegate().select_(x, new RemoveSink(this), skip, limit, order, predicate);
getDelegate().removeAll_(x, skip, limit, order, predicate);
}
}
|
package build.pluto.cli;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.sugarj.common.path.AbsolutePath;
import org.sugarj.common.path.Path;
import org.sugarj.common.path.RelativePath;
import org.sugarj.common.util.Pair;
public class InputParser<In> {
private final Class<In> inputClass;
private Constructor<In> inputConstructor;
private Option[] inputOptions;
public InputParser(Class<In> inputClass) {
this.inputClass = inputClass;
}
@SuppressWarnings("unchecked")
private Constructor<In> getInputConstructor() {
if (inputConstructor != null)
return inputConstructor;
for (Constructor<?> c : inputClass.getConstructors()) {
if (c.isAccessible())
continue;
else if (inputConstructor == null)
inputConstructor = (Constructor<In>) c;
else if (inputConstructor.getParameters().length < c.getParameters().length)
inputConstructor = (Constructor<In>) c;
}
return inputConstructor;
}
public void registerOptions(Options options) {
Constructor<In> c = getInputConstructor();
inputOptions = new Option[c.getParameters().length];
for (int i = 0; i < c.getParameters().length; i++) {
String name = c.getParameters()[i].getName();
Class<?> paramClass = c.getParameters()[i].getType();
Option opt = makeOption(name, paramClass);
options.addOption(opt);
inputOptions[i] = opt;
}
}
private Option makeOption(String name, Class<?> paramClass) {
String optName = makeOptionName(name);
String desc = "Value for constructor parameter " + name + " of type " + pretty(paramClass);
if (paramClass.equals(boolean.class) || paramClass.equals(Boolean.class))
return new Option(null, optName, false, desc);
Option opt = new Option(null, optName, true, desc);
if (paramClass.isArray() || Collection.class.isAssignableFrom(paramClass)) {
opt.setArgs(Option.UNLIMITED_VALUES);
opt.setValueSeparator(' ');
// opt.setDescription(desc + ", separate values by '" + File.pathSeparatorChar + "'");
}
return opt;
}
private String makeOptionName(String s) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isUpperCase(c))
builder.append('-').append(Character.toLowerCase(c));
else
builder.append(c);
}
return builder.toString();
}
public In parseCommandLine(CommandLine line) {
Objects.requireNonNull(inputConstructor);
Objects.requireNonNull(inputOptions);
Object[] inputs = new Object[inputOptions.length];
for (int i = 0; i < inputs.length; i++) {
Option opt = inputOptions[i];
Class<?> paramClass = inputConstructor.getParameters()[i].getType();
if (line.hasOption(opt.getLongOpt())) {
Object paramVal = parseParamFromCommandLine(opt.getLongOpt(), paramClass, line.getOptionValues(opt.getLongOpt()));
inputs[i] = paramVal;
}
else
inputs[i] = defaultParamValue(paramClass);
}
try {
return inputConstructor.newInstance(inputs);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private Object parseParamFromCommandLine(String opt, Class<?> paramClass, String[] vals) {
if (vals == null)
vals = new String[0];
Object collection = parseCollectionParamFromCommandLine(opt, paramClass, vals);
if (collection != null)
return collection;
if (vals.length > 1)
throw new IllegalArgumentException("Too many values for option " + opt + " of type " + pretty(paramClass));
String val = vals[0];
// primitive types
if (paramClass.equals(boolean.class) || paramClass.equals(Boolean.class))
return true;
if (paramClass.equals(byte.class) || paramClass.equals(Byte.class))
return Byte.parseByte(val);
if (paramClass.equals(short.class) || paramClass.equals(Short.class))
return Short.parseShort(val);
if (paramClass.equals(int.class) || paramClass.equals(Integer.class))
return Integer.parseInt(val);
if (paramClass.equals(long.class) || paramClass.equals(Long.class))
return Long.parseLong(val);
if (paramClass.equals(float.class) || paramClass.equals(Float.class))
return Float.parseFloat(val);
if (paramClass.equals(double.class) || paramClass.equals(Double.class))
return Double.parseDouble(val);
if (paramClass.equals(char.class) || paramClass.equals(Character.class)) {
if (val.length() == 1)
return val.charAt(0);
throw new IllegalArgumentException("Expected single character but found " + val + " for option " + opt);
}
// selected class types
if (paramClass.equals(String.class))
return val;
if (paramClass.equals(AbsolutePath.class))
return new AbsolutePath(val);
if (paramClass.equals(Path.class) && AbsolutePath.acceptable(val))
return new AbsolutePath(val);
if (paramClass.equals(Path.class) || paramClass.equals(RelativePath.class))
return new RelativePath(new AbsolutePath("."), val);
throw new UnsupportedOperationException("Cannot parse value of type " + pretty(paramClass) + " for option " + opt);
}
@SuppressWarnings("unchecked")
private Object parseCollectionParamFromCommandLine(String opt, Class<?> paramClass, String[] vals) {
if (paramClass.isArray()) {
Object[] ar = (Object[]) Array.newInstance(paramClass.getComponentType(), vals.length);
for (int i = 0; i < vals.length; i++)
ar[i] = parseParamFromCommandLine(opt, paramClass.getComponentType(), new String[] {vals[i]});
return ar;
}
if (Collection.class.isAssignableFrom(paramClass)) {
Collection<Object> col;
try {
col = (Collection<Object>) paramClass.getConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
try {
col = (Collection<Object>) paramClass.getConstructor(int.class).newInstance(vals.length);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) {
try {
col = (Collection<Object>) paramClass.getConstructor(Integer.class).newInstance(vals.length);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e2) {
throw new UnsupportedOperationException("Cannot instantiate collection of type " + pretty(paramClass));
}
}
}
if (vals.length == 0)
return col;
List<Pair<Object, Class<?>>> elems = new ArrayList<>();
for (String s : vals)
elems.add(parseParamWithInferredType(s));
Class<?> elemType = findCommonSupertype(elems);
for (int i = 0; i < vals.length; i++)
col.add(parseParamFromCommandLine(opt, elemType, new String[] {vals[i]}));
return col;
}
return null;
}
private Pair<Object, Class<?>> parseParamWithInferredType(String s) {
// primitive types
if ("true".equals(s.toLowerCase()) || "false".equals(s.toLowerCase()))
return Pair.create(Boolean.parseBoolean(s), Boolean.class);
try {
return Pair.create(Byte.parseByte(s), Byte.class);
} catch (NumberFormatException e) { }
try {
return Pair.create(Short.parseShort(s), Short.class);
} catch (NumberFormatException e) { }
try {
return Pair.create(Integer.parseInt(s), Integer.class);
} catch (NumberFormatException e) { }
try {
return Pair.create(Long.parseLong(s), Long.class);
} catch (NumberFormatException e) { }
try {
return Pair.create(Float.parseFloat(s), Float.class);
} catch (NumberFormatException e) { }
try {
return Pair.create(Double.parseDouble(s), Double.class);
} catch (NumberFormatException e) { }
// selected class types
if (AbsolutePath.acceptable(s))
return Pair.create(new AbsolutePath(s), AbsolutePath.class);
if (new File(s).exists())
return Pair.create(new RelativePath(new AbsolutePath("."), s), RelativePath.class);
if (s.matches("^([\\w\\.\\-\\$]+[/\\])*[\\w\\.\\-\\$]+$"))
return Pair.create(new RelativePath(new AbsolutePath("."), s), RelativePath.class);
// character types
if (s.length() == 1)
return Pair.create(s.charAt(0), Character.class);
return Pair.create(s, String.class);
}
private Class<?> findCommonSupertype(List<Pair<Object, Class<?>>> elems) {
if (elems.isEmpty())
return null;
Class<?> cl = elems.get(0).b;
for (int i = 1; i < elems.size(); i++) {
Class<?> next = elems.get(i).b;
cl = meetTypes(cl, next);
}
return cl;
}
private Class<?> meetTypes(Class<?> cl1, Class<?> cl2) {
if (cl1.equals(cl2))
return cl1;
if (cl1.isAssignableFrom(cl2))
return cl1;
if (cl2.isAssignableFrom(cl1))
return cl2;
Class<?> prim = meetPrimitiveTypes(cl1, cl2);
if (prim == null)
prim = meetPrimitiveTypes(cl2, cl1);
if (prim != null)
return prim;
return String.class;
}
private Class<?> meetPrimitiveTypes(Class<?> cl1, Class<?> cl2) {
if (cl1.equals(Short.class) && cl2.equals(Byte.class))
return Short.class;
if (cl1.equals(Integer.class) && (cl2.equals(Byte.class) || cl2.equals(Short.class)))
return Integer.class;
if (cl1.equals(Long.class) && (cl2.equals(Byte.class) || cl2.equals(Short.class) || cl2.equals(Integer.class)))
return Integer.class;
if (cl1.equals(Float.class) || (cl2.equals(Byte.class) || cl2.equals(Short.class) || cl2.equals(Integer.class) || cl2.equals(Long.class)))
return Float.class;
if (cl1.equals(Double.class) || (cl2.equals(Byte.class) || cl2.equals(Short.class) || cl2.equals(Integer.class) || cl2.equals(Long.class) || cl2.equals(Float.class)))
return Double.class;
return null;
}
private String pretty(Class<?> cl) {
if (cl.isArray())
return cl.getComponentType().getName() + "[]";
return cl.getName();
}
private Object defaultParamValue(Class<?> paramClass) {
if (paramClass.equals(boolean.class) || paramClass.equals(Boolean.class))
return false;
if (paramClass.equals(byte.class) || paramClass.equals(Byte.class))
return (byte) 0;
if (paramClass.equals(short.class) || paramClass.equals(Short.class))
return (short) 0;
if (paramClass.equals(int.class) || paramClass.equals(Integer.class))
return (int) 0;
if (paramClass.equals(long.class) || paramClass.equals(Long.class))
return (long) 0;
if (paramClass.equals(float.class) || paramClass.equals(Float.class))
return (float) 0;
if (paramClass.equals(double.class) || paramClass.equals(Double.class))
return (double) 0;
if (paramClass.equals(char.class) || paramClass.equals(Character.class))
return (char) 0;
return null;
}
}
|
package net.fortuna.ical4j;
import java.io.FileFilter;
import java.io.File;
public class FileOnlyFilter implements FileFilter {
public boolean accept(final File file) {
// skip directories (including CVS)
boolean accept = file.isFile();
if (accept) {
// ignore hidden files
accept = !file.isHidden();
}
return accept;
}
}
|
package inovapap.sp.gtfs;
public class Shapes {
private int shapeId;
private float shapePtLat;
private float shapePtLon;
private int shapePtSequence;
private float shapeDistTraveled;
}
|
// $Id: CloseTest.java,v 1.9 2006/09/15 14:56:46 belaban Exp $
package org.jgroups.tests;
import junit.framework.TestCase;
import org.jgroups.*;
import org.jgroups.util.Util;
import java.util.Vector;
/**
* Demos the creation of a channel and subsequent connection and closing. Demo application should exit (no
* more threads running)
*/
public class CloseTest extends TestCase {
JChannel channel, channel1, channel2, c1, c2, c3;
String props="UDP(mcast_addr=228.8.8.3;mcast_port=45577;ip_ttl=32;" +
"mcast_send_buf_size=150000;mcast_recv_buf_size=80000;" +
"enable_bundling=true;max_bundle_timeout=30;use_incoming_packet_handler=true;loopback=true):" +
"PING(timeout=2000;num_initial_members=3):" +
"MERGE2(min_interval=5000;max_interval=10000):" +
"FD_SOCK:" +
"VERIFY_SUSPECT(timeout=1500):" +
"pbcast.NAKACK(gc_lag=50;retransmit_timeout=600,1200,2400,4800):" +
"UNICAST(timeout=600,1200,2400):" +
"pbcast.STABLE(desired_avg_gossip=20000):" +
"FRAG(frag_size=4096;down_thread=false;up_thread=false):" +
"pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" +
"shun=true;print_local_addr=true)";
public CloseTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
String cfg=System.getProperty("config");
if(cfg != null)
props=cfg;
}
protected void tearDown() throws Exception {
super.tearDown();
closeChannel(channel);
closeChannel(channel1);
closeChannel(channel2);
closeChannel(c1);
closeChannel(c2);
closeChannel(c3);
}
private void closeChannel(JChannel c) {
if(c != null && (c.isOpen() || c.isConnected())) {
c.close();
}
}
public void testDoubleClose() throws ChannelException {
System.out.println("-- creating channel1 --");
channel1=new JChannel(props);
System.out.println("-- connecting channel1 --");
channel1.connect("bla");
System.out.println("-- closing channel1 --");
channel1.close();
System.out.println("-- closing channel1 (again) --");
channel1.close();
System.out.println("-- done, threads are ");
Util.printThreads();
}
public void testCreationAndClose() throws Exception {
System.out.println("-- creating channel1 --");
channel1=new JChannel(props);
System.out.println("-- connecting channel1 --");
channel1.connect("CloseTest1");
System.out.println("-- closing channel1 --");
channel1.close();
System.out.println("-- done, threads are ");
Util.printThreads();
}
public void testViewChangeReceptionOnChannelCloseByParticipant() throws Exception {
Address a1, a2;
Vector members;
c1=new JChannel(props);
System.out.println("-- connecting c1");
c1.connect("X");
Util.sleep(500); // time to receive its own view
dumpMessages("c1", c1);
a1=c1.getLocalAddress();
c2=new JChannel(props);
System.out.println("-- connecting c2");
c2.connect("X");
Util.sleep(500); // time to receive its own view
a2=c2.getLocalAddress();
dumpMessages("c2", c2);
System.out.println("-- closing c2");
c2.close();
Object obj=c1.receive(100);
assertTrue(obj instanceof View);
View v=(View)obj;
members=v.getMembers();
System.out.println("-- first view of c1: " + v);
assertEquals(2, members.size());
assertTrue(members.contains(a1));
assertTrue(members.contains(a2));
obj=c1.receive(100);
assertTrue(obj instanceof View);
v=(View)obj;
members=v.getMembers();
System.out.println("-- second view of c1: " + v);
assertEquals(1, members.size());
assertTrue(members.contains(a1));
assertFalse(members.contains(a2));
}
public void testViewChangeReceptionOnChannelCloseByCoordinator() throws Exception {
Address a1, a2;
Vector members;
Object obj;
View v;
c1=new JChannel(props);
c1.connect("X");
Util.sleep(500); // time to receive its own view
dumpMessages("c1", c1);
a1=c1.getLocalAddress();
c2=new JChannel(props);
c2.connect("X");
Util.sleep(500); // time to receive its own view
a2=c2.getLocalAddress();
v=(View)c2.receive(1);
members=v.getMembers();
assertEquals(2, members.size());
assertTrue(members.contains(a2));
c1.close();
Util.sleep(500);
System.out.println("queue of c2 is " + c2.dumpQueue());
assertTrue("found 0 messages in channel", c2.getNumMessages() > 0);
obj=c2.receive(0);
assertTrue(obj instanceof View);
v=(View)obj;
members=v.getMembers();
assertEquals(1, members.size());
assertFalse(members.contains(a1));
assertTrue(members.contains(a2));
assertEquals(0, c2.getNumMessages());
}
private void dumpMessages(String msg, JChannel ch) throws Exception {
while(ch.getNumMessages() > 0) {
Object obj=ch.receive(0);
if(obj instanceof View)
System.out.println(msg + ": " + obj);
}
}
public void testConnectDisconnectConnectCloseSequence() throws ChannelException {
System.out.println("-- creating channel --");
channel=new JChannel(props);
System.out.println("-- connecting channel to CloseTest1--");
channel.connect("CloseTest1");
System.out.println("view is " + channel.getView());
System.out.println("-- disconnecting channel --");
channel.disconnect();
System.out.println("-- connecting channel to OtherGroup --");
channel.connect("OtherGroup");
System.out.println("view is " + channel.getView());
System.out.println("-- closing channel --");
channel.close();
System.out.println("-- done, threads are ");
Util.printThreads();
}
public void testConnectCloseSequenceWith2Members() throws ChannelException {
System.out.println("-- creating channel --");
channel=new JChannel(props);
System.out.println("-- connecting channel --");
channel.connect("X");
System.out.println("view is " + channel.getView());
System.out.println("-- creating channel1 --");
channel1=new JChannel(props);
System.out.println("-- connecting channel1 --");
channel1.connect("X");
System.out.println("view is " + channel1.getView());
System.out.println("-- closing channel1 --");
channel1.close();
Util.sleep(2000);
System.out.println("-- closing channel --");
channel.close();
System.out.println("-- done, threads are ");
Util.printThreads();
}
public void testCreationAndClose2() throws Exception {
System.out.println("-- creating channel2 --");
channel2=new JChannel(props);
System.out.println("-- connecting channel2 --");
channel2.connect("CloseTest2");
System.out.println("-- closing channel --");
channel2.close();
Util.sleep(2000);
Util.printThreads();
}
public void testChannelClosedException() throws Exception {
System.out.println("-- creating channel --");
channel=new JChannel(props);
System.out.println("-- connecting channel --");
channel.connect("CloseTestLoop");
System.out.println("-- closing channel --");
channel.close();
Util.sleep(2000);
try {
channel.connect("newGroup");
fail(); // cannot connect to a closed channel
}
catch(ChannelClosedException ex) {
assertTrue(true);
}
}
public void testCreationAndCloseLoop() throws Exception {
System.out.println("-- creating channel --");
channel=new JChannel(props);
for(int i=1; i <= 10; i++) {
System.out.println("-- connecting channel (attempt
channel.connect("CloseTestLoop2");
System.out.println("-- closing channel --");
channel.close();
System.out.println("-- reopening channel --");
channel.open();
}
channel.close();
}
public void testShutdown() throws Exception {
System.out.println("-- creating channel --");
channel=new JChannel(props);
System.out.println("-- connecting channel --");
channel.connect("bla");
System.out.println("-- shutting down channel --");
channel.shutdown();
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
System.out.println("-- active threads:");
for(int i=0; i < threads.length; i++)
System.out.println(threads[i]);
assertTrue(threads.length < 5);
}
public void testMultipleConnectsAndDisconnects() throws Exception {
c1=new JChannel(props);
assertTrue(c1.isOpen());
assertFalse(c1.isConnected());
c1.connect("bla");
assertTrue(c1.isOpen());
assertTrue(c1.isConnected());
assertServiceAndClusterView(c1, 1);
c2=new JChannel(props);
assertTrue(c2.isOpen());
assertFalse(c2.isConnected());
c2.connect("bla");
assertTrue(c2.isOpen());
assertTrue(c2.isConnected());
assertServiceAndClusterView(c2, 2);
Util.sleep(500);
assertServiceAndClusterView(c1, 2);
c2.disconnect();
assertTrue(c2.isOpen());
assertFalse(c2.isConnected());
Util.sleep(500);
assertServiceAndClusterView(c1, 1);
c2.connect("bla");
assertTrue(c2.isOpen());
assertTrue(c2.isConnected());
assertServiceAndClusterView(c2, 2);
Util.sleep(300);
assertServiceAndClusterView(c1, 2);
// Now see what happens if we reconnect the first channel
c3=new JChannel(props);
assertTrue(c3.isOpen());
assertFalse(c3.isConnected());
assertServiceAndClusterView(c1, 2);
assertServiceAndClusterView(c2, 2);
c1.disconnect();
assertTrue(c1.isOpen());
assertFalse(c1.isConnected());
assertServiceAndClusterView(c2, 1);
assertTrue(c3.isOpen());
assertFalse(c3.isConnected());
c1.connect("bla");
assertTrue(c1.isOpen());
assertTrue(c1.isConnected());
assertServiceAndClusterView(c1, 2);
Util.sleep(500);
assertServiceAndClusterView(c2, 2);
assertTrue(c3.isOpen());
assertFalse(c3.isConnected());
}
private void assertServiceAndClusterView(Channel ch, int num) {
View view=ch.getView();
String msg="view=" + view;
assertNotNull(view);
assertEquals(msg, num, view.size());
}
public static void main(String[] args) {
String[] testCaseName={CloseTest.class.getName()};
junit.textui.TestRunner.main(testCaseName);
}
}
|
// MetaPanel.java
package loci.ome;
import ij.*;
import ij.process.ImageProcessor;
import loci.ome.xml.*;
import org.w3c.dom.*;
import java.util.*;
import java.lang.reflect.*;
import org.openmicroscopy.ds.dto.*;
import org.openmicroscopy.ds.*;
import org.openmicroscopy.ds.st.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
/**
* MetaPanel is the class that handles the window used to view attributes
* associated with an image.
*
* @author Philip Huettl pmhuettl at wisc.edu
* @author Melissa Linkert linkert at cs.wisc.edu
*/
public class MetaPanel implements ActionListener, TreeSelectionListener {
// -- Constants --
public static final String[] FEATURE_TYPES = {
"Bounds", "Extent", "Location", "Ratio", "Signal", "Threshold", "Timepoint"
};
// -- Fields --
private JButton cancel;
private JDialog dia;
private JTextField text1, text2;
private Object[] meta;
private int imagePID;
private JTree tree;
private JSplitPane splitPane;
private JPanel customPane, imagePane;
private JTextField iName, iDate, idescription, iID;
private JTextArea customField;
private DefaultMutableTreeNode root;
private static ImageProcessor imageP;
private static boolean isXML;
private static OMENode omeNode;
private static DefaultMutableTreeNode defaultNode;
private static int omeID;
private static Hashtable table;
// -- Constructor --
public MetaPanel(Frame frame, int imageplusID, Object[] obmeta) {
table = new Hashtable();
imagePID = imageplusID;
meta = obmeta;
//Create the tree
root = (DefaultMutableTreeNode) obmeta[1];
tree = new JTree(root);
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(this);
JScrollPane treeView = new JScrollPane(tree);
treeView.setPreferredSize(new Dimension(400, 400));
//creates the dialog box
dia = new JDialog(frame, "OME Image Attributes", true);
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
customPane = new JPanel();
customPane.setLayout(new GridBagLayout());
GridBagConstraints gbl = new GridBagConstraints();
gbl.fill = GridBagConstraints.BOTH;
gbl.gridwidth = GridBagConstraints.REMAINDER;
gbl.gridheight = GridBagConstraints.REMAINDER;
gbl.weighty = 1;
gbl.weightx = 1;
customField = new JTextArea(2,20);
customField.setLineWrap(true);
customField.setWrapStyleWord(true);
JScrollPane customScroll = new JScrollPane(customField);
treeView.setMinimumSize(new Dimension(200,200));
customPane.add(customScroll, gbl);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
treeView, customPane);
customPane.setMinimumSize(customPane.getPreferredSize());
pane.add(splitPane);
JPanel paneButtons = new JPanel();
paneButtons.setLayout(new BoxLayout(paneButtons, BoxLayout.X_AXIS));
paneButtons.setBorder(new EmptyBorder(5,5,5,5));
paneButtons.setAlignmentX(JPanel.LEFT_ALIGNMENT);
pane.add(paneButtons);
dia.setContentPane(pane);
cancel = new JButton("Close");
cancel.setActionCommand("cancel");
paneButtons.add(cancel);
cancel.addActionListener(this);
dia.pack();
centerWindow(frame, dia);
}
/** shows and retrieves info from the DownPanel */
public void show() {
dia.show();
}
/** implements the ActionListener actionPerformed method */
public void actionPerformed(ActionEvent e) {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
dia.hide();
}
/** detects selection in the tree */
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
customField.setText("");
if (node == null) return;
XMLObject nodeInfo = (XMLObject)node.getUserObject();
int type = nodeInfo.getType();
customField.setText(nodeInfo.getValue());
}
// -- OMESidePanel methods --
/** puts the given window at the edge of the specified parent window. */
public static void centerWindow(Window parent, Window window) {
Point loc = parent.getLocation();
Dimension p = parent.getSize();
Dimension w = window.getSize();
int x = loc.x + (p.width - w.width) / 2;
int y = loc.y + (p.height - w.height) / 2;
if (x < 0) x = 0;
if (y < 0) y = 0;
window.setLocation(x, y);
}
// -- OMEMetaDataHandler methods --
/**Method that begins the process of getting metadata from an OME_TIFF file*/
public static DefaultMutableTreeNode exportMeta(String descr,
int ijimageID)
{
isXML = true;
IJ.showStatus("Retrieving OME-TIFF header.");
Object[] meta = new Object[2];
if (descr == null) {
IJ.showStatus("Not an OME-TIFF file.");
if (meta == null) {
meta = new Object[2];
meta[0] = new Integer(0);
}
meta[1] = defaultNode;
defaultNode = null;
return null;
}
IJ.showStatus("Parsing OME-TIFF header.");
try {
omeNode = new OMENode(descr);
}
catch (Exception e) {
IJ.showStatus("Error parsing OME-XML metadata, possibly not present.");
if (meta == null) {
meta = new Object[2];
meta[0] = new Integer(0);
}
meta[1] = null;
defaultNode = null;
return null;
}
if (meta == null) {
meta = new Object[2];
meta[0] = new Integer(0);
}
meta[1] = new DefaultMutableTreeNode(
new XMLObject("OME-XML"));
IJ.showStatus("Metadata is being put into tree structure.");
addDisk(omeNode, (DefaultMutableTreeNode) meta[1], null, "OME");
return (DefaultMutableTreeNode) meta[1];
}
private static void exportMeta(Feature feature, DefaultMutableTreeNode root,
DataFactory df) {
IJ.showStatus("Retrieving Feature attributes.");
DefaultMutableTreeNode featureNode = new DefaultMutableTreeNode(
new XMLObject(XMLObject.FEATUREHEADING));
root.add(featureNode);
featureNode.add(new DefaultMutableTreeNode(
new XMLObject("Name", feature.getName(), XMLObject.FEATURE)));
featureNode.add(new DefaultMutableTreeNode(
new XMLObject("Tag", feature.getTag(), XMLObject.FEATURE)));
//add trajectory entries
java.util.List trajects = null;
if (df != null) {
Criteria trajCriteria = new Criteria();
trajCriteria.addWantedField("feature_id");
trajCriteria.addFilter("feature_id", (new Integer(
feature.getID())).toString());
//retrieve element to add with all columns loaded
trajects = df.retrieveList("Trajectory", trajCriteria);
}
else trajects = ((Trajectory)feature).getTrajectoryEntryList();
Iterator iterTra = trajects.iterator();
while (iterTra.hasNext()) {
addDisk((Trajectory)iterTra.next(), featureNode, df, "Trajectory");
}
//add attributes to this element's node
if (df != null) {
for (int i=0; i<FEATURE_TYPES.length; i++) {
Criteria criteria = new Criteria();
criteria.addWantedField("feature_id");
criteria.addFilter("feature_id",
new Integer(feature.getID()).toString());
IJ.showStatus("Retrieving " + FEATURE_TYPES[i] + "s.");
java.util.List customs = null;
try {
customs = df.retrieveList(FEATURE_TYPES[i], criteria);
}
catch (Exception e) {
e.printStackTrace();
IJ.showStatus("Error while retrieving " + FEATURE_TYPES[i] + "s.");
}
if (customs != null) {
Iterator itCustoms = customs.iterator();
while (itCustoms.hasNext()) {
addDisk(itCustoms.next(), featureNode, df, FEATURE_TYPES[i]);
}
}
}
}
else addDisk(feature, featureNode, df, "Feature");
//add child features to tree
java.util.List features = feature.getChildren();
Iterator iter = features.iterator();
while (iter.hasNext()) {
exportMeta((Feature)iter.next(), featureNode, df);
}
}
/**
* Add an element's attributes and children to the metadata tree.
* This method is only called if we are working with an image stored on
* disk (requires LOCI's OME-XML package).
*/
private static void addDisk(Object element, DefaultMutableTreeNode root,
DataFactory df, String identifier) {
/* debug */ System.out.println("retrieving " + identifier + " attributes");
IJ.showStatus("Retrieving " + identifier + " attributes.");
if (element == null) return;
OMEXMLNode xml = null;
if (!element.toString().startsWith("[")) {
xml = (OMEXMLNode) element;
}
String[] tempAttrs = null;
String[] tempValues = null;
try {
tempAttrs = xml.getAttributeNames();
tempValues = xml.getAttributeValues();
}
catch (NullPointerException n) { }
// NodeList is a list of child DOM elements
NodeList tempChilds = null;
Object[] childs = null;
String[] names = null;
try {
tempChilds = xml.getDOMElement().getChildNodes();
childs = new Object[tempChilds.getLength()];
}
catch (NullPointerException n) { }
try {
for (int i=0; i<tempChilds.getLength(); i++) {
String tmp = tempChilds.item(i).toString();
String id = tmp.substring(1, tmp.indexOf(" "));
String tmpId = tmp;
if (tmp.indexOf(">") >= 0) tmpId = tmp.substring(1, tmp.indexOf(">"));
if (tmpId.length() < id.length()) id = tmpId;
if (!id.endsWith("Node")) {
id = id + "Node";
}
if (!id.startsWith("Attribute") &&
!id.startsWith("CustomAttributes") &&
!id.startsWith("Dataset") && !id.startsWith("Feature") &&
!id.startsWith("Image") && !id.equals("OMENode") &&
!id.startsWith("Project"))
{
if (id.indexOf(":") != -1) {
id = id.substring(0, id.indexOf(":"));
}
id = "loci.ome.xml.st." + id + "Node";
}
else {
if (id.indexOf(":") != -1) {
id = id.substring(0, id.indexOf(":")) + "Node";
}
id = "loci.ome.xml." + id;
}
// construct a new node using this class
Class toConstruct = Class.forName(id.trim());
Constructor construct =
toConstruct.getDeclaredConstructor(new Class[] {Element.class});
childs[i] =
construct.newInstance(new Object[] {(Element) tempChilds.item(i)});
}
names = new String[childs.length];
for (int i=0; i<childs.length; i++) {
String tmp = childs[i].toString();
names[i] = tmp.substring(tmp.lastIndexOf(".")+1, tmp.lastIndexOf("@"));
}
}
catch (Throwable t) { /* debug */ t.printStackTrace(); }
if (df != null && tempAttrs != null) {
Criteria criteria = makeAttributeFields(tempAttrs);
criteria.addWantedField("id");
criteria.addFilter("id", (new Integer(
((ImageGroup) element).getID())).toString());
element = df.retrieve(identifier, criteria);
}
DefaultMutableTreeNode node = new DefaultMutableTreeNode(new XMLObject(
identifier, XMLObject.ELEMENT));
root.add(node);
if (tempAttrs != null && tempValues != null) {
for (int i=0; i<tempValues.length; i++) {
node.add(new DefaultMutableTreeNode(new XMLObject(tempAttrs[i],
tempValues[i], XMLObject.ATTRIBUTE)));
}
}
if (tempChilds != null) {
for (int i=0; i<childs.length; i++) {
String newName = (names == null) ? null : names[i];
/* debug */ System.out.println("adding attribute with name '" +
newName + "'");
addDisk(childs[i], node, df, newName);
}
}
}
// -- OMEDownPanel methods --
/** produces an error notification popup with the inputted text */
public static void error(Frame frame, String s, String x){
JOptionPane.showMessageDialog(frame,s,x,JOptionPane.ERROR_MESSAGE);
}
// -- OMERetrieve methods --
/** populates the criteria for a certain attribute */
public static Criteria makeAttributeFields(String[] attr) {
Criteria c = new Criteria();
for (int i=0; i<attr.length; i++) {
c.addWantedField(attr[i]);
}
return c;
}
}
|
package gui;
import data.AllTracks;
import data.CustomerTracks;
import data.TrackedTimeItem;
import java.awt.Color;
import java.awt.HeadlessException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import logic.Export;
import java.util.concurrent.TimeUnit;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.tree.TreeNode;
/**
*
* @author Lars
*/
public class MainFrame extends javax.swing.JFrame {
private Date createdDate = new Date();
private Timer timer;
private JLabel jLTemplatePath = new JLabel();
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
if (readSaveState()) {
buildTree();
}
this.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
Object[] options = {"Nicht speichern",
"Abbrechen",
"Sichern.."};
int n = JOptionPane.showOptionDialog(null,
"Möchtest du die Änderungen sichern? ",
"Speichern",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
switch (n) {
case 0: //Nicht speichern
System.exit(0);
break;
case 1: //Abbrechen
break;
case 2: //Sichern..
if (save()) {
System.exit(0);
} else {
JOptionPane.showMessageDialog(null, "Fehler beim Speichern", "Speichern", JOptionPane.ERROR_MESSAGE);
}
break;
}
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPMenue = new javax.swing.JPanel();
jBnewCustomer = new javax.swing.JButton();
jBSave = new javax.swing.JButton();
jBExport = new javax.swing.JButton();
jBTamplate = new javax.swing.JButton();
jBDeleteTreeleafs = new javax.swing.JButton();
jPSeperator = new javax.swing.JPanel();
jSeparator1 = new javax.swing.JSeparator();
jPCustomers = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTreeCustomer = new javax.swing.JTree();
jPanel1 = new javax.swing.JPanel();
jPCustomorMenue = new javax.swing.JPanel();
jLKlient = new javax.swing.JLabel();
jBStartTimeTrack = new javax.swing.JButton();
jBStopTimeTrack = new javax.swing.JButton();
jLTime = new javax.swing.JLabel();
jBDeleteCustomer = new javax.swing.JButton();
jPTrackItem = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jTAction = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
jcbKindOfAction = new javax.swing.JComboBox<>();
jSStartTime = new javax.swing.JSpinner();
jSStopTime = new javax.swing.JSpinner();
jBSaveTaskChange = new javax.swing.JButton();
jBDublicateTask = new javax.swing.JButton();
jBDeleteTrack = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Timesheet Generator");
setMinimumSize(new java.awt.Dimension(990, 640));
getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));
jPMenue.setBackground(new java.awt.Color(169, 1, 0));
jPMenue.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
jPMenue.setMaximumSize(new java.awt.Dimension(32767, 82));
jPMenue.setPreferredSize(new java.awt.Dimension(960, 63));
jPMenue.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
jBnewCustomer.setBackground(new java.awt.Color(252, 252, 252));
jBnewCustomer.setText("neuer Mandant");
jBnewCustomer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBnewCustomerActionPerformed(evt);
}
});
jPMenue.add(jBnewCustomer);
jBSave.setBackground(new java.awt.Color(252, 252, 252));
jBSave.setText("Speichern");
jBSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBSaveActionPerformed(evt);
}
});
jPMenue.add(jBSave);
jBExport.setBackground(new java.awt.Color(252, 252, 252));
jBExport.setText("Export");
jBExport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBExportActionPerformed(evt);
}
});
jPMenue.add(jBExport);
jBTamplate.setBackground(new java.awt.Color(252, 252, 252));
jBTamplate.setText("Template");
jBTamplate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBTamplateActionPerformed(evt);
}
});
jPMenue.add(jBTamplate);
jBDeleteTreeleafs.setBackground(new java.awt.Color(252, 252, 252));
jBDeleteTreeleafs.setText("Formular leeren");
jBDeleteTreeleafs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBDeleteTreeleafsActionPerformed(evt);
}
});
jPMenue.add(jBDeleteTreeleafs);
getContentPane().add(jPMenue);
jPSeperator.setBackground(new java.awt.Color(169, 1, 0));
jPSeperator.setMaximumSize(new java.awt.Dimension(32767, 10));
jSeparator1.setMaximumSize(new java.awt.Dimension(32767, 2));
jSeparator1.setMinimumSize(new java.awt.Dimension(2, 2));
javax.swing.GroupLayout jPSeperatorLayout = new javax.swing.GroupLayout(jPSeperator);
jPSeperator.setLayout(jPSeperatorLayout);
jPSeperatorLayout.setHorizontalGroup(
jPSeperatorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPSeperatorLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 984, Short.MAX_VALUE))
);
jPSeperatorLayout.setVerticalGroup(
jPSeperatorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPSeperatorLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14))
);
getContentPane().add(jPSeperator);
jPCustomers.setBackground(new java.awt.Color(204, 204, 204));
jPCustomers.setBorder(javax.swing.BorderFactory.createTitledBorder("Mandant"));
jPCustomers.setAutoscrolls(true);
jPCustomers.setMinimumSize(new java.awt.Dimension(960, 540));
jPCustomers.setPreferredSize(new java.awt.Dimension(960, 560));
jPCustomers.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jScrollPane1.setAlignmentX(0.0F);
jScrollPane1.setAlignmentY(0.0F);
jScrollPane1.setMinimumSize(new java.awt.Dimension(19, 150));
jScrollPane1.setPreferredSize(new java.awt.Dimension(960, 350));
jTreeCustomer.setBackground(new java.awt.Color(252, 252, 252));
javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Mandanten");
jTreeCustomer.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
jTreeCustomer.setAlignmentX(0.0F);
jTreeCustomer.setAlignmentY(0.0F);
jTreeCustomer.setAutoscrolls(true);
jTreeCustomer.setVisibleRowCount(2000);
jTreeCustomer.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
jTreeCustomerValueChanged(evt);
}
});
jScrollPane1.setViewportView(jTreeCustomer);
jPCustomers.add(jScrollPane1);
jPanel1.setBackground(new java.awt.Color(204, 204, 204));
jPanel1.setAlignmentX(0.0F);
jPanel1.setAlignmentY(0.0F);
jPanel1.setPreferredSize(new java.awt.Dimension(960, 140));
jPCustomorMenue.setBackground(new java.awt.Color(204, 204, 204));
jPCustomorMenue.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPCustomorMenue.setToolTipText("");
jPCustomorMenue.setAlignmentX(0.0F);
jPCustomorMenue.setAlignmentY(0.0F);
jPCustomorMenue.setMinimumSize(new java.awt.Dimension(960, 41));
jPCustomorMenue.setPreferredSize(new java.awt.Dimension(960, 50));
jLKlient.setText("Mandant: X");
jPCustomorMenue.add(jLKlient);
jBStartTimeTrack.setBackground(new java.awt.Color(252, 252, 252));
jBStartTimeTrack.setText("Start");
jBStartTimeTrack.setEnabled(false);
jBStartTimeTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBStartTimeTrackActionPerformed(evt);
}
});
jPCustomorMenue.add(jBStartTimeTrack);
jBStopTimeTrack.setBackground(new java.awt.Color(252, 252, 252));
jBStopTimeTrack.setText("Stopp");
jBStopTimeTrack.setEnabled(false);
jBStopTimeTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBStopTimeTrackActionPerformed(evt);
}
});
jPCustomorMenue.add(jBStopTimeTrack);
jLTime.setText("Zeit: ");
jPCustomorMenue.add(jLTime);
jBDeleteCustomer.setBackground(new java.awt.Color(252, 252, 252));
jBDeleteCustomer.setText("Lösche Mandanten");
jBDeleteCustomer.setEnabled(false);
jBDeleteCustomer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBDeleteCustomerActionPerformed(evt);
}
});
jPCustomorMenue.add(jBDeleteCustomer);
jPTrackItem.setBackground(new java.awt.Color(204, 204, 204));
jPTrackItem.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPTrackItem.setAlignmentX(0.0F);
jPTrackItem.setAlignmentY(0.0F);
jPTrackItem.setMinimumSize(new java.awt.Dimension(14, 80));
jPTrackItem.setPreferredSize(new java.awt.Dimension(960, 100));
jPTrackItem.setLayout(new javax.swing.BoxLayout(jPTrackItem, javax.swing.BoxLayout.PAGE_AXIS));
jPanel2.setBackground(new java.awt.Color(204, 204, 204));
jPanel2.setPreferredSize(new java.awt.Dimension(960, 50));
jTAction.setMinimumSize(new java.awt.Dimension(100, 26));
jTAction.setPreferredSize(new java.awt.Dimension(200, 26));
jTAction.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTActionActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 958, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jTAction, javax.swing.GroupLayout.PREFERRED_SIZE, 956, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 34, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 4, Short.MAX_VALUE)
.addComponent(jTAction, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 4, Short.MAX_VALUE)))
);
jPTrackItem.add(jPanel2);
jPanel3.setBackground(new java.awt.Color(204, 204, 204));
jPanel3.setPreferredSize(new java.awt.Dimension(960, 50));
jcbKindOfAction.setBackground(new java.awt.Color(252, 252, 252));
jcbKindOfAction.setEditable(true);
jcbKindOfAction.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { " ", "Büroorga", "Telefonat", "Email", "diverse Korrespondenz", "Besprechung", "Marketing", "Akquise", "Review", "Entwurf", "Review und Entwurf", "Recherche", "Verfügung" }));
jcbKindOfAction.setPreferredSize(new java.awt.Dimension(200, 26));
jPanel3.add(jcbKindOfAction);
jSStartTime.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE));
jPanel3.add(jSStartTime);
jSStopTime.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE));
jPanel3.add(jSStopTime);
jBSaveTaskChange.setBackground(new java.awt.Color(252, 252, 252));
jBSaveTaskChange.setText("speichern");
jBSaveTaskChange.setEnabled(false);
jBSaveTaskChange.setMaximumSize(new java.awt.Dimension(80, 29));
jBSaveTaskChange.setMinimumSize(new java.awt.Dimension(80, 29));
jBSaveTaskChange.setPreferredSize(new java.awt.Dimension(90, 29));
jBSaveTaskChange.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBSaveTaskChangeActionPerformed(evt);
}
});
jPanel3.add(jBSaveTaskChange);
jBDublicateTask.setBackground(new java.awt.Color(252, 252, 252));
jBDublicateTask.setText("duplizieren");
jBDublicateTask.setEnabled(false);
jBDublicateTask.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBDublicateTaskActionPerformed(evt);
}
});
jPanel3.add(jBDublicateTask);
jBDeleteTrack.setBackground(new java.awt.Color(252, 252, 252));
jBDeleteTrack.setText("löschen");
jBDeleteTrack.setEnabled(false);
jBDeleteTrack.setMaximumSize(new java.awt.Dimension(90, 29));
jBDeleteTrack.setMinimumSize(new java.awt.Dimension(90, 29));
jBDeleteTrack.setPreferredSize(new java.awt.Dimension(90, 29));
jBDeleteTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBDeleteTrackActionPerformed(evt);
}
});
jPanel3.add(jBDeleteTrack);
jPTrackItem.add(jPanel3);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPCustomorMenue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jPTrackItem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jPCustomorMenue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPTrackItem, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE)
.addContainerGap())
);
jPCustomers.add(jPanel1);
getContentPane().add(jPCustomers);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jBnewCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBnewCustomerActionPerformed
String S = JOptionPane.showInputDialog("Bitte neuen Mandanten Eingeben!");
AllTracks instance = AllTracks.getInstance();
CustomerTracks get = instance.getAllCustomers().get(S);
int bevor = instance.getAllCustomers().size();
if (get == null) {
CustomerTracks ct = new CustomerTracks(S);
instance.getAllCustomers().put(ct.getCustomername(), ct);
DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
model.insertNodeInto(new DefaultMutableTreeNode(ct), root, root.getChildCount());
} else {
JOptionPane.showMessageDialog(null, "Mandant schon vorhanden!");
}
if (bevor == 0) {
jTreeCustomer.expandRow(0);
jTreeCustomer.setRootVisible(false);
jTreeCustomer.collapseRow(0);
}
}//GEN-LAST:event_jBnewCustomerActionPerformed
private void jBSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSaveActionPerformed
if (save()) {
JOptionPane.showMessageDialog(null, "Der Zustand wurde gespeichert.");
} else {
JOptionPane.showMessageDialog(null, "Fehler beim Speichern");
}
}//GEN-LAST:event_jBSaveActionPerformed
private boolean save() {
if (timer == null) {
OutputStream fos = null;
try {
fos = new FileOutputStream(System.getProperty("user.dir") + "/saveState");
ObjectOutputStream o = new ObjectOutputStream(fos);
AllTracks instance = AllTracks.getInstance();
o.writeObject(instance.getAllCustomers());
o.writeObject(jLTemplatePath);
return true;
} catch (FileNotFoundException e) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, e);
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fos.close();
} catch (Exception e) {
}
}
}
return false;
}
private void jTreeCustomerValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTreeCustomerValueChanged
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent();
String s = selectedNode.getUserObject().getClass().getName();// data.TrackedTimeItem
Date now;
try {
switch (s) {
case "data.CustomerTracks":
CustomerTracks userObject = (CustomerTracks) selectedNode.getUserObject();
jLKlient.setText("Mandant: " + userObject.getCustomername());
jTAction.setText("");
jcbKindOfAction.setSelectedIndex(0);
now = new java.util.Date();
jSStartTime.setValue(now);
jSStopTime.setValue(now);
jBDeleteTrack.setEnabled(false);
jBSaveTaskChange.setEnabled(false);
jBStartTimeTrack.setEnabled(true);
jBDeleteCustomer.setEnabled(true);
jBDublicateTask.setEnabled(false);
break;
case "data.TrackedTimeItem":
TrackedTimeItem trackObject = (TrackedTimeItem) selectedNode.getUserObject();
jTAction.setText(trackObject.getKommand());
jcbKindOfAction.setSelectedItem(trackObject.getKindOfAction());
jSStartTime.setValue(trackObject.getStartTime());
jSStopTime.setValue(trackObject.getEndTime());
jBDeleteTrack.setEnabled(true);
jBSaveTaskChange.setEnabled(true);
jBDeleteCustomer.setEnabled(false);
jBStartTimeTrack.setEnabled(false);
jBStopTimeTrack.setEnabled(false);
jBDublicateTask.setEnabled(true);
break;
case "java.lang.String":
jLKlient.setText("Mandant: ");
jTAction.setText("");
jcbKindOfAction.setSelectedIndex(0);
now = new java.util.Date();
jSStartTime.setValue(now);
jSStopTime.setValue(now);
jBDeleteTrack.setEnabled(false);
jBSaveTaskChange.setEnabled(false);
jBDeleteCustomer.setEnabled(false);
jBStartTimeTrack.setEnabled(false);
jBStopTimeTrack.setEnabled(false);
jBDublicateTask.setEnabled(false);
break;
}
} catch (ClassCastException e) {
JOptionPane.showMessageDialog(null, "Fehler:" + e.getMessage());
}
}//GEN-LAST:event_jTreeCustomerValueChanged
private void jBStopTimeTrackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBStopTimeTrackActionPerformed
if (jTAction.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Bitte einen Beschreibungstext eingeben und erneut Stopp betätigen");
return;
} else {
jBStartTimeTrack.setEnabled(true);
jBStopTimeTrack.setEnabled(false);
jBDeleteCustomer.setEnabled(true);
jTreeCustomer.setEnabled(true);
java.util.Date now = new java.util.Date();
jSStopTime.setValue(now);
TrackedTimeItem TTI;
try {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent();
String name = selectedNode.getUserObject().getClass().getName();
if (name.equals("data.CustomerTracks")) {
CustomerTracks CT = (CustomerTracks) selectedNode.getUserObject();
DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel();
TTI = new TrackedTimeItem(createdDate, now, jTAction.getText(), jcbKindOfAction.getSelectedItem().toString());
model.insertNodeInto(new DefaultMutableTreeNode(TTI), selectedNode, selectedNode.getChildCount());
CT.getCustomeritems().add(TTI);
Calendar cal = Calendar.getInstance();
cal.setTime(TTI.getEndTime());
} else if (name.equals("data.TrackedTimeItem")) {
DefaultMutableTreeNode selectedNodeParent = (DefaultMutableTreeNode) selectedNode.getParent();
CustomerTracks CT = (CustomerTracks) selectedNodeParent.getUserObject();
DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel();
TTI = new TrackedTimeItem(createdDate, now, jTAction.getText(), jcbKindOfAction.getSelectedItem().toString());
model.insertNodeInto(new DefaultMutableTreeNode(TTI), selectedNodeParent, selectedNodeParent.getChildCount());
CT.getCustomeritems().add(TTI);
Calendar cal = Calendar.getInstance();
cal.setTime(TTI.getEndTime());
}
jTAction.setText("");
jLTime.setText("Zeit");
jLTime.setForeground(Color.BLACK);
timer.cancel();
timer = null;
} catch (ClassCastException e) {
JOptionPane.showMessageDialog(this, "Fehler bitte an Programmierer wenden");
}
}
}//GEN-LAST:event_jBStopTimeTrackActionPerformed
private void jBStartTimeTrackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBStartTimeTrackActionPerformed
jBStartTimeTrack.setEnabled(false);
jBDeleteCustomer.setEnabled(false);
jBStopTimeTrack.setEnabled(true);
jTreeCustomer.setEnabled(false);
createdDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(createdDate);
jSStartTime.setValue(createdDate);
jLTime.setText("Zeit ");
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
jLTime.setText("Zeit " + getAgeInSeconds());
}
}, 1000, 1000);
jLTime.setForeground(Color.red);
}//GEN-LAST:event_jBStartTimeTrackActionPerformed
private void jTActionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTActionActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTActionActionPerformed
private void jBExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBExportActionPerformed
if (jLTemplatePath.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Fehler kein Tamplate gefunden", "Export", JOptionPane.ERROR_MESSAGE);
return;
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
FileNameExtensionFilter xlsxfilter = new FileNameExtensionFilter(
"xlsx files (*.xlsx)", "xlsx");
fileChooser.setFileFilter(xlsxfilter);
fileChooser.setDialogTitle("Speicherort");
fileChooser.showOpenDialog(this);
fileChooser.setAcceptAllFileFilterUsed(false);
if (fileChooser.getSelectedFile() != null) {
Export exp = new Export(fileChooser, jLTemplatePath.getText());
try {
boolean convertXls = exp.convertXls();
if (convertXls) {
JOptionPane.showMessageDialog(this, "Erfolgreich Exportiert unter: " + fileChooser.getSelectedFile().toString());
//export entity delete
} else {
JOptionPane.showMessageDialog(this, "Leider nicht Erfolgreich Exportiert!");
}
} catch (HeadlessException | IOException | IllegalArgumentException ex) {
JOptionPane.showMessageDialog(null, "Fehler: " + ex.getMessage(), "Export", JOptionPane.ERROR_MESSAGE);
}
}
}//GEN-LAST:event_jBExportActionPerformed
private void jBDeleteCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDeleteCustomerActionPerformed
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent();
try {
CustomerTracks CT = (CustomerTracks) selectedNode.getUserObject();
AllTracks instance = AllTracks.getInstance();
instance.getAllCustomers().remove(CT.getCustomername());
buildTree();
} catch (ClassCastException ex) {
JOptionPane.showMessageDialog(null, "Fehler bitte einen Mandanten auswählen", "Fehler", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jBDeleteCustomerActionPerformed
private void jBTamplateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTamplateActionPerformed
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter(".xlsx", "xlsx"));
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.showOpenDialog(this);
if (fileChooser.getSelectedFile() != null) {
jLTemplatePath.setText(fileChooser.getSelectedFile().toString());
jLTemplatePath.setForeground(new java.awt.Color(252, 252, 252));
jPMenue.add(jLTemplatePath);
SwingUtilities.updateComponentTreeUI(this);
}
}//GEN-LAST:event_jBTamplateActionPerformed
private void jBDeleteTreeleafsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDeleteTreeleafsActionPerformed
AllTracks instance = AllTracks.getInstance();
Set set = instance.getAllCustomers().entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry mentry = (Map.Entry) iterator.next();
CustomerTracks cusomer = (CustomerTracks) mentry.getValue();
ArrayList<TrackedTimeItem> customeritems = new ArrayList<TrackedTimeItem>();
cusomer.setCustomeritems(customeritems);
}
buildTree();
}//GEN-LAST:event_jBDeleteTreeleafsActionPerformed
private void jBSaveTaskChangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSaveTaskChangeActionPerformed
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent();
TrackedTimeItem TI = (TrackedTimeItem) selectedNode.getUserObject();
TI.setKommand(jTAction.getText());
TI.setKindOfAction(jcbKindOfAction.getSelectedItem().toString());
TI.setStartTime((Date) jSStartTime.getModel().getValue());
TI.setEndTime((Date) jSStopTime.getModel().getValue());
selectedNode.setUserObject(TI);
DefaultMutableTreeNode selectedNode2 = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent();
String s = selectedNode2.getUserObject().getClass().getName();
DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel();
model.reload((TreeNode) selectedNode2);
}//GEN-LAST:event_jBSaveTaskChangeActionPerformed
private void jBDeleteTrackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDeleteTrackActionPerformed
AllTracks instance = AllTracks.getInstance();
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTreeCustomer.getLastSelectedPathComponent();
DefaultMutableTreeNode selectedNodeParent = (DefaultMutableTreeNode) selectedNode.getParent();
CustomerTracks CT = (CustomerTracks) selectedNodeParent.getUserObject();
CustomerTracks get = instance.getAllCustomers().get(CT.getCustomername());
TrackedTimeItem TI = (TrackedTimeItem) selectedNode.getUserObject();
get.getCustomeritems().remove(TI);
buildTree();
}//GEN-LAST:event_jBDeleteTrackActionPerformed
private void jBDublicateTaskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDublicateTaskActionPerformed
jBStopTimeTrack.setEnabled(true);
jTreeCustomer.setEnabled(false);
createdDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(createdDate);
jSStartTime.setValue(createdDate);
jLTime.setText("Zeit ");
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
jLTime.setText("Zeit " + getAgeInSeconds());
}
}, 1000, 1000);
jLTime.setForeground(Color.red);
// TODO add your handling code here:
}//GEN-LAST:event_jBDublicateTaskActionPerformed
public String getAgeInSeconds() {
Calendar cal = Calendar.getInstance();
java.util.Date now = new java.util.Date();
cal.setTime(now);
long diff = now.getTime() - createdDate.getTime();//as given
String curTime = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(diff) % 24, TimeUnit.MILLISECONDS.toMinutes(diff) % 60, TimeUnit.MILLISECONDS.toSeconds(diff) % 60);
return curTime;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jBDeleteCustomer;
private javax.swing.JButton jBDeleteTrack;
private javax.swing.JButton jBDeleteTreeleafs;
private javax.swing.JButton jBDublicateTask;
private javax.swing.JButton jBExport;
private javax.swing.JButton jBSave;
private javax.swing.JButton jBSaveTaskChange;
private javax.swing.JButton jBStartTimeTrack;
private javax.swing.JButton jBStopTimeTrack;
private javax.swing.JButton jBTamplate;
private javax.swing.JButton jBnewCustomer;
private javax.swing.JLabel jLKlient;
private javax.swing.JLabel jLTime;
private javax.swing.JPanel jPCustomers;
private javax.swing.JPanel jPCustomorMenue;
private javax.swing.JPanel jPMenue;
private javax.swing.JPanel jPSeperator;
private javax.swing.JPanel jPTrackItem;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JSpinner jSStartTime;
private javax.swing.JSpinner jSStopTime;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextField jTAction;
private javax.swing.JTree jTreeCustomer;
private javax.swing.JComboBox<String> jcbKindOfAction;
// End of variables declaration//GEN-END:variables
private boolean readSaveState() {
File state = new File(System.getProperty("user.dir") + "/saveState");
if (state.isFile()) {
InputStream fis = null;
try {
fis = new FileInputStream(System.getProperty("user.dir") + "/saveState");
ObjectInputStream o = new ObjectInputStream(fis);
AllTracks instance = AllTracks.getInstance();
// private TreeMap<String, CustomerTracks> allCustomers = new TreeMap<String, CustomerTracks>(String.CASE_INSENSITIVE_ORDER);
TreeMap<String, CustomerTracks> allCustomers = new TreeMap<String, CustomerTracks>(String.CASE_INSENSITIVE_ORDER);
Object confObjekt = o.readObject();
allCustomers = (TreeMap<String, CustomerTracks>) confObjekt;
confObjekt = o.readObject();
jLTemplatePath = (JLabel) confObjekt;
jPMenue.add(jLTemplatePath);
SwingUtilities.updateComponentTreeUI(this);
instance.setAllCustomers(allCustomers);
return true;
} catch (IOException | ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "Fehler beim Laden der saveState Datei: \n" + e.getMessage(), "Fehler", JOptionPane.ERROR_MESSAGE);
} finally {
try {
fis.close();
} catch (IOException e) {
}
}
}
return false;
}
private void buildTree() {
AllTracks instance = AllTracks.getInstance();
DefaultTreeModel model = (DefaultTreeModel) jTreeCustomer.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
root.removeAllChildren();
Set set = instance.getAllCustomers().entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry mentry = (Map.Entry) iterator.next();
CustomerTracks cusomer = (CustomerTracks) mentry.getValue();
DefaultMutableTreeNode first = new DefaultMutableTreeNode(cusomer);
model.insertNodeInto(first, root, root.getChildCount());
for (TrackedTimeItem ti : cusomer.getCustomeritems()) {
model.insertNodeInto(new DefaultMutableTreeNode(ti), first, first.getChildCount());
}
}
if (instance.getAllCustomers().size() != 0) {
jTreeCustomer.expandRow(0);
jTreeCustomer.setRootVisible(false);
jTreeCustomer.collapseRow(0);
}
jBDeleteTrack.setEnabled(false);
jBSaveTaskChange.setEnabled(false);
jBStartTimeTrack.setEnabled(false);
jBStopTimeTrack.setEnabled(false);
jBDeleteCustomer.setEnabled(false);
jBDublicateTask.setEnabled(false);
SwingUtilities.updateComponentTreeUI(this);
}
}
|
package brevis;
import java.io.IOException;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantLock;
import org.ejml.data.DenseMatrix64F;
import org.lwjgl.util.vector.Vector3f;
import org.ode4j.ode.DGeom;
import org.ode4j.ode.DJointGroup;
import org.ode4j.ode.DSpace;
import org.ode4j.ode.DWorld;
import org.ode4j.ode.OdeHelper;
import ags.utils.dataStructures.trees.thirdGenKD.KdTree;
import clojure.lang.PersistentVector;
import duyn.algorithm.nearestneighbours.FastKdTree;
import duyn.algorithm.nearestneighbours.PrioNode;
public class Engine implements Serializable {
/*
* Callback classes.
*/
private static final long serialVersionUID = 5209150139378668298L;
// Compute the update after DT amount of time for object with UID
public static class UpdateHandler implements Serializable {
private static final long serialVersionUID = 7301251223848548305L;
public BrObject update( Engine engine, Long uid, Double dt ) {
BrObject obj = engine.objects.get( uid );
return obj;
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
}
public static class GlobalUpdateHandler implements Serializable {
private static final long serialVersionUID = 5310171212429743564L;
public Long priority = (long) 0;
public void update( Engine engine ) {
}
public Long getPriority () {
return priority;
}
public void setPriority( Long priority2 ) {
priority = priority2;
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
}
// All collisions are pairwise now.
// Compute the collision after DT amount of time for object with UID colliding with UID, other
/*public static class CollisionHandler {
public BrObject collide( BrObject subj, BrObject othr, Double dt) {
return subj;
}
}*/
public static class CollisionHandler implements Serializable {
private static final long serialVersionUID = -5029373761039142328L;
public clojure.lang.PersistentVector collide( Engine engine, BrObject subj, BrObject othr, Double dt) {
clojure.lang.PersistentVector v = clojure.lang.PersistentVector.create( subj, othr );
return v;
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
}
/*
* Variables:
*/
// updateHandlers
protected HashMap<String,UpdateHandler> updateHandlers;
protected HashMap<String,Boolean> updateKinematics;
protected PriorityQueue<GlobalUpdateHandler> globalUpdateHandlers;
public double dt = 1.0;
// neighborhoodRadius
public double neighborhoodRadius = 25.0;
// physics
public BrPhysics physics;
protected long simulationStart = -1;
protected long numSteps = 0;
public double startWallTime = 0;
// objects
//protected HashMap<Long,BrObject> objects;
protected ConcurrentHashMap<Long,BrObject> objects;
// addedObjects
protected HashMap<Long,BrObject> addedObjects;
// deletedObjects
protected HashSet<Long> deletedObjects;
// collisionHandlers
protected HashMap< SimpleEntry<String,String>, CollisionHandler > collisionHandlers;
// collisions
protected HashSet< SimpleEntry<Long,Long> > collisions;
// DEPRECATED: temporary variable for boostrapped version
public static HashSet< SimpleEntry<Long,Long> > globalCollisions;
// physicsEnabled
public boolean physicsEnabled = true;
// collisionsEnabled
public boolean collisionsEnabled = true;
// neighborhoodsEnabled
public boolean neighborhoodsEnabled = true;
// enableParallel
public boolean brevisParallel = false;
public transient BrKDTree<BrKDNode> spaceTree = null;
public transient ReentrantLock lock = new ReentrantLock();
/* Methods: */
class GUHComparator implements Comparator<GlobalUpdateHandler>, Serializable {
private static final long serialVersionUID = 8745204900496801037L;
@Override
public int compare(GlobalUpdateHandler gh1, GlobalUpdateHandler gh2) {
return (int) ( gh1.priority - gh2.priority );
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
}
public Engine() {
updateHandlers = new HashMap<String,UpdateHandler>();
updateKinematics = new HashMap<String,Boolean>();
physics = new BrPhysics();
//objects = new HashMap<Long,BrObject>();
objects = new ConcurrentHashMap<Long,BrObject>();
addedObjects = new HashMap<Long,BrObject>();
deletedObjects = new HashSet<Long>();
collisionHandlers = new HashMap< SimpleEntry<String,String>, CollisionHandler >();
collisions = new HashSet< SimpleEntry<Long,Long> >();
globalCollisions = new HashSet< SimpleEntry<Long,Long> >();
globalUpdateHandlers =
new PriorityQueue<GlobalUpdateHandler>(1, (Comparator<GlobalUpdateHandler>) new GUHComparator() );
simulationStart = System.nanoTime();
spaceTree = new BrKDTree<BrKDNode>();
}
public static class BrevisCollision implements DGeom.DNearCallback {
@SuppressWarnings("unchecked")
@Override
public void call(Object data, DGeom o1, DGeom o2) {
HashMap<String,Object> o1map = (HashMap<String,Object>)o1.getBody().getData();
HashMap<String,Object> o2map = (HashMap<String,Object>)o2.getBody().getData();
Long uid1 = (Long)o1map.get("uid");
Long uid2 = (Long)o2map.get("uid");
// Only add one collisions, and sort them small to big
if( uid1 < uid2 )
Engine.globalCollisions.add( new SimpleEntry<Long,Long>( uid1, uid2 ) );
else if( uid2 > uid1 )
Engine.globalCollisions.add( new SimpleEntry<Long,Long>( uid2, uid1 ) );
// This used to add 2
//SimpleEntry<Long,Long> p1 = new SimpleEntry<Long,Long>( uid1, uid2 );
//SimpleEntry<Long,Long> p2 = new SimpleEntry<Long,Long>( uid2, uid1 );
//System.out.println( "collision callback " + p1 + " " + p2 + " " + o1map + " " + o2map );
//Engine.globalCollisions.add( p1 );
//Engine.globalCollisions.add( p2 );
/*if (physicsEnabled) {
// Also do a physics collision?
}*/
}
}
/* updatePhysics
* Move according to physics
*/
public void updatePhysics( double dt ) {
lock.lock(); // block until condition holds
try {
physics.contactGroup.empty();
if( collisionsEnabled ) {
OdeHelper.spaceCollide( physics.space, null, new BrevisCollision() );
}
physics.world.quickStep( dt );
physics.time += dt;
} finally {
lock.unlock();
}
}
public void clearSimulation() {
/* Just clear everything */
lock.lock(); // block until condition holds
try {
physics = new BrPhysics();
//objects = new HashMap<Long,BrObject>();
objects = new ConcurrentHashMap<Long,BrObject>();
addedObjects = new HashMap<Long,BrObject>();
deletedObjects = new HashSet<Long>();
} finally {
lock.unlock();
}
}
/* synchronizeObjects
* Apply all insertions/deletions
*/
public void synchronizeObjects() {
lock.lock(); // block until condition holds
try {
//System.out.println( "synchronizeObjects del: " + deletedObjects.size() + " add: " + addedObjects.size() );
// Remove deleted objects
for( Long uid : deletedObjects ) {
//objects.get(uid).clear();
// things aren't getting removed from the physics engine
BrObject object = objects.get( uid );
physics.getSpace().remove( object.getGeom() );
objects.remove( uid );
}
deletedObjects = new HashSet<Long>();
// Add newly created objects
objects.putAll( addedObjects );
addedObjects = new HashMap<Long,BrObject>();
} finally {
lock.unlock();
}
//physics.space.cleanGeoms();
}
/* updateObjects
* Call individual update functions
*/
public void updateObjects( double dt ) {
lock.lock(); // block until condition holds
try {
//HashMap<Long,BrObject> updatedObjects = new HashMap<Long,BrObject>();
ConcurrentHashMap<Long,BrObject> updatedObjects = new ConcurrentHashMap<Long,BrObject>();
// Call the 0 update handler once (eliminating this implementation)
/*if( updateHandlers.containsKey( 0 ) ) {
UpdateHandler global_uh = updateHandlers.get( 0 );
BrObject placeholder = global_uh.update( this, null, dt );
}*/
//System.out.println( "updateObjects " + objects.keySet() );
for( Map.Entry<Long,BrObject> entry : objects.entrySet() ) {
BrObject obj = entry.getValue();
UpdateHandler uh = updateHandlers.get( obj.type );
BrObject newObj = obj;
if( uh != null ) {
//System.out.println( "--" + getTime() + " updating object " + entry.getKey() );
newObj = uh.update( this, entry.getKey(), dt );
}
//else System.out.println( "--" + getTime() + " not updating object " + entry.getKey() + " " + entry.getValue().type );
Boolean kh = updateKinematics.get( obj.type );
//System.out.println( obj.type + " " + kh );
if( kh != null && kh ) {
newObj.updateObjectKinematics( dt );
}
updatedObjects.put( entry.getKey(), newObj );
}
objects = updatedObjects;
} finally {
lock.unlock();
}
}
class BrObjectResult {
public BrObject obj;
public Long UID;
BrObjectResult(){
}
}
class UpdateObjectTask implements Callable<BrObjectResult> {
BrObject obj;
Long UID;
UpdateObjectTask( BrObject myObj, Long myUID ){
UID = myUID;
obj = myObj;
}
public BrObjectResult call() throws Exception {
BrObjectResult result = new BrObjectResult();
UpdateHandler uh = updateHandlers.get( obj.type );
result.obj = obj;
result.UID = UID;
if( uh != null ) {
//System.out.println( "--" + getTime() + " updating object " + entry.getKey() );
result.obj = uh.update( null, UID, dt );
}
//else System.out.println( "--" + getTime() + " not updating object " + entry.getKey() + " " + entry.getValue().type );
return result;
}
}
/* parallelUpdateObjects (not working properly yet)
* Call individual update functions in parallel
*/
public void parallelUpdateObjects( final double dt ) {
lock.lock(); // block until condition holds
ConcurrentHashMap<Long,BrObject> updatedObjects = new ConcurrentHashMap<Long,BrObject>();
ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
try {
CompletionService<BrObjectResult> taskCompletionService =
new ExecutorCompletionService<BrObjectResult>(exec);
// Send
for( Map.Entry<Long,BrObject> entry : objects.entrySet() ){
taskCompletionService.submit(new UpdateObjectTask( entry.getValue(), entry.getKey() ));
}
// Wait
for(int tasksHandled=0;tasksHandled<objects.size();tasksHandled++){
try {
System.out.println("trying to take from Completion service");
Future<BrObjectResult> result = taskCompletionService.take();
System.out.println("result for a task availble in queue.Trying to get()" );
// above call blocks till atleast one task is completed and results availble for it
// but we dont have to worry which one
// process the result here by doing result.get()
BrObjectResult obj = result.get();
if( !deletedObjects.contains( obj.UID ) ) {// Can't update what isn't there (i.e. objects that self-delete)
Boolean kh = updateKinematics.get( obj.obj.type );
//System.out.println( obj.type + " " + kh );
if( kh != null && kh ) {
obj.obj.updateObjectKinematics( dt );
}
//updatedObjects.put( entry.getKey(), newObj ); //was here
} else {
// Delete the object
if( obj.obj != null )
obj.obj.destroy( null );
}
updatedObjects.put( obj.UID, obj.obj );
//System.out.println("Task " + String.valueOf(tasksHandled) + "Completed - results obtained : " + String.valueOf(l.result));
} catch (InterruptedException e) {
// Something went wrong with a task submitted
System.out.println("Error Interrupted exception");
e.printStackTrace();
} catch (ExecutionException e) {
// Something went wrong with the result
e.printStackTrace();
System.out.println("Error get() threw exception");
}
}
} finally {
exec.shutdown();
lock.unlock();
}
objects = updatedObjects;
}
/* globalUpdateObjects
* Call individual update functions
*/
public void globalUpdateObjects( boolean preIndividual ) {
lock.lock();
try {
for( GlobalUpdateHandler gh : globalUpdateHandlers ) {
//System.out.println( "guh " + gh );
if( preIndividual && gh.getPriority() < 0 ) {
// System.out.println( "globalUpdate " + gh );
gh.update( this );
synchronizeObjects();
} else if ( !preIndividual && gh.getPriority() >= 0 ) {
//System.out.println( "globalUpdate " + gh );
gh.update( this );
synchronizeObjects();
}
}
} finally {
lock.unlock();
}
}
/* handleCollisions
* Respond to all computed collisions
*/
public void handleCollisions( double dt ) {
lock.lock(); // block until condition holds
try {
collisions = globalCollisions;
// It might be reasonable to shuffle here
//HashMap<Long,BrObject> updatedObjects = new HashMap<Long,BrObject>();
ConcurrentHashMap<Long,BrObject> updatedObjects = new ConcurrentHashMap<Long,BrObject>();
updatedObjects.putAll(objects);
//System.out.println( "handleCollisions " + collisions );
for( SimpleEntry<Long,Long> entry: collisions ) {
BrObject subj = updatedObjects.get( entry.getKey() );
BrObject othr = updatedObjects.get( entry.getValue() );
// If the colliding objects both still exist
if( subj != null && othr != null ) {
SimpleEntry<String,String> typeEntry = new SimpleEntry<String,String>(subj.type,othr.type);
// Find the corresponding collision handler
CollisionHandler ch = collisionHandlers.get( typeEntry );
// Collisions are only inserted into the list once, so let's check the opposite type ordering for another collision handler if we cant find one
if( ch == null ) {
ch = collisionHandlers.get( new SimpleEntry<String,String>(othr.type,subj.type) );
if( ch != null ) {
BrObject tmp = subj;
subj = othr;
othr = tmp;
}
}
//System.out.println( "collision " + subj + " " + othr + " " + ch + " " + typeEntry + " " + collisionHandlers );
//System.out.println( "collision " + subj.type + " " + othr.type + " " + ch + " " + typeEntry + " " + collisionHandlers );
if( ch != null ) {
//System.out.println( "Collision handler found " );
PersistentVector pair = ch.collide( this, subj, othr, dt );
BrObject newSubj = (BrObject) pair.get(0);
BrObject newOthr = (BrObject) pair.get(1);
// Need to avoid calling on the same key-value pair twice
updatedObjects.put( entry.getKey() , newSubj );
updatedObjects.put( entry.getValue() , newOthr);
}
}
}
objects = updatedObjects;
collisions.clear();
} finally {
lock.unlock();
}
}
/* updateNeighborhoods
* Update the neighborhoods of all objects
* KD tree implementation
*/
public void updateNeighborhoods() {
lock.lock(); // block until condition holds
try {
//HashMap<Long,BrObject> updatedObjects = new HashMap<Long,BrObject>();
ConcurrentHashMap<Long,BrObject> updatedObjects = new ConcurrentHashMap<Long,BrObject>();
//spaceTree = new BrKDTree<BrKDNode>();//lazy
spaceTree.clear();
// Add everyone to the KD tree
for( Map.Entry<Long,BrObject> entry : objects.entrySet() ) {
BrObject obj = entry.getValue();
//Vector3f pos = obj.getPosition();
Vector3f pos = new Vector3f();
pos = Vector3f.add( obj.getPosition(), obj.getShape().center, pos);
double[] arryloc = { pos.x, pos.y, pos.z };
BrKDNode n = new BrKDNode( arryloc, entry.getKey() );
spaceTree.add( n );
}
int nResults = 10;
// Loop over everyone and cache their neighborhood (this could be made lazy)
for( Map.Entry<Long,BrObject> entry : objects.entrySet() ) {
BrObject obj = entry.getValue();
Vector<Long> nbrs = new Vector<Long>();
Vector3f pos = obj.getPosition();
double[] arryloc = { pos.x, pos.y, pos.z };
//Iterable<PrioNode<BrKDNode>> itNbrs = spaceTree.search( arryloc, nResults);
//Iterable<PrioNode<BrKDNode>> itNbrs = spaceTree.searchByDistance( arryloc, neighborhoodRadius );
ArrayList<BrKDNode> searchNbrs = spaceTree.searchByDistance( arryloc, neighborhoodRadius );
Iterator<BrKDNode> itr = searchNbrs.iterator();
double closestDistance = 99999999;//maybe dangerous?
long closestUID = 0;
boolean foundClosest = false;
Vector3f diff = new Vector3f();
while( itr.hasNext() ) {
BrKDNode nbr = itr.next();
nbrs.add( nbr.UID );
Vector3f.sub( objects.get( nbr.UID ).position, obj.position, diff );
double ldiff = diff.length();
if ( ( ldiff < closestDistance ) && ( nbr.UID != obj.uid ) ) {
closestDistance = ldiff;
closestUID = nbr.UID;
foundClosest = true;
}
}
if( foundClosest )
obj.closestNeighbor = closestUID;
else
obj.closestNeighbor = (long) 0;
//System.out.println( "Neighbors of " + obj + " " + nbrs.size() );
obj.nbrs = nbrs;
updatedObjects.put( entry.getKey(), obj );
}
objects = updatedObjects;
} finally {
lock.unlock();
}
}
/*(defn distance-obj-to-line
"Distance of an object to a line."*/
public double distanceToLine( Vector3f testPoint, Vector3f linePoint, Vector3f direction ) {
Vector3f diff = Vector3f.sub( testPoint, linePoint, null );
Vector3f diffXv = Vector3f.cross( diff, direction, null );
double ldiff = diff.length();
double sinTheta = diffXv.length() / ( ldiff * direction.length() );
return ( ldiff * sinTheta );
}
/*
* Return all objects along a line with start point, start, and direction vector, direction
* within distance, radius
* NOTE: currently only centers of objects are considered, so radius should account for the largest dimension of the largest object to be considered
*/
public ArrayList<BrObject> objectsAlongLine( double[] start, double[] direction, double radius ) {
ArrayList<BrObject> objs = null;
Vector3f linePoint = new Vector3f( (float)start[0], (float)start[1], (float)start[2] );
Vector3f dirVec= new Vector3f( (float)direction[0], (float)direction[1], (float)direction[2] );
lock.lock(); // block until condition holds
try {
objs = new ArrayList<BrObject>();
spaceTree.clear();
for( Map.Entry<Long,BrObject> entry : objects.entrySet() ) {
BrObject obj = entry.getValue();
Vector3f pos = obj.getPosition();
double[] arryloc = { pos.x, pos.y, pos.z };
BrKDNode n = new BrKDNode( arryloc, entry.getKey() );
spaceTree.add( n );
}
for( Map.Entry<Long,BrObject> entry : objects.entrySet() ) {
BrObject obj = entry.getValue();
Vector<Long> nbrs = new Vector<Long>();
Vector3f pos = obj.getPosition();
double[] arryloc = { pos.x, pos.y, pos.z };
//Iterable<PrioNode<BrKDNode>> itNbrs = spaceTree.search( arryloc, nResults);
//Iterable<PrioNode<BrKDNode>> itNbrs = spaceTree.searchByDistance( arryloc, neighborhoodRadius );
ArrayList<BrKDNode> searchNbrs = spaceTree.searchAlongLine( start, direction, radius);
Iterator<BrKDNode> itr = searchNbrs.iterator();
while( itr.hasNext() ) {
BrKDNode nbr = itr.next();
nbrs.add( nbr.UID );
}
//System.out.println( "Neighbors of " + obj + " " + nbrs.size() );
//obj.nbrs = nbrs;
if( distanceToLine( pos, linePoint, dirVec ) < radius )
objs.add( obj );
}
} finally {
lock.unlock();
}
return objs;
}
/* initWorld
* Initialization functions
*/
public void initWorld( ) {
lock.lock(); // block until condition holds
try {
physics.time = 0;
startWallTime = System.nanoTime();
objects.clear();
addedObjects.clear();
deletedObjects.clear();
collisions.clear();
globalCollisions.clear();
spaceTree.clear();
synchronizeObjects();
} finally {
lock.unlock();
}
}
/* updateWorld
* Run all of the enabled update subroutines including object updates, collisions, etc.
*/
//public void updateWorld( double dt ) {
public void updateWorld() {
// Clear up old collisions
if( collisionsEnabled ) {
physics.clearContactGroup();
}
if( physicsEnabled ) {
synchronizeObjects();
updatePhysics( dt );
synchronizeObjects();
}
// Global update handlers < 0 run before individual object updates
//System.out.println( " pre globalupdate ");
globalUpdateObjects( true );
synchronizeObjects();
//System.out.println( " normal update " + globalUpdateHandlers.size() );
if( brevisParallel ) {
parallelUpdateObjects( dt );
} else {
updateObjects( dt );
}
synchronizeObjects();
//System.out.println( " post globalupdate ");
// Global update handlers >= 0 run after individual object updates
globalUpdateObjects( false );
synchronizeObjects();
if( collisionsEnabled ) {
handleCollisions( dt );
synchronizeObjects();
}
if( neighborhoodsEnabled ) {
updateNeighborhoods();
synchronizeObjects();
}
numSteps++;
}
public double getCurrentSimulationRate( ) {
//System.out.println( "(" + simulationStart + " - " + System.nanoTime() + " ) / " + numSteps );
return numSteps / ( (double) ( System.nanoTime() - simulationStart ) ) * 1000000.0;
}
public boolean getCollisionsEnabled() {
return collisionsEnabled;
}
public void setCollisionsEnabled( boolean newCE ) {
collisionsEnabled = newCE;
}
public boolean getNeighborhoodsEnabled() {
return neighborhoodsEnabled;
}
public void setNeighborhoodsEnabled( boolean newNE ) {
neighborhoodsEnabled = newNE;
}
public DWorld getWorld() {
return physics.getWorld();
}
public DJointGroup getContactGroup() {
return physics.getContactGroup();
}
public DSpace getSpace() {
return physics.getSpace();
}
public double getWallTime() {
return (System.nanoTime() - startWallTime) / 1000000000.0;
}
public double getDT() {
return dt;
}
public void setDT(double newDT) {
dt = newDT;
}
public double getTime() {
return physics.getTime();
}
public long getSteps() {
return numSteps;
}
/* addObject
* Add an object to the simulation
*/
synchronized public void addObject( Long UID, BrObject obj ) {
addedObjects.put( UID, obj );
//System.out.println( "addObject " + UID + " " + obj );
}
synchronized public void setObject( Long UID, BrObject obj ) {
objects.put( UID, obj );
//System.out.println( "addObject " + UID + " " + obj );
}
public void deleteObject( Long UID ) {
deletedObjects.add( UID );
}
public void addUpdateHandler( String type, UpdateHandler uh ) {
System.out.println( "Adding update handler for type: " + type );
updateHandlers.put( type, uh );
}
public void addGlobalUpdateHandler( Long priority, GlobalUpdateHandler gh ) {
System.out.println( "Adding global update handler " + gh + " with priority " + priority );
gh.setPriority( priority );
globalUpdateHandlers.add( gh );
}
public void enableUpdateKinematics( String type ) {
//System.out.println( type );
updateKinematics.put( type, true );
}
public void addCollisionHandler( String typea, String typeb, CollisionHandler ch ) {
SimpleEntry<String,String> typeEntry = new SimpleEntry<String,String>( typea, typeb );
collisionHandlers.put( typeEntry, ch );
}
public Vector<Long> allObjectUIDs() {
Vector<Long> v = new Vector<Long>();
v.addAll( objects.keySet() );
return v;
}
public Vector<Long> allObjectUIDsByType( String type ) {
Vector<Long> v = new Vector<Long>();
for( Map.Entry<Long,BrObject> entry : objects.entrySet() ) {
if( entry.getValue().getType() == type ) {
v.add( entry.getKey() );
}
}
return v;
}
public Collection<BrObject> allObjects() {
return objects.values();
}
public BrObject getObject( Long UID ) {
return objects.get( UID );
}
public void setNeighborhoodRadius( Double r ) {
neighborhoodRadius = r;
}
public double getNeighborhoodRadius() {
return neighborhoodRadius;
}
public Collection<BrObject> getObjects() {
return objects.values();
}
public BrPhysics getPhysics() {
return physics;
}
public DenseMatrix64F pairwiseObjectDistances() {
DenseMatrix64F dists = new DenseMatrix64F( objects.size(), objects.size() );
ArrayList<Long> objKeys = new ArrayList<Long>( objects.keySet() );
for( int k = 0; k < objects.size(); k++ ) {
BrObject thisObj = objects.get( objKeys.get( k ) );
for( int j = 0; j < objects.size(); j++ ) {
double val = 0;
if( k == j ) val = 0;
else {
val = thisObj.distanceTo( objects.get( objKeys.get( j ) ) );
}
dists.set(k,j,val);
dists.set(j,k,val);
}
}
return dists;
}
public void setParallel( boolean newParallel ) {
brevisParallel = newParallel;
}
public boolean getParallel() {
return brevisParallel;
}
/* Serialization stuff */
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
/* private void readObjectNoData() throws ObjectStreamException {
}*/
}
|
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class ValidateBinarySearchTree {
/**
* wrong answer
*
*
* public boolean isValidBST(TreeNode root) {
* if(root == null) {
* return true;
* }
* if(root.left != null && root.left.val >= root.val) {
* return false;
* }
* if(root.right != null && root.right.val >= root.val) {
* return false;
* }
* return isValidBST(root.left) && isValidBST(root.right);
* }
*/
// binary search tree
public static boolean isValidBST1(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
inOrderTraversal(root, list);
for (int i = 1; i < list.size(); i++) {
if (list.get(i) <= list.get(i - 1)) {
return false;
}
}
return true;
}
public static void inOrderTraversal(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inOrderTraversal(root.left, list);
list.add(root.val);
inOrderTraversal(root.right, list);
}
private TreeNode lastNode = null
public boolean isValidBST2(TreeNode root) {
if(root != null) {
if(!isValidBST2(root.left)) {
return false;
}
if(lastNode != null && lastNode.val >= root.val) {
return false;
}
lastNode = root;
if(!isValidBST2(root.right)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
}
}
|
package edu.cmu.cs440.airhockey;
import java.util.Locale;
import android.text.TextUtils;
/**
* A ball has a current location, a trajectory angle, a speed in pixels per
* second, and a last update time. It is capable of updating itself based on its
* trajectory and speed.
*
* It also knows its boundaries, and will 'bounce' off them when it reaches
* them.
*/
public class Puck extends Shape {
// TODO: make these values specific to the user's device size and density
public static final float MIN_SPEED = 100f;
public static final float MAX_SPEED = 900f;
private PuckRegion mRegion;
private int mId;
private float mX;
private float mY;
private double mDirection;
private float mRadiusPixels;
private float mPixelsPerSecond;
private boolean mPressed;
private long mLastUpdate;
private int mHasExited;
private Color mColor;
private String mLastUser;
private Puck(long now, int id, float pps, float x, float y, double angle, float radius,
Color color, String lastUser) {
mId = id;
mX = x;
mY = y;
mDirection = angle;
mRadiusPixels = radius;
mPixelsPerSecond = pps;
mPressed = false;
mLastUpdate = now;
mHasExited = -1;
mColor = color;
mLastUser = lastUser;
}
public int getId() {
return mId;
}
/**
* Returns the x coordinate of the ball's origin.
*/
public float getX() {
return mX;
}
/**
* Returns the y coordinate of the ball's origin.
*/
public float getY() {
return mY;
}
/**
* Sets the ball's origin to point (x,y).
*/
public void setCoords(float x, float y) {
mX = x;
mY = y;
}
/** {@inheritDoc} */
@Override
public float getLeft() {
return mX - mRadiusPixels;
}
/** {@inheritDoc} */
@Override
public float getRight() {
return mX + mRadiusPixels;
}
/** {@inheritDoc} */
@Override
public float getTop() {
return mY - mRadiusPixels;
}
/** {@inheritDoc} */
@Override
public float getBottom() {
return mY + mRadiusPixels;
}
public double getAngle() {
return mDirection;
}
public void setDirection(double angle) {
mDirection = angle;
}
public float getRadiusPixels() {
return mRadiusPixels;
}
public void setRadiusPixels(float radiusPixels) {
mRadiusPixels = radiusPixels;
}
public float getPixelsPerSecond() {
return mPixelsPerSecond;
}
public void setPixelsPerSecond(float pps) {
mPixelsPerSecond = pps;
}
public Color getColor() {
return mColor;
}
public void setColor(Color color) {
mColor = color;
}
public boolean isPressed() {
return mPressed;
}
public void setPressed(boolean pressed) {
mPressed = pressed;
}
public int hasExited() {
return mHasExited;
}
public void setExited(int i) {
mHasExited = i;
}
public void setLastUser(String lastUser) {
mLastUser = lastUser;
}
public String getLastUser() {
return mLastUser;
}
/**
* Get the region that this ball is contained in.
*/
public Shape getRegion() {
return mRegion;
}
/**
* Set the region that this ball is contained in.
*/
public void setRegion(PuckRegion region) {
if (region.isGoal()) {
if (mX < region.getLeft()) {
mX = region.getLeft();
} else if (region.getRight() < mX) {
mX = region.getRight();
}
if (mY < region.getTop()) {
mY = region.getTop();
} else if (region.getBottom() < mY) {
mY = region.getBottom();
}
}
mRegion = region;
}
public void setNow(long now) {
mLastUpdate = now;
}
public void update(long now) {
if (now <= mLastUpdate) {
// Don't update if 'now' is outdated.
return;
} else if (mPressed) {
// Don't update if the ball is being held.
return;
}
if (mRegion.isGoal()) {
// bounce when at walls
if (mX <= mRegion.getLeft() + mRadiusPixels) { // at left wall
mX = mRegion.getLeft() + mRadiusPixels;
bounceOffLeft();
} else if (mY <= mRegion.getTop() + mRadiusPixels) { // at top wall
mY = mRegion.getTop() + mRadiusPixels;
bounceOffTop();
} else if (mX >= mRegion.getRight() - mRadiusPixels) { // at right wall
mX = mRegion.getRight() - mRadiusPixels;
bounceOffRight();
} else if (mY >= mRegion.getBottom() - mRadiusPixels) { // at bottom wall
mY = mRegion.getBottom() - mRadiusPixels;
bounceOffBottom();
}
} else {
// fall out of the screen... don't bounce at walls
if (mX <= -mRadiusPixels) {
// at left wall
mHasExited = PuckRegion.LEFT;
} else if (mY <= -mRadiusPixels) {
// at top wall
mHasExited = PuckRegion.TOP;
} else if (mX >= mRegion.getRight() + AirHockeyView.BORDER_WIDTH + mRadiusPixels) {
// TODO: figure out if adding the border width here is necessary?
// at right wall
mHasExited = PuckRegion.RIGHT;
} else if (mY >= mRegion.getBottom() + AirHockeyView.BORDER_WIDTH + mRadiusPixels) {
// TODO: figure out if adding the border width here is necessary?
// at bottom wall
mHasExited = PuckRegion.BOTTOM;
}
}
// TODO: make this smoother for large screens with low-ish densities
// (i.e. the Motorola Xoom!)
float delta = (now - mLastUpdate) * mPixelsPerSecond;
delta = delta / 1000f;
mX += (delta * Math.cos(mDirection));
mY += (delta * Math.sin(mDirection));
double friction;
if (mRegion.isGoal()) {
// Balls in the goal region slow down faster... this reduces the
// visually apparent "spaz" effect when a ball enters the goal region :P
friction = 0.98;
} else {
friction = 0.995;
}
double newSpeed = friction * mPixelsPerSecond;
mPixelsPerSecond = (float) Math.max(newSpeed, MIN_SPEED);
mLastUpdate = now;
}
private void bounceOffBottom() {
if (mDirection < 0.5 * Math.PI) {
mDirection = -mDirection; // going right
} else {
mDirection += (Math.PI - mDirection) * 2; // going left
}
}
private void bounceOffRight() {
if (mDirection > 1.5 * Math.PI) {
mDirection -= (mDirection - 1.5 * Math.PI) * 2; // going up
} else {
mDirection += (0.5 * Math.PI - mDirection) * 2; // going down
}
}
private void bounceOffTop() {
if (mDirection < 1.5 * Math.PI) {
mDirection -= (mDirection - Math.PI) * 2; // going left
} else {
mDirection += (2 * Math.PI - mDirection) * 2; // going right
mDirection -= 2 * Math.PI;
}
}
private void bounceOffLeft() {
if (mDirection < Math.PI) {
mDirection -= ((mDirection - (Math.PI / 2)) * 2); // going down
} else {
mDirection += (((1.5 * Math.PI) - mDirection) * 2); // going up
}
}
public boolean isCircleOverlapping(Puck otherBall) {
float dy = otherBall.mY - mY;
float dx = otherBall.mX - mX;
float distance = dy * dy + dx * dx;
return (distance < ((2 * mRadiusPixels) * (2 * mRadiusPixels)))
&& !movingAwayFromEachother(this, otherBall); // avoid messy collisions
}
private boolean movingAwayFromEachother(Puck b1, Puck b2) {
double collA = Math.atan2(b2.mY - b1.mY, b2.mX - b1.mX);
double collB = Math.atan2(b1.mY - b2.mY, b1.mX - b2.mX);
double ax = Math.cos(b1.mDirection - collA);
double bx = Math.cos(b2.mDirection - collB);
return ax + bx < 0;
}
/**
* Given that ball a and b have collided, adjust their angles to reflect their
* state after the collision.
*
* @param b1
* The first ball in a collision
* @param b2
* The second ball in a collision
*/
public static void adjustForCollision(Puck b1, Puck b2) {
// TODO: account for balls with different velocities... this method
// technically doesn't follow the laws of conservation of energy.
double collA = Math.atan2(b2.mY - b1.mY, b2.mX - b1.mX);
double collB = Math.atan2(b1.mY - b2.mY, b1.mX - b2.mX);
double ax = Math.cos(b1.mDirection - collA);
double ay = Math.sin(b1.mDirection - collA);
double bx = Math.cos(b2.mDirection - collB);
double by = Math.cos(b2.mDirection - collB);
double diffA = Math.atan2(ay, -bx);
double diffB = Math.atan2(by, -ax);
b1.mDirection = collA + diffA;
b2.mDirection = collB + diffB;
}
@Override
public String toString() {
return String.format(Locale.US,
"Ball(id=%d, x=%f, y=%f, angle=%f, speed=%f, color=%s, exitEdge=%s)", mId, mX, mY,
Math.toDegrees(mDirection), (float) mPixelsPerSecond, Utils.colorToStr(mColor),
Utils.exitEdgeToStr(mHasExited));
}
/**
* A more readable way to create balls than using a 5 param constructor of all
* numbers.
*/
public static class Builder {
private long mNow = -1;
private int mId = -1;
private float mX = -1;
private float mY = -1;
private double mAngle = -1;
private float mRadiusPixels = -1;
private float mPixelsPerSecond = 120f;
private Color mPuckColor = Color.Blue;
private String mLastUser = null;
public Puck create() {
if (mNow < 0) {
throw new IllegalStateException("must set 'now'");
}
if (mId < 0) {
throw new IllegalStateException("id must be set");
}
// if (mX < 0) {
// if (mY < 0) {
if (mAngle > 2 * Math.PI) {
throw new IllegalStateException("angle must be less that 2Pi");
}
if (mRadiusPixels <= 0) {
throw new IllegalStateException("radius must be set");
}
if (TextUtils.isEmpty(mLastUser)) {
throw new IllegalStateException("puck must belong to a user!");
}
return new Puck(mNow, mId, mPixelsPerSecond, mX, mY, mAngle, mRadiusPixels, mPuckColor,
mLastUser);
}
public Builder setId(int id) {
mId = id;
return this;
}
public Builder setNow(long now) {
mNow = now;
return this;
}
public Builder setX(float x) {
mX = x;
return this;
}
public Builder setY(float y) {
mY = y;
return this;
}
public Builder setAngle(double angle) {
mAngle = angle;
return this;
}
public Builder setRadiusPixels(float pixels) {
mRadiusPixels = pixels;
return this;
}
public Builder setPixelsPerSecond(float pixelsPerSecond) {
mPixelsPerSecond = pixelsPerSecond;
return this;
}
public Builder setColor(Color color) {
mPuckColor = color;
return this;
}
public Builder setLastUser(String lastUser) {
mLastUser = lastUser;
return this;
}
}
public enum Color {
Blue, Green, LightBlue, Orange, Purple, Red, Yellow,
}
}
|
package okio;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static java.util.Arrays.asList;
import static okio.TestUtil.repeat;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class BufferedSinkTest {
private interface Factory {
BufferedSink create(Buffer data);
}
@Parameterized.Parameters(name = "{0}")
public static List<Object[]> parameters() {
return Arrays.asList(new Object[] {
new Factory() {
@Override public BufferedSink create(Buffer data) {
return data;
}
@Override public String toString() {
return "Buffer";
}
}
}, new Object[] {
new Factory() {
@Override public BufferedSink create(Buffer data) {
return new RealBufferedSink(data);
}
@Override public String toString() {
return "RealBufferedSink";
}
}
});
}
@Parameterized.Parameter
public Factory factory;
private Buffer data;
private BufferedSink sink;
@Before public void setUp() {
data = new Buffer();
sink = factory.create(data);
}
@Test public void writeNothing() throws IOException {
sink.writeUtf8("");
sink.flush();
assertEquals(0, data.size());
}
@Test public void writeBytes() throws Exception {
sink.writeByte(0xab);
sink.writeByte(0xcd);
sink.flush();
assertEquals("Buffer[size=2 data=abcd]", data.toString());
}
@Test public void writeLastByteInSegment() throws Exception {
sink.writeUtf8(repeat('a', Segment.SIZE - 1));
sink.writeByte(0x20);
sink.writeByte(0x21);
sink.flush();
assertEquals(asList(Segment.SIZE, 1), data.segmentSizes());
assertEquals(repeat('a', Segment.SIZE - 1), data.readUtf8(Segment.SIZE - 1));
assertEquals("Buffer[size=2 data=2021]", data.toString());
}
@Test public void writeShort() throws Exception {
sink.writeShort(0xabcd);
sink.writeShort(0x4321);
sink.flush();
assertEquals("Buffer[size=4 data=abcd4321]", data.toString());
}
@Test public void writeShortLe() throws Exception {
sink.writeShortLe(0xabcd);
sink.writeShortLe(0x4321);
sink.flush();
assertEquals("Buffer[size=4 data=cdab2143]", data.toString());
}
@Test public void writeInt() throws Exception {
sink.writeInt(0xabcdef01);
sink.writeInt(0x87654321);
sink.flush();
assertEquals("Buffer[size=8 data=abcdef0187654321]", data.toString());
}
@Test public void writeLastIntegerInSegment() throws Exception {
sink.writeUtf8(repeat('a', Segment.SIZE - 4));
sink.writeInt(0xabcdef01);
sink.writeInt(0x87654321);
sink.flush();
assertEquals(asList(Segment.SIZE, 4), data.segmentSizes());
assertEquals(repeat('a', Segment.SIZE - 4), data.readUtf8(Segment.SIZE - 4));
assertEquals("Buffer[size=8 data=abcdef0187654321]", data.toString());
}
@Test public void writeIntegerDoesNotQuiteFitInSegment() throws Exception {
sink.writeUtf8(repeat('a', Segment.SIZE - 3));
sink.writeInt(0xabcdef01);
sink.writeInt(0x87654321);
sink.flush();
assertEquals(asList(Segment.SIZE - 3, 8), data.segmentSizes());
assertEquals(repeat('a', Segment.SIZE - 3), data.readUtf8(Segment.SIZE - 3));
assertEquals("Buffer[size=8 data=abcdef0187654321]", data.toString());
}
@Test public void writeIntLe() throws Exception {
sink.writeIntLe(0xabcdef01);
sink.writeIntLe(0x87654321);
sink.flush();
assertEquals("Buffer[size=8 data=01efcdab21436587]", data.toString());
}
@Test public void writeLong() throws Exception {
sink.writeLong(0xabcdef0187654321L);
sink.writeLong(0xcafebabeb0b15c00L);
sink.flush();
assertEquals("Buffer[size=16 data=abcdef0187654321cafebabeb0b15c00]", data.toString());
}
@Test public void writeLongLe() throws Exception {
sink.writeLongLe(0xabcdef0187654321L);
sink.writeLongLe(0xcafebabeb0b15c00L);
sink.flush();
assertEquals("Buffer[size=16 data=2143658701efcdab005cb1b0bebafeca]", data.toString());
}
@Test public void writeSpecificCharset() throws Exception {
sink.writeString("təˈranəˌsôr", Charset.forName("utf-32be"));
sink.flush();
assertEquals(ByteString.decodeHex("0000007400000259000002c800000072000000610000006e00000259"
+ "000002cc00000073000000f400000072"), data.readByteString());
}
@Test public void writeAll() throws Exception {
Buffer source = new Buffer().writeUtf8("abcdef");
assertEquals(6, sink.writeAll(source));
assertEquals(0, source.size());
sink.flush();
assertEquals("abcdef", data.readUtf8());
}
@Test public void writeAllExhausted() throws Exception {
Buffer source = new Buffer();
assertEquals(0, sink.writeAll(source));
assertEquals(0, source.size());
}
@Test public void closeEmitsBufferedBytes() throws IOException {
sink.writeByte('a');
sink.close();
assertEquals('a', data.readByte());
}
}
|
package pt.fraunhofer.pulse;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.WindowManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.MyCameraBridgeViewBase;
import org.opencv.android.MyCameraBridgeViewBase.CvCameraViewListener;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.core.Rect;
import org.opencv.highgui.Highgui;
import pt.fraunhofer.pulse.Pulse.Face;
import pt.fraunhofer.pulse.dialog.AppConfigDialog;
import pt.fraunhofer.pulse.view.BpmView;
import pt.fraunhofer.pulse.view.PulseView;
public class App extends Activity implements CvCameraViewListener {
private static final String TAG = "Pulse::App";
private MyCameraBridgeViewBase camera;
private BpmView bpmView;
private PulseView pulseView;
private Pulse pulse;
private Paint faceBoxPaint;
private AppConfigDialog configDialog;
private BaseLoaderCallback loaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
loaderCallbackSuccess();
break;
default:
super.onManagerConnected(status);
break;
}
}
};
private void loaderCallbackSuccess() {
System.loadLibrary("pulse");
pulse = new Pulse();
File dir = getDir("cascade", Context.MODE_PRIVATE);
File file = createFileFromResource(dir, R.raw.lbpcascade_frontalface, "xml");
pulse.load(file.getAbsolutePath());
dir.delete();
pulseView.setGridSize(pulse.getMaxSignalSize());
configDialog = new AppConfigDialog(pulse);
camera.enableView();
}
private File createFileFromResource(File dir, int id, String extension) {
String name = getResources().getResourceEntryName(id) + "." + extension;
InputStream is = getResources().openRawResource(id);
File file = new File(dir, name);
try {
FileOutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
} catch (IOException ex) {
Log.e(TAG, "Failed to create file: " + file.getPath(), ex);
}
return file;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.app);
camera = (MyCameraBridgeViewBase) findViewById(R.id.camera);
camera.setCvCameraViewListener(this);
camera.SetCaptureFormat(Highgui.CV_CAP_ANDROID_COLOR_FRAME_RGB);
camera.setMaxFrameSize(650, 650);
bpmView = (BpmView) findViewById(R.id.bpm);
pulseView = (PulseView) findViewById(R.id.pulse);
faceBoxPaint = initFaceBoxPaint();
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
camera.setCameraId(savedInstanceState.getInt("cameraId"));
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("cameraId", camera.getCameraId());
}
@Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5, this, loaderCallback);
}
@Override
public void onPause() {
if (camera != null) {
camera.disableView();
}
bpmView.setNoBpm();
pulseView.setNoPulse();
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.app, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.switch_camera:
camera.switchCamera();
return true;
case R.id.config:
if (configDialog != null) configDialog.show(getFragmentManager(), null);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCameraViewStarted(int width, int height) {
Log.d(TAG, "onCameraViewStarted("+width+", "+height+")");
pulse.start(width, height);
}
@Override
public void onCameraViewStopped() {
}
@Override
public Mat onCameraFrame(Mat frame) {
pulse.onFrame(frame);
return frame;
}
@Override
public void onCameraFrame(Canvas canvas) {
Face face = getCurrentFace(pulse.getFaces()); // TODO support multiple faces
if (face != null) {
onFace(canvas, face);
} else {
// no faces
runOnUiThread(new Runnable() {
@Override
public void run() {
bpmView.setNoBpm();
pulseView.setNoPulse();
}
});
}
}
private int currentFaceId = 0;
private Face getCurrentFace(Face[] faces) {
Face face = null;
if (currentFaceId > 0) {
face = findFace(faces, currentFaceId);
}
if (face == null && faces.length > 0) {
face = faces[0];
}
if (face == null) {
currentFaceId = 0;
} else {
currentFaceId = face.getId();
}
return face;
}
private Face findFace(Face[] faces, int id) {
for (Face face : faces) {
if (face.getId() == id) {
return face;
}
}
return null;
}
private void onFace(Canvas canvas, Face face) {
// draw face box
canvas.drawPath(createFaceBoxPath(face.getBox()), faceBoxPaint);
// update views
if (face.existsPulse()) {
final double bpm = face.getBpm();
final double[] signal = face.getPulse();
runOnUiThread(new Runnable() {
@Override
public void run() {
bpmView.setBpm(bpm);
pulseView.setPulse(signal);
}
});
} else {
// no pulse
runOnUiThread(new Runnable() {
@Override
public void run() {
bpmView.setNoBpm();
pulseView.setNoPulse();
}
});
}
}
private Paint initFaceBoxPaint() {
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(Color.WHITE);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(4);
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeJoin(Paint.Join.ROUND);
return p;
}
private Path createFaceBoxPath(Rect box) {
float size = box.width * 0.25f;
Path path = new Path();
// top left
path.moveTo(box.x, box.y + size);
path.lineTo(box.x, box.y);
path.lineTo(box.x + size, box.y);
// top right
path.moveTo(box.x + box.width, box.y + size);
path.lineTo(box.x + box.width, box.y);
path.lineTo(box.x + box.width - size, box.y);
// bottom left
path.moveTo(box.x, box.y + box.height - size);
path.lineTo(box.x, box.y + box.height);
path.lineTo(box.x + size, box.y + box.height);
// bottom right
path.moveTo(box.x + box.width, box.y + box.height - size);
path.lineTo(box.x + box.width, box.y + box.height);
path.lineTo(box.x + box.width - size, box.y + box.height);
return path;
}
}
|
package org.bimserver;
import java.nio.file.Paths;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.websocket.DeploymentException;
import javax.websocket.Session;
import org.bimserver.servlets.RootServlet;
import org.bimserver.servlets.websockets.jsr356.AdditionalWebSocketConfigurator;
import org.bimserver.servlets.websockets.jsr356.Jsr356Impl;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.eclipse.jetty.websocket.jsr356.JsrSession;
import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EmbeddedWebServer implements EmbeddedWebServerInterface {
private static final Logger LOGGER = LoggerFactory.getLogger(EmbeddedWebServer.class);
private WebAppContext context;
private Server server;
@SuppressWarnings("unchecked")
public EmbeddedWebServer(BimServer bimServer, String resourceBase, boolean localDev) {
server = new Server(new QueuedThreadPool(200, 20));
ServerConnector socketConnector = new ServerConnector(server);
socketConnector.setPort(bimServer.getConfig().getPort());
socketConnector.setIdleTimeout(10800000); // 3 hours for bulkcheckin
socketConnector.setStopTimeout(10800000); // 3 hours for bulkcheckin
server.addConnector(socketConnector);
context = new WebAppContext(server, "", "/");
context.setTempDirectory(bimServer.getHomeDir().resolve("jettytmp").toFile());
try {
org.eclipse.jetty.websocket.jsr356.server.ServerContainer configureContext = WebSocketServerContainerInitializer.configureContext(context);
// TODO this speeds up local loading, but for remote loading it's probably faster to enable permessage-deflate
configureContext.getWebSocketServerFactory().getExtensionFactory().unregister("permessage-deflate");
Jsr356Impl.setServletContext(configureContext, context.getServletContext());
Jsr356Impl.setAdditionalWebSocketConfigurator(new AdditionalWebSocketConfigurator() {
@Override
public void configure(Session websocketSession) {
JsrSession jsrSession = (JsrSession)websocketSession;
WebSocketPolicy policy = jsrSession.getPolicy();
websocketSession.setMaxTextMessageBufferSize(1024 * 1024 * 64);
websocketSession.setMaxBinaryMessageBufferSize(1024 * 1024 * 512);
policy.setMaxTextMessageSize(1024 * 1024 * 64);
}
});
configureContext.addEndpoint(Jsr356Impl.class);
} catch (ServletException e) {
e.printStackTrace();
} catch (DeploymentException e) {
e.printStackTrace();
}
if (localDev) {
// TODO document why
// context.setDefaultsDescriptor("../BimServer/www/WEB-INF/webdefault.xml");
}
ServletHolder servletHolder = new ServletHolder(new RootServlet());
|
package etomica.normalmode;
import java.awt.Color;
import java.util.Arrays;
import etomica.action.activity.ActivityIntegrate;
import etomica.api.IAtom;
import etomica.api.IAtomType;
import etomica.api.IBox;
import etomica.box.Box;
import etomica.data.AccumulatorAverageCovariance;
import etomica.data.DataPumpListener;
import etomica.data.DataSourceCountSteps;
import etomica.data.IData;
import etomica.data.meter.MeterPotentialEnergy;
import etomica.graphics.ColorScheme;
import etomica.graphics.DisplayTextBox;
import etomica.graphics.SimulationGraphic;
import etomica.integrator.IntegratorMC;
import etomica.lattice.crystal.Basis;
import etomica.lattice.crystal.BasisCubicFcc;
import etomica.lattice.crystal.Primitive;
import etomica.lattice.crystal.PrimitiveCubic;
import etomica.liquidLJ.DataProcessorReweight;
import etomica.liquidLJ.DataProcessorReweightRatio;
import etomica.liquidLJ.Potential2SoftSphericalLSMultiLat;
import etomica.liquidLJ.ValueCache;
import etomica.nbr.list.PotentialMasterList;
import etomica.potential.P2LennardJones;
import etomica.potential.P2SoftSphere;
import etomica.potential.P2SoftSphericalTruncated;
import etomica.potential.Potential2SoftSpherical;
import etomica.potential.PotentialMasterMonatomic;
import etomica.simulation.Simulation;
import etomica.space.Boundary;
import etomica.space.BoundaryRectangularPeriodic;
import etomica.space.Space;
import etomica.species.SpeciesSpheresMono;
import etomica.util.ParameterBase;
import etomica.util.ParseArgs;
import etomica.util.RandomMersenneTwister;
public class SimLJHTTISuper extends Simulation {
public SimLJHTTISuper(Space _space, int numAtoms, double density, double temperature, double rc, boolean ss) {
super(_space);
potentialMaster = new PotentialMasterList(this, space);
species = new SpeciesSpheresMono(this, space);
addSpecies(species);
// TARGET
box = new Box(space);
addBox(box);
box.setNMolecules(species, numAtoms);
integrator = new IntegratorMC(potentialMaster, getRandom(), temperature);
MeterPotentialEnergy meterPE = new MeterPotentialEnergy(potentialMaster);
meterPE.setBox(box);
atomMove = new MCMoveAtomCoupled(potentialMaster, meterPE, getRandom(), space);
atomMove.setStepSize(0.1);
atomMove.setStepSizeMax(0.5);
atomMove.setDoExcludeNonNeighbors(true);
integrator.getMoveManager().addMCMove(atomMove);
// ((MCMoveStepTracker)atomMove.getTracker()).setNoisyAdjustment(true);
double L = Math.pow(4.0/density, 1.0/3.0);
double nbrDistance = L / Math.sqrt(2);
int n = (int)Math.round(Math.pow(numAtoms/4, 1.0/3.0));
primitive = new PrimitiveCubic(space, n*L);
nCells = new int[]{n,n,n};
boundary = new BoundaryRectangularPeriodic(space, n * L);
Basis basisFCC = new BasisCubicFcc();
basis = new BasisBigCell(space, basisFCC, nCells);
box.setBoundary(boundary);
coordinateDefinition = new CoordinateDefinitionLeaf(box, primitive, basis, space);
coordinateDefinition.initializeCoordinates(new int[]{1,1,1});
potential = ss ? new P2SoftSphere(space, 1.0, 4.0, 12) : new P2LennardJones(space, 1.0, 1.0);
potential = new P2SoftSphericalTruncated(space, potential, rc);
atomMove.setPotential(potential);
IAtomType sphereType = species.getLeafType();
potentialMaster.addPotential(potential, new IAtomType[] {sphereType, sphereType });
/*
* 1-body Potential to Constraint the atom from moving too far
* away from its lattice-site
*
*/
P1ConstraintNbr p1Constraint = new P1ConstraintNbr(space, nbrDistance, this);
p1Constraint.initBox(box);
atomMove.setConstraint(p1Constraint);
potentialMaster.lrcMaster().setEnabled(false);
integrator.setBox(box);
int cellRange = 7;
potentialMaster.setRange(rc);
potentialMaster.setCellRange(cellRange); // insanely high, this lets us have neighborRange close to dimensions/2
// find neighbors now. Don't hook up NeighborListManager (neighbors won't change)
potentialMaster.getNeighborManager(box).reset();
int potentialCells = potentialMaster.getNbrCellManager(box).getLattice().getSize()[0];
if (potentialCells < cellRange*2+1) {
throw new RuntimeException("oops ("+potentialCells+" < "+(cellRange*2+1)+")");
}
activityIntegrate = new ActivityIntegrate(integrator);
getController().addAction(activityIntegrate);
// extend potential range, so that atoms that move outside the truncation range will still interact
// atoms that move in will not interact since they won't be neighbors
((P2SoftSphericalTruncated)potential).setTruncationRadius(0.6*boundary.getBoxSize().getX(0));
}
public void initialize(long initSteps) {
// equilibrate off the lattice to avoid anomolous contributions
activityIntegrate.setMaxSteps(initSteps);
getController().actionPerformed();
getController().reset();
integrator.getMoveManager().setEquilibrating(false);
}
/**
* @param args filename containing simulation parameters
* @see SimLJHTTI.SimOverlapParam
*/
public static void main(String[] args) {
//set up simulation parameters
SimOverlapParam params = new SimOverlapParam();
if (args.length == 0) {
params.numAtoms = 500;
params.numSteps = 1000000;
params.temperature = 1;
params.density = 1;
params.rcMax0 = 13;
params.rc = 3;
params.bpharm = new double[]{}; // 864
params.bpharm = new double[]{9.550752087386252e+00,9.554899656911383e+00,9.557975701182272e+00,9.561039289571333e+00,9.561785691168332e+00,9.562084920108349e+00,9.562184015777641e+00,9.562223770855450e+00,9.562237600652669e+00}; //500
params.bpharmLJ = new double[]{1.361085875265710e+00,1.362422294066396e+00,1.363399142959180e+00,1.364383687422787e+00,1.364621191334029e+00,1.364711705394565e+00,1.364747826183867e+00,1.364760708535937e+00,1.364768368160011e+00}; //500
params.ss = true;
}
else {
ParseArgs.doParseArgs(params, args);
}
boolean ss = params.ss;
double density = params.density;
long numSteps = params.numSteps;
final int numAtoms = params.numAtoms;
double temperature = params.temperature;
double rc = params.rc;
double rcMax0 = params.rcMax0;
double[] bpharm = params.bpharm;
double[] bpharmLJ = params.bpharmLJ;
System.out.println("Running "+(ss?"soft-sphere":"Lennard-Jones")+" simulation");
System.out.println(numAtoms+" atoms at density "+density+" and temperature "+temperature);
System.out.println(numSteps+" steps");
//instantiate simulation
final SimLJHTTISuper sim = new SimLJHTTISuper(Space.getInstance(3), numAtoms, density, temperature, rc*Math.pow(density, -1.0/3.0), ss);
int[] seeds = ((RandomMersenneTwister)sim.getRandom()).getSeedArray();
System.out.println("Random seeds: "+Arrays.toString(seeds));
if (false) {
SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, sim.space, sim.getController());
simGraphic.setPaintInterval(sim.box, 1000);
ColorScheme colorScheme = new ColorScheme() {
public Color getAtomColor(IAtom a) {
if (allColors==null) {
allColors = new Color[768];
for (int i=0; i<256; i++) {
allColors[i] = new Color(255-i,i,0);
}
for (int i=0; i<256; i++) {
allColors[i+256] = new Color(0,255-i,i);
}
for (int i=0; i<256; i++) {
allColors[i+512] = new Color(i,0,255-i);
}
}
return allColors[(2*a.getLeafIndex()) % 768];
}
protected Color[] allColors;
};
simGraphic.getDisplayBox(sim.box).setColorScheme(colorScheme);
DisplayTextBox timer = new DisplayTextBox();
DataSourceCountSteps counter = new DataSourceCountSteps(sim.integrator);
DataPumpListener counterPump = new DataPumpListener(counter, timer, 100);
sim.integrator.getEventManager().addListener(counterPump);
simGraphic.getPanel().controlPanel.add(timer.graphic());
simGraphic.makeAndDisplayFrame("SS");
return;
}
//start simulation
double L = Math.pow(numAtoms, 1.0/3.0);
double rcMax1 = 0.494*L;
if (rcMax1>rcMax0) rcMax1 = rcMax0;
double delta = 0.5;
int nCutoffs = 1;
double c = rc;
for (nCutoffs=1; c<rcMax1; nCutoffs++) {
c += delta;
if (nCutoffs%2==0) delta += 0.5;
}
nCutoffs
if (nCutoffs > bpharm.length) {
throw new RuntimeException("need more beta P harmonic");
}
delta = 0.5;
double[] cutoffs = new double[nCutoffs];
cutoffs[0] = rc;
for (int i=1; i<nCutoffs; i++) {
cutoffs[i] = cutoffs[i-1] + delta;
if (i%2==0) delta += 0.5;
}
for (int i=0; i<nCutoffs; i++) {
cutoffs[i] *= Math.pow(density, -1.0/3.0);
}
PotentialMasterList potentialMasterData;
Potential2SoftSpherical potential = ss ? new P2SoftSphere(sim.getSpace(), 1.0, 4.0, 12) : new P2LennardJones(sim.getSpace(), 1.0, 1.0);
{
// |potential| is our local potential used for data collection.
potentialMasterData = new PotentialMasterList(sim, cutoffs[nCutoffs-1], sim.getSpace());
P2SoftSphericalTruncated potentialT = new P2SoftSphericalTruncated(sim.getSpace(), potential, cutoffs[nCutoffs-1]-0.01);
IAtomType sphereType = sim.species.getLeafType();
potentialMasterData.addPotential(potentialT, new IAtomType[] {sphereType, sphereType });
potentialMasterData.lrcMaster().setEnabled(false);
int cellRange = 7;
potentialMasterData.setCellRange(cellRange); // insanely high, this lets us have neighborRange close to dimensions/2
// find neighbors now. Don't hook up NeighborListManager (neighbors won't change)
potentialMasterData.getNeighborManager(sim.box).reset();
int potentialCells = potentialMasterData.getNbrCellManager(sim.box).getLattice().getSize()[0];
if (potentialCells < cellRange*2+1) {
throw new RuntimeException("oops ("+potentialCells+" < "+(cellRange*2+1)+")");
}
// extend potential range, so that atoms that move outside the truncation range will still interact
// atoms that move in will not interact since they won't be neighbors
potentialT.setTruncationRadius(0.6*sim.box.getBoundary().getBoxSize().getX(0));
}
PotentialMasterList potentialMasterDataLJ = null;
P2LennardJones p2LJ = null;
Potential2SoftSpherical potentialLJ = null;
if (ss) {
// |potential| is our local potential used for data collection.
potentialMasterDataLJ = new PotentialMasterList(sim, cutoffs[nCutoffs-1], sim.getSpace());
p2LJ = new P2LennardJones(sim.getSpace());
potentialLJ = new P2SoftSphericalTruncated(sim.getSpace(), p2LJ, cutoffs[nCutoffs-1]-0.01);
IAtomType sphereType = sim.species.getLeafType();
potentialMasterDataLJ.addPotential(potentialLJ, new IAtomType[] {sphereType, sphereType });
potentialMasterDataLJ.lrcMaster().setEnabled(false);
int cellRange = 7;
potentialMasterDataLJ.setCellRange(cellRange); // insanely high, this lets us have neighborRange close to dimensions/2
// find neighbors now. Don't hook up NeighborListManager (neighbors won't change)
potentialMasterDataLJ.getNeighborManager(sim.box).reset();
int potentialCells = potentialMasterDataLJ.getNbrCellManager(sim.box).getLattice().getSize()[0];
if (potentialCells < cellRange*2+1) {
throw new RuntimeException("oops ("+potentialCells+" < "+(cellRange*2+1)+")");
}
// extend potential range, so that atoms that move outside the truncation range will still interact
// atoms that move in will not interact since they won't be neighbors
((P2SoftSphericalTruncated)potentialLJ).setTruncationRadius(0.6*sim.box.getBoundary().getBoxSize().getX(0));
}
// meter needs lattice energy, so make it now
MeterSolidDACut meterSolid = new MeterSolidDACut(sim.getSpace(), potentialMasterData, sim.coordinateDefinition, cutoffs);
meterSolid.setTemperature(temperature);
meterSolid.setBPRes(bpharm);
IData d = meterSolid.getData();
MeterPotentialEnergy meterEnergyShort = new MeterPotentialEnergy(sim.potentialMaster);
meterEnergyShort.setBox(sim.box);
final double[] uFacCut = new double[cutoffs.length];
double uShort = meterEnergyShort.getDataAsScalar();
for (int i=0; i<uFacCut.length; i++) {
uFacCut[i] = d.getValue(5*i)*numAtoms - uShort;
}
if (ss) {
if (bpharmLJ.length != bpharm.length) {
throw new RuntimeException("I need LJ harmonic pressures for all cutoffs");
}
meterSolid.setPotentialMasterDADv2(potentialMasterDataLJ, bpharmLJ);
}
double rcMaxLS = 3*rcMax1;
if (rcMax1 >= rcMax0) rcMaxLS=0;
else if (rcMaxLS>rcMax0) rcMaxLS = rcMax0;
delta = 0.5;
int nCutoffsLS = 1;
c = rc;
for (nCutoffsLS=1; c<rcMaxLS; nCutoffsLS++) {
c += delta;
if (nCutoffsLS%2==0) delta += 0.5;
}
nCutoffsLS
if (nCutoffsLS > bpharm.length) {
throw new RuntimeException("need more beta P harmonic");
}
final double[] cutoffsLS = new double[nCutoffsLS];
PotentialMasterMonatomic potentialMasterLS = new PotentialMasterMonatomic(sim);
Potential2SoftSphericalLSMultiLat pLS = null;
PotentialMasterMonatomic potentialMasterLJLS = null;
Potential2SoftSphericalLSMultiLat pLJLS = null;
final double[] uFacCutLS = new double[cutoffsLS.length];
MeterSolidDACut meterSolidLS = null;
if (nCutoffsLS>0) {
cutoffsLS[0] = cutoffs[0];
delta = 0.5;
for (int i=1; i<cutoffsLS.length; i++) {
cutoffsLS[i] = cutoffsLS[i-1] + delta;
if (i%2==0) delta += 0.5;
}
for (int i=0; i<nCutoffsLS; i++) {
cutoffsLS[i] *= Math.pow(density, -1.0/3.0);
}
pLS = new Potential2SoftSphericalLSMultiLat(sim.getSpace(), cutoffsLS, potential, sim.coordinateDefinition);
potentialMasterLS.addPotential(pLS, new IAtomType[]{sim.species.getLeafType(),sim.species.getLeafType()});
meterSolidLS = new MeterSolidDACut(sim.getSpace(), potentialMasterLS, sim.coordinateDefinition, cutoffsLS);
meterSolidLS.setTemperature(temperature);
meterSolidLS.setBPRes(bpharm);
d = meterSolidLS.getData();
if (params.ss) {
potentialMasterLJLS = new PotentialMasterMonatomic(sim);
pLJLS = new Potential2SoftSphericalLSMultiLat(sim.getSpace(), cutoffsLS, p2LJ, sim.coordinateDefinition);
potentialMasterLJLS.addPotential(pLJLS, new IAtomType[]{sim.species.getLeafType(),sim.species.getLeafType()});
meterSolidLS.setPotentialMasterDADv2(potentialMasterLJLS, bpharmLJ);
}
for (int i=0; i<uFacCut.length; i++) {
uFacCutLS[i] = uFacCut[i];
}
for (int i=uFacCut.length; i<uFacCutLS.length; i++) {
uFacCutLS[i] = d.getValue(5*i)*numAtoms - uShort;
}
}
System.out.print("cutoffs: ");
if (nCutoffsLS>0) {
for (int i=0; i<nCutoffsLS; i++) {
System.out.print(" "+cutoffsLS[i]);
}
}
else {
for (int i=0; i<nCutoffs; i++) {
System.out.print(" "+cutoffs[i]);
}
}
System.out.println();
System.out.print("bPharm ");
if (nCutoffsLS>0) {
for (int i=0; i<nCutoffsLS; i++) {
System.out.print(" "+bpharm[i]);
}
}
else {
for (int i=0; i<nCutoffs; i++) {
System.out.print(" "+bpharm[i]);
}
}
System.out.println();
if (ss) {
System.out.print("bPharmLJ ");
if (nCutoffsLS>0) {
for (int i=0; i<nCutoffsLS; i++) {
System.out.print(" "+bpharmLJ[i]);
}
}
else {
for (int i=0; i<nCutoffs; i++) {
System.out.print(" "+bpharmLJ[i]);
}
}
System.out.println();
}
if (args.length == 0) {
// quick initialization
sim.initialize(numSteps/10);
}
else {
sim.initialize(numSteps/20 + 50*numAtoms + numAtoms*numAtoms*3);
}
int numBlocks = 100;
int interval = 2*numAtoms;
long blockSize = numSteps/(numBlocks*interval);
if (blockSize == 0) blockSize = 1;
System.out.println("block size "+blockSize+" interval "+interval);
final ValueCache energyFastCache = new ValueCache(meterEnergyShort, sim.integrator);
DataProcessorReweight puReweight = new DataProcessorReweight(temperature, energyFastCache, uFacCut, sim.box, cutoffs.length);
DataPumpListener pumpPU = new DataPumpListener(meterSolid, puReweight, interval);
sim.integrator.getEventManager().addListener(pumpPU);
final AccumulatorAverageCovariance avgSolid = new AccumulatorAverageCovariance(blockSize);
puReweight.setDataSink(avgSolid);
DataProcessorReweightRatio puReweightRatio = new DataProcessorReweightRatio(cutoffs.length);
avgSolid.setBlockDataSink(puReweightRatio);
AccumulatorAverageCovariance accPUBlocks = new AccumulatorAverageCovariance(1, true);
puReweightRatio.setDataSink(accPUBlocks);
AccumulatorAverageCovariance accPULSBlocks = null;
AccumulatorAverageCovariance accPULS = null;
if (nCutoffsLS>0) {
int intervalLS = 5*interval;
DataProcessorReweight puLSReweight = new DataProcessorReweight(temperature, energyFastCache, uFacCutLS, sim.box, nCutoffsLS);
DataPumpListener pumpPULS = new DataPumpListener(meterSolidLS, puLSReweight, intervalLS);
sim.integrator.getEventManager().addListener(pumpPULS);
blockSize = numSteps/(intervalLS*numBlocks);
accPULS = new AccumulatorAverageCovariance(blockSize);
puLSReweight.setDataSink(accPULS);
DataProcessorReweightRatio puLSReweightRatio = new DataProcessorReweightRatio(nCutoffsLS, nCutoffs-1);
accPULS.setBlockDataSink(puLSReweightRatio);
accPULSBlocks = new AccumulatorAverageCovariance(1, true);
puLSReweightRatio.setDataSink(accPULSBlocks);
}
final long startTime = System.currentTimeMillis();
sim.activityIntegrate.setMaxSteps(numSteps);
sim.getController().actionPerformed();
long endTime = System.currentTimeMillis();
System.out.println();
IData avgRawData = avgSolid.getData(avgSolid.AVERAGE);
IData errRawData = avgSolid.getData(avgSolid.ERROR);
IData corRawData = avgSolid.getData(avgSolid.BLOCK_CORRELATION);
int j = 6;
for (int i=1; i<cutoffs.length; i++) {
double avgW = avgRawData.getValue(j+5);
double errW = errRawData.getValue(j+5);
double corW = corRawData.getValue(j+5);
System.out.println(String.format("rc: %2d dbA: % 21.15e %10.4e % 5.3f % 6.4f", i, -Math.log(avgW)/numAtoms, errW/avgW/numAtoms, corW, errW/avgW));
j += 6;
}
System.out.println("\n");
if (nCutoffsLS>0) {
avgRawData = accPULS.getData(accPULS.AVERAGE);
errRawData = accPULS.getData(accPULS.ERROR);
corRawData = accPULS.getData(accPULS.BLOCK_CORRELATION);
j = 6;
for (int i=1; i<cutoffsLS.length; i++) {
double avgW = avgRawData.getValue(j+5);
double errW = errRawData.getValue(j+5);
double corW = corRawData.getValue(j+5);
System.out.println(String.format("rcLS: %2d dbA: % 21.15e %10.4e % 5.3f % 6.4f", i, -Math.log(avgW)/numAtoms, errW/avgW/numAtoms, corW, errW/avgW));
j += 6;
}
System.out.println("\n");
}
IData avgData = accPUBlocks.getData(avgSolid.AVERAGE);
IData errData = accPUBlocks.getData(avgSolid.ERROR);
IData corData = accPUBlocks.getData(avgSolid.BLOCK_CORRELATION);
IData covData = accPUBlocks.getData(avgSolid.BLOCK_COVARIANCE);
int n = avgData.getLength();
j = 0;
for (int i=0; i<cutoffs.length; i++) {
double avgU = avgData.getValue(j+0);
double errU = errData.getValue(j+0);
double corU = corData.getValue(j+0);
double avgP = avgData.getValue(j+1);
double errP = errData.getValue(j+1);
double corP = corData.getValue(j+1);
double avgBUc = avgData.getValue(j+2);
double errBUc = errData.getValue(j+2);
double corBUc = corData.getValue(j+2);
double avgZc = avgData.getValue(j+3);
double errZc = errData.getValue(j+3);
double corZc = corData.getValue(j+3);
// this is dbAc/drho at constant Y (for LJ)
double avgDADv2 = avgData.getValue(j+4);
double errDADv2 = errData.getValue(j+4);
double corDADv2 = corData.getValue(j+4);
double DADACor = covData.getValue(2*n+4)/Math.sqrt(covData.getValue(2*n+2)*covData.getValue(4*n+4));
double ZcUcCor = covData.getValue(3*n+4)/Math.sqrt(covData.getValue(3*n+3)*covData.getValue(4*n+4));
double facDADY = 4*density*density*density*density/temperature;
System.out.print(String.format("rc: %2d DADY: % 21.15e %10.4e % 5.3f\n", i, -facDADY*avgBUc, facDADY*errBUc, corBUc));
System.out.print(String.format("rc: %2d DADv2: % 21.15e %10.4e % 5.3f % 8.6f\n", i, avgDADv2, errDADv2, corDADv2, DADACor));
System.out.print(String.format("rc: %2d Zc: % 21.15e %10.4e % 5.3f\n", i, avgZc, errZc, corZc));
System.out.print(String.format("rc: %2d bUc: % 21.15e %10.4e % 5.3f % 8.6f\n", i, avgBUc, errBUc, corBUc, ZcUcCor));
double PUCor = covData.getValue(1*n+0)/Math.sqrt(covData.getValue(1*n+1)*covData.getValue(0*n+0));
System.out.print(String.format("rc: %2d Uraw: % 21.15e %10.4e % 5.3f\n", i, avgU, errU, corU));
System.out.print(String.format("rc: %2d Praw: % 21.15e %10.4e % 5.3f % 8.6f\n", i, avgP, errP, corP, PUCor));
System.out.println();
j+=5;
}
if (nCutoffsLS > 0) {
avgData = accPULSBlocks.getData(accPULSBlocks.AVERAGE);
errData = accPULSBlocks.getData(accPULSBlocks.ERROR);
covData = accPULSBlocks.getData(accPULSBlocks.BLOCK_COVARIANCE);
corData = accPULSBlocks.getData(accPULSBlocks.BLOCK_CORRELATION);
n = avgData.getLength();
j = 0;
for (int i=0; i<cutoffsLS.length; i++) {
if (i<=cutoffs.length-1) {
j+=5;
continue;
}
double avgU = avgData.getValue(j+0);
double errU = errData.getValue(j+0);
double corU = corData.getValue(j+0);
double avgP = avgData.getValue(j+1);
double errP = errData.getValue(j+1);
double corP = corData.getValue(j+1);
double avgBUc = avgData.getValue(j+2);
double errBUc = errData.getValue(j+2);
double corBUc = corData.getValue(j+2);
double avgZc = avgData.getValue(j+3);
double errZc = errData.getValue(j+3);
double corZc = corData.getValue(j+3);
// this is dbAc/drho at constant Y (for LJ)
double avgDADv2 = avgData.getValue(j+4);
double errDADv2 = errData.getValue(j+4);
double corDADv2 = corData.getValue(j+4);
double DADACor = covData.getValue(2*n+4)/Math.sqrt(covData.getValue(2*n+2)*covData.getValue(4*n+4));
double ZcUcCor = covData.getValue(3*n+4)/Math.sqrt(covData.getValue(3*n+3)*covData.getValue(4*n+4));
double facDADY = 4*density*density*density*density/temperature;
System.out.print(String.format("rcLS: %2d DADY: % 21.15e %10.4e % 5.3f\n", i, -facDADY*avgBUc, facDADY*errBUc, corBUc));
System.out.print(String.format("rcLS: %2d DADv2: % 21.15e %10.4e % 5.3f % 8.6f\n", i, avgDADv2, errDADv2, corDADv2, DADACor));
System.out.print(String.format("rcLS: %2d Zc: % 21.15e %10.4e % 5.3f\n", i, avgZc, errZc, corZc));
System.out.print(String.format("rcLS: %2d bUc: % 21.15e %10.4e % 5.3f % 8.6f\n", i, avgBUc, errBUc, corBUc, ZcUcCor));
double PUCor = covData.getValue(1*n+0)/Math.sqrt(covData.getValue(1*n+1)*covData.getValue(0*n+0));
System.out.print(String.format("rcLS: %2d Uraw: % 21.15e %10.4e % 5.3f\n", i, avgU, errU, corU));
System.out.print(String.format("rcLS: %2d Praw: % 21.15e %10.4e % 5.3f % 8.6f\n", i, avgP, errP, corP, PUCor));
System.out.println();
j+=5;
}
}
System.out.println("time: " + (endTime - startTime)/1000.0);
}
public IntegratorMC integrator;
public ActivityIntegrate activityIntegrate;
public IBox box;
public Boundary boundary;
public int[] nCells;
public Basis basis;
public Primitive primitive;
public MCMoveAtomCoupled atomMove;
public PotentialMasterList potentialMaster;
public final CoordinateDefinitionLeaf coordinateDefinition;
public Potential2SoftSpherical potential;
public SpeciesSpheresMono species;
/**
* Inner class for parameters understood by the HSMD3D constructor
*/
public static class SimOverlapParam extends ParameterBase {
public int numAtoms = 256;
public double density = 1.28;
public long numSteps = 1000000;
public double temperature = 0.1;
public double rc = 2.5;
public double rcMax0 = 100;
public double[] bpharm = new double[0];
public double[] bpharmLJ = new double[0];
public boolean ss = false;
}
}
|
package org.bunkr.gui;
import java.io.IOException;
import java.net.*;
/**
* Creator: benmeier
* Created At: 2015-12-31
*/
public class URLRequestBlocker
{
final Proxy http_proxy;
final Proxy https_proxy;
public URLRequestBlocker()
{
http_proxy = build_proxy(System.getenv("http_proxy"));
https_proxy = build_proxy(System.getenv("https_proxy"));
}
public void install()
{
URL.setURLStreamHandlerFactory(this::getStreamHandler);
}
public URLStreamHandler getStreamHandler(String protocol)
{
if (protocol.equals("jar") || protocol.equals("file")) return null;
if (protocol.equals("http")) return new HTTPHandler();
if (protocol.equals("https")) return new HTTPSHandler();
return new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) throws IOException
{
throw new IOException(String.format("Outgoing request to %s blocked", u));
}
};
}
private Proxy build_proxy(String input)
{
if (input == null) return Proxy.NO_PROXY;
URI u = URI.create(input);
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(u.getHost(), u.getPort()));
}
private class HTTPHandler extends URLStreamHandler
{
@Override
protected int getDefaultPort()
{
return 80;
}
@Override
protected URLConnection openConnection(URL url) throws IOException
{
return this.openConnection(url, http_proxy);
}
@Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException
{
throw new IOException(String.format("Outgoing request to %s blocked", url));
}
}
private class HTTPSHandler extends URLStreamHandler
{
@Override
protected int getDefaultPort()
{
return 80;
}
@Override
protected URLConnection openConnection(URL url) throws IOException
{
return this.openConnection(url, https_proxy);
}
@Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException
{
throw new IOException(String.format("Outgoing request to %s blocked", url));
}
}
}
|
package pt.webdetails.cdb.api;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.platform.api.engine.IParameterProvider;
import org.pentaho.platform.api.engine.IPluginManager;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.web.http.api.resources.PluginResource;
import pt.webdetails.cdb.CdbEngine;
import pt.webdetails.cdb.InterPluginBroker;
import pt.webdetails.cdb.exporters.ExporterEngine;
import pt.webdetails.cdb.util.JsonUtils;
import pt.webdetails.cdb.utils.RestApiUtils;
import pt.webdetails.cpf.InvalidOperationException;
import pt.webdetails.cpf.persistence.PersistenceEngine;
import pt.webdetails.cpf.utils.CharsetHelper;
import pt.webdetails.cpf.utils.MimeTypes;
import pt.webdetails.cpf.utils.PluginIOUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Path( "/cdb/api" )
public class CdbApi {
static Log logger = LogFactory.getLog( CdbApi.class );
public static final String PLUGIN_NAME = "cdb";
@GET
@Path( "/ping" )
public String ping() {
logger.info( "pong" );
return "pong";
}
@GET
@Path( "/home" )
@Produces( MediaType.TEXT_HTML )
public String home( @Context HttpServletRequest request, @Context HttpServletResponse response,
@Context HttpHeaders headers ) throws IOException {
CdbEngine.getEnv(); // TODO: FOR REMOVE WHEN FOUND A WAY TO INSTANTIATE IN LYFECYCLE GIVES AN ERROR
//IParameterProvider requestParams = getRequestParameters();
// ServletRequest wrapper = getRequest();
Map<String, Map<String, Object>> params = RestApiUtils.buildBloatedMap( request, response, headers );
Map<String, Object> requestMap = new HashMap<String, Object>();
Map<String, Object> requestParams = params.get( "request" );
requestMap.put( "solution", "system" );
requestMap.put( "path", "cdb/presentation" );
requestMap.put( "file", "cdb.wcdf" );
requestMap.put( "absolute", "false" );
requestMap.put( "inferScheme", "false" );
for ( String name : requestParams.keySet() ) {
requestMap.put( name, requestParams.get( name ) );
}
//add request parameters
//PluginUtils.copyParametersFromProvider(params, WrapperUtils.wrapParamProvider(requestParams));
if ( requestMap.get( "mode" ) != null && requestMap.get( "mode" ).equals( "edit" ) ) {
// Send this to CDE
redirectToCdeEditor( response, requestMap );
return "";
}
try {
response.setContentType( MimeTypes.HTML );
InterPluginBroker.run( requestMap, response.getOutputStream() );
} catch ( Exception e ) {
return e.toString(); //To change body of catch statement use File | Settings | File Templates.
}
/*InterPluginCall pluginCall = new InterPluginCall(InterPluginCall.CDE, "Render", params);
pluginCall.setResponse(response);
//pluginCall.setOutputStream(out);
pluginCall.run();*/
return "";
}
@GET
@Path( "/storage" )
@Produces( "text/javascript" )
public void storage( @Context HttpServletRequest request, @Context HttpServletResponse response,
@Context HttpHeaders headers ) throws IOException, InvalidOperationException {
CdbEngine.getEnv(); // TODO: FOR REMOVE WHEN FOUND A WAY TO INSTANTIATE IN LYFECYCLE GIVES AN ERROR
Map<String, Map<String, Object>> bloatedMap = RestApiUtils.buildBloatedMap( request, response, headers );
try {
PersistenceEngine engine = PersistenceEngine.getInstance();
String result =
engine.process( RestApiUtils.getRequestParameters( bloatedMap ), PentahoSessionHolder.getSession() );
PluginIOUtils.writeOutAndFlush( response.getOutputStream(), result );
} catch ( Exception ex ) {
logger.error( ex.toString() );
JsonUtils.buildJsonResult( response.getOutputStream(), false,
"Exception found: " + ex.getClass().getName() + " - " + ex.getMessage() );
}
}
@GET
@Path( "/doQuery" )
@Produces( { "text/csv", "text/javascript" } )
public void doQuery( @Context HttpServletRequest request, @Context HttpServletResponse response,
@Context HttpHeaders headers ) throws IOException {
CdbEngine.getEnv(); // TODO: FOR REMOVE WHEN FOUND A WAY TO INSTANTIATE IN LYFECYCLE GIVES AN ERROR
Map<String, Map<String, Object>> bloatedMap = RestApiUtils.buildBloatedMap( request, response, headers );
IParameterProvider requestParams = RestApiUtils.getRequestParameters( bloatedMap );
String group = requestParams.getStringParameter( "group", "" );
String id = requestParams.getStringParameter( "id", "" );
String outputType = requestParams.getStringParameter( "outputType", "json" );
try {
String result = ExporterEngine.exportCda( group, id, outputType );
PluginIOUtils.writeOutAndFlush( response.getOutputStream(), result );
} catch ( Exception ex ) {
logger.error( ex.toString() );
JsonUtils.buildJsonResult( response.getOutputStream(), false,
"Exception found: " + ex.getClass().getName() + " - " + ex.getMessage() );
}
}
private void redirectToCdeEditor( HttpServletResponse response,
Map<String, Object> params ) throws IOException {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append( "../../pentaho-cdf-dd/api/renderer/edit" );
if ( params.size() > 0 ) {
urlBuilder.append( "?" );
}
List<String> paramArray = new ArrayList<String>();
for ( String key : params.keySet() ) {
Object value = params.get( key );
if ( value instanceof String ) {
paramArray.add( key + "=" + URLEncoder.encode( (String) value, CharsetHelper.getEncoding() ) );
}
}
urlBuilder.append( StringUtils.join( paramArray, "&" ) );
if ( response == null ) {
logger.error( "response not found" );
return;
}
try {
response.sendRedirect( urlBuilder.toString() );
} catch ( IOException e ) {
logger.error( "could not redirect", e );
}
}
@GET
@Path( "/{path: [^?]+ }" )
@Produces( { MediaType.WILDCARD } )
public Response getSystemResource( @PathParam( "path" ) String path, @Context HttpServletResponse response )
throws IOException {
String pluginId = CdbEngine.getInstance().getEnvironment().getPluginId();
IPluginManager pluginManager = PentahoSystem.get( IPluginManager.class );
if ( !StringUtils.isEmpty( path ) && pluginManager.isPublic( pluginId, path ) ) {
Response readFileResponse = new PluginResource( response ).readFile( pluginId, path );
if ( readFileResponse.getStatus() != Response.Status.NOT_FOUND.getStatusCode() ) {
return readFileResponse;
}
}
return Response.status( Response.Status.NOT_FOUND ).build();
}
}
|
package org.freeflow.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.freeflow.layouts.AbstractLayout;
import org.freeflow.layouts.animations.DefaultLayoutAnimator;
import org.freeflow.layouts.animations.LayoutAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
public class Container extends AbsLayoutContainer {
private static final String TAG = "Container";
// ViewPool class
protected ViewPool viewpool;
// Not used yet, but we'll probably need to
// prevent layout in <code>layout()</code> method
private boolean preventLayout = false;
protected BaseSectionedAdapter itemAdapter;
protected AbstractLayout layout;
public int viewPortX = 0;
public int viewPortY = 0;
protected View headerView = null;
private VelocityTracker mVelocityTracker = null;
private float deltaX = -1f;
private float deltaY = -1f;
private int maxFlingVelocity;
private int touchSlop;
private LayoutParams params = new LayoutParams(0, 0);
private LayoutAnimator layoutAnimator = new DefaultLayoutAnimator();
private ItemProxy beginTouchAt;
private boolean markLayoutDirty = false;
private boolean markAdapterDirty = false;
private AbstractLayout oldLayout;
public Container(Context context) {
super(context);
}
public Container(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Container(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init(Context context) {
// usedViews = new HashMap<Object, ItemProxy>();
// usedHeaderViews = new HashMap<Object, ItemProxy>();
viewpool = new ViewPool();
frames = new HashMap<Object, ItemProxy>();
maxFlingVelocity = ViewConfiguration.get(context).getScaledMaximumFlingVelocity();
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int beforeWidth = getWidth();
int beforeHeight = getHeight();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int afterWidth = MeasureSpec.getSize(widthMeasureSpec);
int afterHeight = MeasureSpec.getSize(heightMeasureSpec);
if(beforeWidth != afterWidth || beforeHeight != afterHeight || markLayoutDirty){
computeLayout(afterWidth, afterHeight);
}
}
public void computeLayout(int w, int h) {
Log.d(TAG, "=== Computing layout ==== ");
if (layout != null) {
layout.setDimensions(w, h);
if (this.itemAdapter != null)
layout.setItems(itemAdapter);
computeViewPort(layout);
HashMap<? extends Object, ItemProxy> oldFrames = frames;
if (markLayoutDirty) {
markLayoutDirty = false;
if (mOnLayoutChangeListener != null) {
mOnLayoutChangeListener.onLayoutChanging(oldLayout, layout);
}
}
// Create a copy of the incoming values because the source
// Layout
// may change the map inside its own class
frames = new HashMap<Object, ItemProxy>(layout.getItemProxies(viewPortX, viewPortY));
animateChanges(getViewChanges(oldFrames, frames));
// for (ItemProxy frameDesc : changeSet.added) {
// addAndMeasureViewIfNeeded(frameDesc);
}
}
private void addAndMeasureViewIfNeeded(ItemProxy frameDesc) {
View view;
if (frameDesc.view == null) {
View convertView = viewpool.getViewFromPool(itemAdapter.getViewType(frameDesc));
if (frameDesc.isHeader) {
view = itemAdapter.getHeaderViewForSection(frameDesc.itemSection, convertView, this);
} else {
view = itemAdapter.getViewForSection(frameDesc.itemSection, frameDesc.itemIndex, convertView, this);
}
if (view instanceof Container)
throw new IllegalStateException("A container cannot be a direct child view to a container");
frameDesc.view = view;
prepareViewForAddition(view);
addViewInLayout(view, -1, params);
}
view = frameDesc.view;
int widthSpec = MeasureSpec.makeMeasureSpec(frameDesc.frame.width, MeasureSpec.EXACTLY);
int heightSpec = MeasureSpec.makeMeasureSpec(frameDesc.frame.height, MeasureSpec.EXACTLY);
view.measure(widthSpec, heightSpec);
if (view instanceof StateListener)
((StateListener) view).ReportCurrentState(frameDesc.state);
}
private void prepareViewForAddition(View view) {
// view.setOnTouchListener(this);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d(TAG, "== onLayout ==");
if (layout == null || frames == null) {
return;
}
// animateChanges();
}
private void doLayout(ItemProxy proxy) {
View view = proxy.view;
Frame frame = proxy.frame;
view.layout(frame.left - viewPortX, frame.top - viewPortY, frame.left + frame.width - viewPortX, frame.top
+ frame.height - viewPortY);
if (view instanceof StateListener)
((StateListener) view).ReportCurrentState(proxy.state);
}
public void setLayout(AbstractLayout lc) {
if (lc == layout) {
return;
}
oldLayout = layout;
layout = lc;
markLayoutDirty = true;
Log.d(TAG, "=== setting layout ===");
requestLayout();
}
public AbstractLayout getLayout() {
return layout;
}
private void computeViewPort(AbstractLayout newLayout) {
if (layout == null || frames == null || frames.size() == 0) {
viewPortX = 0;
viewPortY = 0;
return;
}
Object data = null;
int lowestSection = 99999;
int lowestPosition = 99999;
for (ItemProxy fd : frames.values()) {
if (fd.itemSection < lowestSection || (fd.itemSection == lowestSection && fd.itemIndex < lowestPosition)) {
data = fd.data;
lowestSection = fd.itemSection;
lowestPosition = fd.itemIndex;
}
}
ItemProxy proxy = newLayout.getItemProxyForItem(data);
if (proxy == null) {
viewPortX = 0;
viewPortY = 0;
return;
}
Frame vpFrame = proxy.frame;
viewPortX = vpFrame.left;
viewPortY = vpFrame.top;
if (viewPortX > newLayout.getContentWidth())
viewPortX = newLayout.getContentWidth();
if (viewPortY > newLayout.getContentHeight())
viewPortY = newLayout.getContentHeight();
}
/**
* Returns the actual frame for a view as its on stage. The ItemProxy's
* frame object always represents the position it wants to be in but actual
* frame may be different based on animation etc.
*
* @param proxy
* The proxy to get the <code>Frame</code> for
* @return The Frame for the proxy or null if that view doesn't exist
*/
public Frame getActualFrame(final ItemProxy proxy) {
View v = proxy.view;
if (v == null) {
return null;
}
Frame of = new Frame();
of.left = (int) (v.getLeft() + v.getTranslationX());
of.top = (int) (v.getTop() + v.getTranslationY());
of.width = v.getWidth();
of.height = v.getHeight();
return of;
}
/**
* TODO:::: This should be renamed to layoutInvalidated, since the layout
* isn't changed
*/
public void layoutChanged() {
requestLayout();
}
private void animateChanges(LayoutChangeSet changeSet) {
layoutAnimator.cancel();
Log.d(TAG, "changeSet is null: " + (changeSet == null));
for (ItemProxy proxy : changeSet.getAdded()) {
addAndMeasureViewIfNeeded(proxy);
doLayout(proxy);
}
Log.d(TAG, "== animating changes: " + changeSet.toString());
// preventLayout = true;
layoutAnimator.animateChanges(changeSet, this);
}
public void onLayoutChangeAnimationsCompleted(LayoutAnimator anim) {
// preventLayout = false;
Log.d(TAG, "=== layout changes complete");
for (ItemProxy proxy : anim.getChangeSet().getRemoved()) {
View v = proxy.view;
removeViewInLayout(v);
returnItemToPoolIfNeeded(proxy);
}
// changeSet = null;
}
public LayoutChangeSet getViewChanges(HashMap<? extends Object, ItemProxy> oldFrames,
HashMap<? extends Object, ItemProxy> newFrames) {
// cleanupViews();
LayoutChangeSet change = new LayoutChangeSet();
if (oldFrames == null) {
markAdapterDirty = false;
Log.d(TAG, "old frames is null");
for (ItemProxy proxy : newFrames.values()) {
change.addToAdded(proxy);
}
return change;
}
if (markAdapterDirty) {
Log.d(TAG, "old frames is null");
markAdapterDirty = false;
for (ItemProxy proxy : newFrames.values()) {
change.addToAdded(proxy);
}
for (ItemProxy proxy : oldFrames.values()) {
change.addToDeleted(proxy);
}
return change;
}
Iterator<?> it = newFrames.entrySet().iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
ItemProxy proxy = (ItemProxy) m.getValue();
if (oldFrames.get(m.getKey()) != null) {
ItemProxy old = oldFrames.remove(m.getKey());
proxy.view = old.view;
change.addToMoved(proxy, getActualFrame(proxy));
} else {
change.addToAdded(proxy);
}
}
for (ItemProxy proxy : oldFrames.values()) {
change.addToDeleted(proxy);
}
frames = newFrames;
return change;
}
@Override
public void requestLayout() {
Log.d(TAG, "== requesting layout ===");
if (!preventLayout) {
super.requestLayout();
}
}
/**
* Sets the adapter for the this CollectionView.All view pools will be
* cleared at this point and all views on the stage will be cleared
*
* @param adapter
* The {@link BaseSectionedAdapter} that will populate this
* Collection
*/
public void setAdapter(BaseSectionedAdapter adapter) {
Log.d(TAG, "setting adapter");
markLayoutDirty = true;
markAdapterDirty = true;
this.itemAdapter = adapter;
viewpool.initializeViewPool(adapter.getViewTypes());
requestLayout();
}
public AbstractLayout getLayoutController() {
return layout;
}
/**
* Indicates that we are not in the middle of a touch gesture
*/
static final int TOUCH_MODE_REST = -1;
/**
* Indicates we just received the touch event and we are waiting to see if
* the it is a tap or a scroll gesture.
*/
static final int TOUCH_MODE_DOWN = 0;
/**
* Indicates the touch has been recognized as a tap and we are now waiting
* to see if the touch is a longpress
*/
static final int TOUCH_MODE_TAP = 1;
/**
* Indicates we have waited for everything we can wait for, but the user's
* finger is still down
*/
static final int TOUCH_MODE_DONE_WAITING = 2;
/**
* Indicates the touch gesture is a scroll
*/
static final int TOUCH_MODE_SCROLL = 3;
/**
* Indicates the view is in the process of being flung
*/
static final int TOUCH_MODE_FLING = 4;
/**
* Indicates the touch gesture is an overscroll - a scroll beyond the
* beginning or end.
*/
static final int TOUCH_MODE_OVERSCROLL = 5;
/**
* Indicates the view is being flung outside of normal content bounds and
* will spring back.
*/
static final int TOUCH_MODE_OVERFLING = 6;
/**
* One of TOUCH_MODE_REST, TOUCH_MODE_DOWN, TOUCH_MODE_TAP,
* TOUCH_MODE_SCROLL, or TOUCH_MODE_DONE_WAITING
*/
int mTouchMode = TOUCH_MODE_REST;
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
if (layout == null)
return false;
if (!layout.horizontalDragEnabled() && !layout.verticalDragEnabled())
return false;
if (mVelocityTracker == null)
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(event);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
beginTouchAt = layout.getItemAt(viewPortX + event.getX(), viewPortY + event.getY());
deltaX = event.getX();
deltaY = event.getY();
mTouchMode = TOUCH_MODE_DOWN;
return true;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
float xDiff = event.getX() - deltaX;
float yDiff = event.getY() - deltaY;
double distance = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
if (mTouchMode == TOUCH_MODE_DOWN) {
if (distance > touchSlop) {
mTouchMode = TOUCH_MODE_SCROLL;
}
}
if (mTouchMode == TOUCH_MODE_SCROLL) {
moveScreen(event.getX() - deltaX, event.getY() - deltaY);
deltaX = event.getX();
deltaY = event.getY();
}
return true;
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
mTouchMode = TOUCH_MODE_REST;
mVelocityTracker.recycle();
mVelocityTracker = null;
// requestLayout();
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Log.d(TAG, "Action Up");
if (mTouchMode == TOUCH_MODE_SCROLL) {
Log.d(TAG, "Scroll....");
mVelocityTracker.computeCurrentVelocity(maxFlingVelocity);
// frames = layoutController.getFrameDescriptors(viewPortX,
// viewPortY);
if (Math.abs(mVelocityTracker.getXVelocity()) > 100) {
final float velocityX = mVelocityTracker.getXVelocity();
final float velocityY = mVelocityTracker.getYVelocity();
ValueAnimator animator = ValueAnimator.ofFloat(1, 0);
animator.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int translateX = (int) ((1 - animation.getAnimatedFraction()) * velocityX / 350);
int translateY = (int) ((1 - animation.getAnimatedFraction()) * velocityY / 350);
moveScreen(translateX, translateY);
}
});
animator.setDuration(500);
animator.start();
}
mTouchMode = TOUCH_MODE_REST;
Log.d(TAG, "Setting to rest");
}
else {
Log.d(TAG, "Select");
selectedItemProxy = beginTouchAt;
if (mOnItemSelectedListener != null) {
mOnItemSelectedListener.onItemSelected(this, selectedItemProxy);
}
mTouchMode = TOUCH_MODE_REST;
}
return true;
}
return false;
}
private void moveScreen(float movementX, float movementY) {
if (layout.horizontalDragEnabled()) {
viewPortX = (int) (viewPortX - movementX);
} else {
movementX = 0;
}
if (layout.verticalDragEnabled()) {
viewPortY = (int) (viewPortY - movementY);
} else {
movementY = 0;
}
if (viewPortX < 0)
viewPortX = 0;
else if (viewPortX > layout.getContentWidth())
viewPortX = layout.getContentWidth();
if (viewPortY < 0)
viewPortY = 0;
else if (viewPortY > layout.getContentHeight())
viewPortY = layout.getContentHeight();
HashMap<? extends Object, ItemProxy> oldFrames = frames;
frames = new HashMap<Object, ItemProxy>(layout.getItemProxies(viewPortX, viewPortY));
LayoutChangeSet changeSet = getViewChanges(oldFrames, frames);
for (ItemProxy proxy : changeSet.added) {
addAndMeasureViewIfNeeded(proxy);
doLayout(proxy);
}
for (Pair<ItemProxy, Frame> proxyPair : changeSet.moved) {
doLayout(proxyPair.first);
}
for (ItemProxy proxy : changeSet.removed) {
removeViewInLayout(proxy.view);
returnItemToPoolIfNeeded(proxy);
}
}
protected void returnItemToPoolIfNeeded(ItemProxy proxy) {
View v = proxy.view;
v.setTranslationX(0);
v.setTranslationY(0);
v.setRotation(0);
v.setScaleX(1f);
v.setScaleY(1f);
v.setAlpha(1);
viewpool.returnViewToPool(v);
}
public BaseSectionedAdapter getAdapter() {
return itemAdapter;
}
public void setLayoutAnimator(LayoutAnimator anim) {
layoutAnimator = anim;
}
public LayoutAnimator getLayoutAnimator() {
return layoutAnimator;
}
public HashMap<? extends Object, ItemProxy> getFrames() {
return frames;
}
public void clearFrames() {
removeAllViews();
frames = null;
}
protected OnLayoutChangeListener mOnLayoutChangeListener;
/**
* Interface that all listeners interested in layout change events must
* implement
*
*/
public interface OnLayoutChangeListener {
/**
* Called when the layout is about to change. Measurements based on the
* current data provider and current size have been completed.
*
* @param oldLayout
* @param newLayout
*/
public void onLayoutChanging(AbstractLayout oldLayout, AbstractLayout newLayout);
}
}
|
package org.freeflow.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.freeflow.layouts.AbstractLayout;
import org.freeflow.layouts.animations.DefaultLayoutAnimator;
import org.freeflow.layouts.animations.LayoutAnimator;
import org.freeflow.utils.ViewUtils;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.VpnService;
import android.support.v4.util.SimpleArrayMap;
import android.text.GetChars;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Pair;
import android.view.ActionMode;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.HapticFeedbackConstants;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Checkable;
import android.widget.EdgeEffect;
import android.widget.OverScroller;
public class Container extends AbsLayoutContainer {
private static final String TAG = "Container";
// ViewPool class
protected ViewPool viewpool;
// Not used yet, but we'll probably need to
// prevent layout in <code>layout()</code> method
private boolean preventLayout = false;
protected BaseSectionedAdapter itemAdapter;
protected AbstractLayout layout;
public int viewPortX = 0;
public int viewPortY = 0;
protected int scrollableWidth;
protected int scrollableHeight;
protected View headerView = null;
private VelocityTracker mVelocityTracker = null;
private float deltaX = -1f;
private float deltaY = -1f;
private int scrollDeltaX = 0;
private int scrollDeltaY = 0;
private int maxFlingVelocity;
private int touchSlop;
private Runnable mTouchModeReset;
private Runnable mPerformClick;
private Runnable mPendingCheckForTap;
private Runnable mPendingCheckForLongPress;
private OverScroller scroller;
private boolean flingStarted = false;
private EdgeEffect mLeftEdge, mRightEdge, mTopEdge, mBottomEdge;
private float pullPastSlack = 300f;
private ArrayList<OnScrollListener> scrollListeners = new ArrayList<Container.OnScrollListener>();
// This flag controls whether onTap/onLongPress/onTouch trigger
// the ActionMode
// private boolean mDataChanged = false;
private ContextMenuInfo mContextMenuInfo = null;
private SimpleArrayMap<IndexPath, Boolean> mCheckStates = null;
ActionMode mChoiceActionMode;
MultiChoiceModeWrapper mMultiChoiceModeCallback;
/**
* Normal list that does not indicate choices
*/
public static final int CHOICE_MODE_NONE = 0;
/**
* The list allows up to one choice
*/
public static final int CHOICE_MODE_SINGLE = 1;
/**
* The list allows multiple choices
*/
public static final int CHOICE_MODE_MULTIPLE = 2;
/**
* The list allows multiple choices in a modal selection mode
*/
public static final int CHOICE_MODE_MULTIPLE_MODAL = 3;
int mChoiceMode = CHOICE_MODE_NONE;
private LayoutParams params = new LayoutParams(0, 0);
private LayoutAnimator layoutAnimator = new DefaultLayoutAnimator();
private ItemProxy beginTouchAt;
private boolean markLayoutDirty = false;
private boolean markAdapterDirty = false;
private AbstractLayout oldLayout;
public Container(Context context) {
super(context);
}
public Container(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Container(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init(Context context) {
// usedViews = new HashMap<Object, ItemProxy>();
// usedHeaderViews = new HashMap<Object, ItemProxy>();
setWillNotDraw(false);
viewpool = new ViewPool();
frames = new HashMap<Object, ItemProxy>();
maxFlingVelocity = ViewConfiguration.get(context).getScaledMaximumFlingVelocity();
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
// TODO: create Scroller vars
scroller = new OverScroller(context);
mLeftEdge = new EdgeEffect(context);
mRightEdge = new EdgeEffect(context);
mTopEdge = new EdgeEffect(context);
mBottomEdge = new EdgeEffect(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int beforeWidth = getWidth();
int beforeHeight = getHeight();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int afterWidth = MeasureSpec.getSize(widthMeasureSpec);
int afterHeight = MeasureSpec.getSize(heightMeasureSpec);
if (beforeWidth != afterWidth || beforeHeight != afterHeight || markLayoutDirty) {
computeLayout(afterWidth, afterHeight);
}
}
public void computeLayout(int w, int h) {
Log.d(TAG, "=== Computing layout ==== ");
if (layout != null) {
layout.setDimensions(w, h);
if (this.itemAdapter != null)
layout.setItems(itemAdapter);
computeViewPort(layout);
HashMap<? extends Object, ItemProxy> oldFrames = frames;
if (markLayoutDirty) {
markLayoutDirty = false;
}
// Create a copy of the incoming values because the source
// Layout
// may change the map inside its own class
frames = new HashMap<Object, ItemProxy>(layout.getItemProxies(viewPortX, viewPortY));
dispatchLayoutComputed();
animateChanges(getViewChanges(oldFrames, frames));
// for (ItemProxy frameDesc : changeSet.added) {
// addAndMeasureViewIfNeeded(frameDesc);
}
}
private void addAndMeasureViewIfNeeded(ItemProxy frameDesc) {
View view;
if (frameDesc.view == null) {
View convertView = viewpool.getViewFromPool(itemAdapter.getViewType(frameDesc));
if (frameDesc.isHeader) {
view = itemAdapter.getHeaderViewForSection(frameDesc.itemSection, convertView, this);
} else {
view = itemAdapter.getViewForSection(frameDesc.itemSection, frameDesc.itemIndex, convertView, this);
}
if (view instanceof Container)
throw new IllegalStateException("A container cannot be a direct child view to a container");
frameDesc.view = view;
prepareViewForAddition(view, frameDesc);
addView(view, getChildCount(), params);
}
view = frameDesc.view;
int widthSpec = MeasureSpec.makeMeasureSpec(frameDesc.frame.width(), MeasureSpec.EXACTLY);
int heightSpec = MeasureSpec.makeMeasureSpec(frameDesc.frame.height(), MeasureSpec.EXACTLY);
view.measure(widthSpec, heightSpec);
if (view instanceof StateListener)
((StateListener) view).ReportCurrentState(frameDesc.state);
}
private void prepareViewForAddition(View view, ItemProxy proxy) {
if (view instanceof Checkable) {
((Checkable) view).setChecked(isChecked(proxy.itemSection, proxy.itemIndex));
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// Log.d(TAG, "== onLayout ==");
// mDataChanged = false;
dispatchLayoutComplete();
}
private void doLayout(ItemProxy proxy) {
View view = proxy.view;
Rect frame = proxy.frame;
view.layout(frame.left - viewPortX, frame.top - viewPortY, frame.right - viewPortX, frame.bottom - viewPortY);
if (view instanceof StateListener)
((StateListener) view).ReportCurrentState(proxy.state);
}
public void setLayout(AbstractLayout lc) {
if (lc == layout) {
return;
}
oldLayout = layout;
layout = lc;
dispatchLayoutChanging(oldLayout, lc);
dispatchDataChanged();
markLayoutDirty = true;
viewPortX = 0;
viewPortY = 0;
Log.d(TAG, "=== setting layout ===");
requestLayout();
}
public AbstractLayout getLayout() {
return layout;
}
private void computeViewPort(AbstractLayout newLayout) {
if (layout == null || frames == null || frames.size() == 0) {
viewPortX = 0;
viewPortY = 0;
return;
}
Object data = null;
int lowestSection = 99999;
int lowestPosition = 99999;
for (ItemProxy fd : frames.values()) {
if (fd.itemSection < lowestSection || (fd.itemSection == lowestSection && fd.itemIndex < lowestPosition)) {
data = fd.data;
lowestSection = fd.itemSection;
lowestPosition = fd.itemIndex;
}
}
ItemProxy proxy = newLayout.getItemProxyForItem(data);
if (proxy == null) {
viewPortX = 0;
viewPortY = 0;
return;
}
Rect vpFrame = proxy.frame;
viewPortX = vpFrame.left;
viewPortY = vpFrame.top;
scrollableWidth = layout.getContentWidth() - getWidth();
scrollableHeight = layout.getContentHeight() - getHeight();
if (viewPortX > scrollableWidth)
viewPortX = scrollableWidth;
if (viewPortY > scrollableHeight)
viewPortY = scrollableHeight;
}
/**
* Returns the actual frame for a view as its on stage. The ItemProxy's
* frame object always represents the position it wants to be in but actual
* frame may be different based on animation etc.
*
* @param proxy
* The proxy to get the <code>Frame</code> for
* @return The Frame for the proxy or null if that view doesn't exist
*/
public Rect getActualFrame(final ItemProxy proxy) {
View v = proxy.view;
if (v == null) {
return null;
}
Rect of = new Rect();
of.left = (int) (v.getLeft() + v.getTranslationX());
of.top = (int) (v.getTop() + v.getTranslationY());
of.right = (int) (v.getRight() + v.getTranslationX());
of.bottom = (int) (v.getBottom() + v.getTranslationY());
return of;
}
/**
* TODO:::: This should be renamed to layoutInvalidated, since the layout
* isn't changed
*/
public void layoutChanged() {
Log.d(TAG, "== layoutChanged");
markLayoutDirty = true;
dispatchDataChanged();
requestLayout();
}
protected boolean isAnimatingChanges = false;
private void animateChanges(LayoutChangeSet changeSet) {
if (changeSet.added.size() == 0 && changeSet.removed.size() == 0 && changeSet.moved.size() == 0) {
return;
}
for (ItemProxy proxy : changeSet.getAdded()) {
addAndMeasureViewIfNeeded(proxy);
doLayout(proxy);
}
if (isAnimatingChanges) {
layoutAnimator.cancel();
}
isAnimatingChanges = true;
Log.d(TAG, "== animating changes: " + changeSet.toString());
dispatchAnimationsStarted();
layoutAnimator.animateChanges(changeSet, this);
}
public void onLayoutChangeAnimationsCompleted(LayoutAnimator anim) {
// preventLayout = false;
isAnimatingChanges = false;
Log.d(TAG, "=== layout changes complete");
for (ItemProxy proxy : anim.getChangeSet().getRemoved()) {
View v = proxy.view;
removeView(v);
returnItemToPoolIfNeeded(proxy);
}
dispatchAnimationsComplete();
// changeSet = null;
}
public LayoutChangeSet getViewChanges(HashMap<? extends Object, ItemProxy> oldFrames,
HashMap<? extends Object, ItemProxy> newFrames) {
return getViewChanges(oldFrames, newFrames, false);
}
public LayoutChangeSet getViewChanges(HashMap<? extends Object, ItemProxy> oldFrames,
HashMap<? extends Object, ItemProxy> newFrames, boolean moveEvenIfSame) {
// cleanupViews();
LayoutChangeSet change = new LayoutChangeSet();
if (oldFrames == null) {
markAdapterDirty = false;
Log.d(TAG, "old frames is null");
for (ItemProxy proxy : newFrames.values()) {
change.addToAdded(proxy);
}
return change;
}
if (markAdapterDirty) {
Log.d(TAG, "old frames is null");
markAdapterDirty = false;
for (ItemProxy proxy : newFrames.values()) {
change.addToAdded(proxy);
}
for (ItemProxy proxy : oldFrames.values()) {
change.addToDeleted(proxy);
}
return change;
}
Iterator<?> it = newFrames.entrySet().iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
ItemProxy proxy = (ItemProxy) m.getValue();
if (oldFrames.get(m.getKey()) != null) {
ItemProxy old = oldFrames.remove(m.getKey());
proxy.view = old.view;
// if (moveEvenIfSame || !old.compareRect(((ItemProxy)
// m.getValue()).frame)) {
if (moveEvenIfSame || !old.frame.equals(((ItemProxy) m.getValue()).frame)) {
change.addToMoved(proxy, getActualFrame(proxy));
}
} else {
change.addToAdded(proxy);
}
}
for (ItemProxy proxy : oldFrames.values()) {
change.addToDeleted(proxy);
}
frames = newFrames;
return change;
}
@Override
public void requestLayout() {
if (!preventLayout) {
super.requestLayout();
}
}
/**
* Sets the adapter for the this CollectionView.All view pools will be
* cleared at this point and all views on the stage will be cleared
*
* @param adapter
* The {@link BaseSectionedAdapter} that will populate this
* Collection
*/
public void setAdapter(BaseSectionedAdapter adapter) {
Log.d(TAG, "setting adapter");
markLayoutDirty = true;
markAdapterDirty = true;
viewPortX = 0;
viewPortY = 0;
this.itemAdapter = adapter;
if (adapter != null)
viewpool.initializeViewPool(adapter.getViewTypes());
requestLayout();
}
public AbstractLayout getLayoutController() {
return layout;
}
/**
* Indicates that we are not in the middle of a touch gesture
*/
public static final int TOUCH_MODE_REST = -1;
/**
* Indicates we just received the touch event and we are waiting to see if
* the it is a tap or a scroll gesture.
*/
public static final int TOUCH_MODE_DOWN = 0;
/**
* Indicates the touch has been recognized as a tap and we are now waiting
* to see if the touch is a longpress
*/
public static final int TOUCH_MODE_TAP = 1;
/**
* Indicates we have waited for everything we can wait for, but the user's
* finger is still down
*/
public static final int TOUCH_MODE_DONE_WAITING = 2;
/**
* Indicates the touch gesture is a scroll
*/
public static final int TOUCH_MODE_SCROLL = 3;
/**
* Indicates the view is in the process of being flung
*/
public static final int TOUCH_MODE_FLING = 4;
/**
* Indicates the touch gesture is an overscroll - a scroll beyond the
* beginning or end.
*/
public static final int TOUCH_MODE_OVERSCROLL = 5;
/**
* Indicates the view is being flung outside of normal content bounds and
* will spring back.
*/
public static final int TOUCH_MODE_OVERFLING = 6;
/**
* One of TOUCH_MODE_REST, TOUCH_MODE_DOWN, TOUCH_MODE_TAP,
* TOUCH_MODE_SCROLL, or TOUCH_MODE_DONE_WAITING
*/
int mTouchMode = TOUCH_MODE_REST;
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
if (layout == null)
return false;
boolean canScroll = false;
if (layout.horizontalDragEnabled() && this.layout.getContentWidth() > getWidth()) {
canScroll = true;
}
if (layout.verticalDragEnabled() && layout.getContentHeight() > getHeight()) {
canScroll = true;
}
if (mVelocityTracker == null && canScroll) {
mVelocityTracker = VelocityTracker.obtain();
}
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(event);
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
scroller.forceFinished(true);
beginTouchAt = ViewUtils.getItemAt(frames, (int) (viewPortX + event.getX()),
(int) (viewPortY + event.getY()));
if (canScroll) {
deltaX = event.getX();
deltaY = event.getY();
}
mTouchMode = TOUCH_MODE_DOWN;
if (mPendingCheckForTap != null) {
removeCallbacks(mPendingCheckForTap);
mPendingCheckForLongPress = null;
}
if (beginTouchAt != null) {
mPendingCheckForTap = new CheckForTap();
}
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
return true;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (canScroll) {
float xDiff = event.getX() - deltaX;
float yDiff = event.getY() - deltaY;
double distance = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
if (mTouchMode == TOUCH_MODE_DOWN && distance > touchSlop) {
mTouchMode = TOUCH_MODE_SCROLL;
if (mPendingCheckForTap != null) {
removeCallbacks(mPendingCheckForTap);
mPendingCheckForTap = null;
}
}
if (mTouchMode == TOUCH_MODE_SCROLL) {
moveScreen(event.getX() - deltaX, event.getY() - deltaY, false);
deltaX = event.getX();
deltaY = event.getY();
}
}
return true;
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
mTouchMode = TOUCH_MODE_REST;
if (canScroll) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
releaseEdges();
// requestLayout();
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (mTouchMode == TOUCH_MODE_SCROLL) {
releaseEdges();
mVelocityTracker.computeCurrentVelocity(1000, maxFlingVelocity);
if (Math.abs(mVelocityTracker.getXVelocity()) > 100 || Math.abs(mVelocityTracker.getYVelocity()) > 100) {
// TODO: add scroller call here...
flingStarted = true;
scroller.fling(viewPortX, viewPortY, -(int) mVelocityTracker.getXVelocity(),
-(int) mVelocityTracker.getYVelocity(), 0, layout.getContentWidth() - getWidth(), 0,
layout.getContentHeight() - getHeight(), (int) pullPastSlack, (int) pullPastSlack);
post(scrollRunnable);
}
mTouchMode = TOUCH_MODE_REST;
} else if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_DONE_WAITING) {
if (mTouchModeReset != null) {
removeCallbacks(mTouchModeReset);
}
if (beginTouchAt != null && beginTouchAt.view != null) {
beginTouchAt.view.setPressed(true);
mTouchModeReset = new Runnable() {
@Override
public void run() {
mTouchModeReset = null;
mTouchMode = TOUCH_MODE_REST;
if (beginTouchAt != null && beginTouchAt.view != null) {
Log.d(TAG, "setting pressed back to false in reset");
beginTouchAt.view.setPressed(false);
}
if (mChoiceActionMode == null && mOnItemSelectedListener != null) {
mOnItemSelectedListener.onItemSelected(Container.this, selectedItemProxy);
}
// setPressed(false);
// if (!mDataChanged) {
mPerformClick = new PerformClick();
mPerformClick.run();
}
};
selectedItemProxy = beginTouchAt;
postDelayed(mTouchModeReset, ViewConfiguration.getPressedStateDuration());
mTouchMode = TOUCH_MODE_TAP;
} else {
mTouchMode = TOUCH_MODE_REST;
}
}
return true;
}
return false;
}
public ItemProxy getSelectedItemProxy() {
return selectedItemProxy;
}
private void releaseEdges() {
mLeftEdge.onRelease();
mTopEdge.onRelease();
mRightEdge.onRelease();
mBottomEdge.onRelease();
if (scroller.isFinished()) {
boolean start = scroller.springBack(viewPortX, viewPortY, 0, layout.getContentWidth() - getWidth(), 0,
layout.getContentHeight() - getHeight());
Log.d(TAG, "starting spring back = " + start);
if (start) {
flingStarted = true;
post(scrollRunnable);
}
}
}
// TODO: scroll runnable
private Runnable scrollRunnable = new Runnable() {
@Override
public void run() {
if (scroller.isFinished()) {
for (OnScrollListener l : scrollListeners) {
l.onScrolled();
}
return;
}
boolean more = scroller.computeScrollOffset();
if (flingStarted) {
if (mLeftEdge.isFinished() && viewPortX < 0 && layout.horizontalDragEnabled()) {
mLeftEdge.finish();
mLeftEdge.onAbsorb((int) scroller.getCurrVelocity());
}
if (mRightEdge.isFinished() && viewPortX > layout.getContentWidth() - getMeasuredWidth()
&& layout.horizontalDragEnabled()) {
mRightEdge.finish();
mRightEdge.onAbsorb((int) scroller.getCurrVelocity());
}
if (mTopEdge.isFinished() && viewPortY < 0 && layout.verticalDragEnabled()) {
mTopEdge.finish();
mTopEdge.onAbsorb((int) scroller.getCurrVelocity());
}
if (mBottomEdge.isFinished() && viewPortY > layout.getContentHeight() - getMeasuredHeight()
&& layout.verticalDragEnabled()) {
mBottomEdge.finish();
mBottomEdge.onAbsorb((int) scroller.getCurrVelocity());
}
flingStarted = false;
scrollDeltaX = scroller.getCurrX();
scrollDeltaY = scroller.getCurrY();
}
// Log.d("scrolling", "vel = " + scroller.getCurrVelocity() +
// ", cur x = " + scroller.getCurrX()
// + ", cur y = " + scroller.getCurrY() + ", vp x = " + viewPortX);
int x = scroller.getCurrX();
int y = scroller.getCurrY();
int diffx = x - scrollDeltaX;
int diffy = y - scrollDeltaY;
scrollDeltaX = x;
scrollDeltaY = y;
moveScreen(-diffx, -diffy, true);
if (more) {
post(scrollRunnable);
}
}
};
private void moveScreen(float movementX, float movementY, boolean fling) {
if (layout.horizontalDragEnabled()) {
viewPortX = (int) (viewPortX - movementX);
} else {
movementX = 0;
}
if (layout.verticalDragEnabled()) {
viewPortY = (int) (viewPortY - movementY);
} else {
movementY = 0;
}
scrollableWidth = layout.getContentWidth() - getWidth();
scrollableHeight = layout.getContentHeight() - getHeight();
if (!fling) {
if (viewPortX < (int) -pullPastSlack) {
viewPortX = (int) -pullPastSlack;
} else if (viewPortX > scrollableWidth + pullPastSlack) {
viewPortX = (int) (scrollableWidth + pullPastSlack);
}
if (viewPortY < (int) (-pullPastSlack)) {
viewPortY = (int) -pullPastSlack;
} else if (viewPortY > scrollableHeight + pullPastSlack) {
viewPortY = (int) (scrollableHeight + pullPastSlack);
}
if (viewPortX <= 0) {
float val = viewPortX / (-pullPastSlack);
// Log.d(TAG, "val = " + val);
mLeftEdge.onPull(val);
invalidate();
} else if (viewPortX >= scrollableWidth) {
mRightEdge.onPull((viewPortX - scrollableWidth) / (-pullPastSlack));
invalidate();
}
if (viewPortY <= 0) {
mTopEdge.onPull(viewPortY / (-pullPastSlack));
invalidate();
} else if (viewPortY >= scrollableHeight) {
mBottomEdge.onPull((viewPortY - scrollableHeight) / (-pullPastSlack));
invalidate();
}
}
HashMap<? extends Object, ItemProxy> oldFrames = frames;
frames = new HashMap<Object, ItemProxy>(layout.getItemProxies(viewPortX, viewPortY));
LayoutChangeSet changeSet = getViewChanges(oldFrames, frames, true);
for (ItemProxy proxy : changeSet.added) {
addAndMeasureViewIfNeeded(proxy);
doLayout(proxy);
}
for (Pair<ItemProxy, Rect> proxyPair : changeSet.moved) {
doLayout(proxyPair.first);
}
for (ItemProxy proxy : changeSet.removed) {
proxy.view.setAlpha(0.3f);
removeViewInLayout(proxy.view);
returnItemToPoolIfNeeded(proxy);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
boolean needsInvalidate = false;
final int height = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
final int width = getMeasuredWidth();
if (!mLeftEdge.isFinished()) {
// Log.d("EdgeView", "edge not finished");
final int restoreCount = canvas.save();
canvas.rotate(270);
canvas.translate(-height + getPaddingTop(), 0);// width);
mLeftEdge.setSize(height, width);
needsInvalidate = mLeftEdge.draw(canvas);
canvas.restoreToCount(restoreCount);
}
if (!mTopEdge.isFinished()) {
// Log.d("EdgeView", "edge not finished");
final int restoreCount = canvas.save();
mTopEdge.setSize(width, height);
needsInvalidate = mTopEdge.draw(canvas);
canvas.restoreToCount(restoreCount);
}
if (!mRightEdge.isFinished()) {
// Log.d("EdgeView", "edge not finished");
final int restoreCount = canvas.save();
canvas.rotate(90);
canvas.translate(0, -width);// width);
mRightEdge.setSize(height, width);
needsInvalidate = mRightEdge.draw(canvas);
canvas.restoreToCount(restoreCount);
}
if (!mBottomEdge.isFinished()) {
// Log.d("EdgeView", "edge not finished");
final int restoreCount = canvas.save();
canvas.rotate(180);
canvas.translate(-width + getPaddingTop(), -height);
mBottomEdge.setSize(width, height);
needsInvalidate = mBottomEdge.draw(canvas);
canvas.restoreToCount(restoreCount);
}
if (needsInvalidate)
postInvalidateOnAnimation();
}
protected void returnItemToPoolIfNeeded(ItemProxy proxy) {
View v = proxy.view;
v.setTranslationX(0);
v.setTranslationY(0);
v.setRotation(0);
v.setScaleX(1f);
v.setScaleY(1f);
v.setAlpha(1);
viewpool.returnViewToPool(v);
}
public BaseSectionedAdapter getAdapter() {
return itemAdapter;
}
public void setLayoutAnimator(LayoutAnimator anim) {
layoutAnimator = anim;
}
public LayoutAnimator getLayoutAnimator() {
return layoutAnimator;
}
public HashMap<? extends Object, ItemProxy> getFrames() {
return frames;
}
public void clearFrames() {
removeAllViews();
frames = null;
}
@Override
public boolean shouldDelayChildPressedState() {
return true;
}
public int getCheckedItemCount() {
return mCheckStates.size();
}
public ArrayList<IndexPath> getCheckedItemPositions(){
ArrayList<IndexPath> checked = new ArrayList<IndexPath>();
for(int i=0; i<mCheckStates.size(); i++){
checked.add(mCheckStates.keyAt(i));
}
return checked;
}
public void clearChoices() {
mCheckStates.clear();
}
public void setChoiceMode(int choiceMode) {
mChoiceMode = choiceMode;
if (mChoiceActionMode != null) {
mChoiceActionMode.finish();
mChoiceActionMode = null;
}
if (mChoiceMode != CHOICE_MODE_NONE) {
if (mCheckStates == null) {
Log.d(TAG, "Creating mCheckStates");
mCheckStates = new SimpleArrayMap<IndexPath, Boolean>();
}
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
clearChoices();
setLongClickable(true);
}
}
}
boolean isLongClickable = false;
@Override
public void setLongClickable(boolean b) {
isLongClickable = b;
}
@Override
public boolean isLongClickable() {
return isLongClickable;
}
public void setMultiChoiceModeListener(MultiChoiceModeListener listener) {
if (mMultiChoiceModeCallback == null) {
mMultiChoiceModeCallback = new MultiChoiceModeWrapper();
}
mMultiChoiceModeCallback.setWrapped(listener);
}
final class CheckForTap implements Runnable {
@Override
public void run() {
if (mTouchMode == TOUCH_MODE_DOWN) {
mTouchMode = TOUCH_MODE_TAP;
if (beginTouchAt != null && beginTouchAt.view != null) {
beginTouchAt.view.setPressed(true);
// setPressed(true);
}
refreshDrawableState();
final int longPressTimeout = ViewConfiguration.getLongPressTimeout();
final boolean longClickable = isLongClickable();
if (longClickable) {
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
postDelayed(mPendingCheckForLongPress, longPressTimeout);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
private class CheckForLongPress implements Runnable {
@Override
public void run() {
if (beginTouchAt == null) {
// Assuming child that was being long pressed
// is no longer valid
return;
}
mCheckStates.clear();
final View child = beginTouchAt.view;
if (child != null) {
boolean handled = false;
// if (!mDataChanged) {
handled = performLongPress();
if (handled) {
mTouchMode = TOUCH_MODE_REST;
// setPressed(false);
child.setPressed(false);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
boolean performLongPress() {
// CHOICE_MODE_MULTIPLE_MODAL takes over long press.
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
if (mChoiceActionMode == null && (mChoiceActionMode = startActionMode(mMultiChoiceModeCallback)) != null) {
setItemChecked(beginTouchAt.itemSection, beginTouchAt.itemIndex, true);
updateOnScreenCheckedViews();
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return true;
}
boolean handled = false;
final long longPressId = itemAdapter.getItemId(beginTouchAt.itemSection, beginTouchAt.itemSection);
if (mOnItemLongClickListener != null) {
handled = mOnItemLongClickListener.onItemLongClick(this, beginTouchAt.view, beginTouchAt.itemSection,
beginTouchAt.itemIndex, longPressId);
}
if (!handled) {
mContextMenuInfo = createContextMenuInfo(beginTouchAt.view, beginTouchAt.itemSection,
beginTouchAt.itemIndex, longPressId);
handled = super.showContextMenuForChild(this);
}
if (handled) {
updateOnScreenCheckedViews();
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return handled;
}
ContextMenuInfo createContextMenuInfo(View view, int sectionIndex, int positionInSection, long id) {
return new AbsLayoutContainerContextMenuInfo(view, sectionIndex, positionInSection, id);
}
class MultiChoiceModeWrapper implements MultiChoiceModeListener {
private MultiChoiceModeListener mWrapped;
public void setWrapped(MultiChoiceModeListener wrapped) {
mWrapped = wrapped;
}
public boolean hasWrappedCallback() {
return mWrapped != null;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
if (mWrapped.onCreateActionMode(mode, menu)) {
// Initialize checked graphic state?
setLongClickable(false);
return true;
}
return false;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return mWrapped.onPrepareActionMode(mode, menu);
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return mWrapped.onActionItemClicked(mode, item);
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mWrapped.onDestroyActionMode(mode);
mChoiceActionMode = null;
// Ending selection mode means deselecting everything.
clearChoices();
updateOnScreenCheckedViews();
// rememberSyncState();
requestLayout();
setLongClickable(true);
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int section, int position, long id, boolean checked) {
mWrapped.onItemCheckedStateChanged(mode, section, position, id, checked);
// If there are no items selected we no longer need the selection
// mode.
if (getCheckedItemCount() == 0) {
mode.finish();
}
}
}
public interface MultiChoiceModeListener extends ActionMode.Callback {
/**
* Called when an item is checked or unchecked during selection mode.
*
* @param mode
* The {@link ActionMode} providing the selection mode
* @param section
* The Section of the item that was checked
* @param position
* Adapter position of the item in the section that was
* checked or unchecked
* @param id
* Adapter ID of the item that was checked or unchecked
* @param checked
* <code>true</code> if the item is now checked,
* <code>false</code> if the item is now unchecked.
*/
public void onItemCheckedStateChanged(ActionMode mode, int section, int position, long id, boolean checked);
}
public void setItemChecked(int sectionIndex, int positionInSection, boolean value) {
if (mChoiceMode == CHOICE_MODE_NONE) {
return;
}
// Start selection mode if needed. We don't need to if we're unchecking
// something.
if (value && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode == null) {
if (mMultiChoiceModeCallback == null || !mMultiChoiceModeCallback.hasWrappedCallback()) {
throw new IllegalStateException("Container: attempted to start selection mode "
+ "for CHOICE_MODE_MULTIPLE_MODAL but no choice mode callback was "
+ "supplied. Call setMultiChoiceModeListener to set a callback.");
}
mChoiceActionMode = startActionMode(mMultiChoiceModeCallback);
}
if (mChoiceMode == CHOICE_MODE_MULTIPLE || mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
Log.d(TAG, "Setting checked: " + sectionIndex + "/" + positionInSection + ": " + value);
setCheckedValue(sectionIndex, positionInSection, value);
if (mChoiceActionMode != null) {
final long id = itemAdapter.getItemId(sectionIndex, positionInSection);
mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode, sectionIndex, positionInSection,
id, value);
}
} else {
setCheckedValue(sectionIndex, positionInSection, value);
}
// if (!mInLayout && !mBlockLayoutRequests) {
// mDataChanged = true;
// rememberSyncState();
requestLayout();
}
@Override
public boolean performItemClick(View view, int section, int position, long id) {
boolean handled = false;
boolean dispatchItemClick = true;
if (mChoiceMode != CHOICE_MODE_NONE) {
handled = true;
boolean checkedStateChanged = false;
if (mChoiceMode == CHOICE_MODE_MULTIPLE
|| (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode != null)) {
boolean checked = isChecked(section, position);
checked = !checked;
setCheckedValue(section, position, checked);
if (mChoiceActionMode != null) {
mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode, section, position, id,
checked);
dispatchItemClick = false;
}
checkedStateChanged = true;
} else if (mChoiceMode == CHOICE_MODE_SINGLE) {
boolean checked = !isChecked(section, position);
if (checked) {
setCheckedValue(section, position, checked);
}
checkedStateChanged = true;
}
if (checkedStateChanged) {
updateOnScreenCheckedViews();
}
}
if (dispatchItemClick) {
handled |= super.performItemClick(view, section, position, id);
}
return handled;
}
private class PerformClick implements Runnable {
@Override
public void run() {
// if (mDataChanged) return;
View view = beginTouchAt.view;
if (view != null) {
performItemClick(view, beginTouchAt.itemSection, beginTouchAt.itemIndex,
itemAdapter.getItemId(beginTouchAt.itemSection, beginTouchAt.itemIndex));
}
}
}
/**
* Perform a quick, in-place update of the checked or activated state on all
* visible item views. This should only be called when a valid choice mode
* is active.
*/
private void updateOnScreenCheckedViews() {
Iterator<?> it = frames.entrySet().iterator();
View child = null;
while (it.hasNext()) {
Map.Entry<?, ItemProxy> pairs = (Map.Entry<?, ItemProxy>) it.next();
child = pairs.getValue().view;
boolean isChecked = isChecked(pairs.getValue().itemSection, pairs.getValue().itemIndex);
if (child instanceof Checkable) {
Log.d(TAG, "Setting checked UI : " + pairs.getValue().itemSection + ", " + pairs.getValue().itemIndex
+ ": " + isChecked);
((Checkable) child).setChecked(isChecked);
} else {
child.setActivated(isChecked);
}
}
}
public boolean isChecked(int sectionIndex, int positionInSection) {
for (int i = 0; i < mCheckStates.size(); i++) {
IndexPath p = mCheckStates.keyAt(i);
if (p.section == sectionIndex && p.positionInSection == positionInSection) {
return true;
}
}
return false;
}
/**
* Updates the internal ArrayMap keeping track of checked states. Will not
* update the check UI.
*/
protected void setCheckedValue(int sectionIndex, int positionInSection, boolean val) {
int foundAtIndex = -1;
for (int i = 0; i < mCheckStates.size(); i++) {
IndexPath p = mCheckStates.keyAt(i);
if (p.section == sectionIndex && p.positionInSection == positionInSection) {
foundAtIndex = i;
break;
}
}
if (foundAtIndex > -1 && val == false) {
mCheckStates.removeAt(foundAtIndex);
} else if (foundAtIndex == -1 && val == true) {
IndexPath pos = new IndexPath(sectionIndex, positionInSection);
mCheckStates.put(pos, true);
}
}
public void addScrollListener(OnScrollListener listener) {
if (!scrollListeners.contains(listener))
scrollListeners.add(listener);
}
public void removeScrollListener(OnScrollListener listener) {
scrollListeners.remove(listener);
}
public void scrollToItem(int sectionIndex, int itemIndex, boolean animate) {
Section section;
if (sectionIndex > itemAdapter.getNumberOfSections() || sectionIndex < 0
|| (section = itemAdapter.getSection(sectionIndex)) == null) {
Log.d(TAG, "section returning");
return;
}
if (itemIndex < 0 || itemIndex > section.getDataCount()) {
Log.d(TAG, "item index returning");
return;
}
ItemProxy proxy = layout.getItemProxyForItem(section.getDataAtIndex(itemIndex));
int newVPX = proxy.frame.left;
int newVPY = proxy.frame.top;
if (newVPX > layout.getContentWidth() - getMeasuredWidth())
newVPX = layout.getContentWidth() - getMeasuredWidth();
if (newVPY > layout.getContentHeight() - getMeasuredHeight())
newVPY = layout.getContentHeight() - getMeasuredHeight();
if (animate) {
Log.d(TAG, "vpx = " + newVPX + ", vpy = " + newVPY);
Log.d(TAG, "viewpx = " + viewPortX + ", viewpy = " + viewPortY);
scroller.startScroll(viewPortX, viewPortY, (newVPX - viewPortX), (viewPortY - newVPY), 1500);
Log.d(TAG, "final vpx = " + scroller.getFinalX() + ", final vpy = " + scroller.getFinalY());
flingStarted = true;
post(scrollRunnable);
} else {
Log.d(TAG, "vpx = " + newVPX + ", vpy = " + newVPY);
moveScreen((viewPortX - newVPX), (viewPortY - newVPY), false);
for (OnScrollListener l : scrollListeners) {
l.onScrolled();
}
}
}
public interface OnScrollListener {
public void onScrolled();
}
}
|
package comlib.message;
import rescuecore2.standard.entities.Human;
import rescuecore2.worldmodel.EntityID;
abstract public class HumanMessage extends CommunicationMessage {
protected EntityID humanID;
protected int humanHP;
protected int humanBuriedness;
protected int humanDamage;
protected EntityID humanPosition;
public DummyMessage(int messageID, int test) {
super(messageID);
dummyTest = test;
}
public DummyMessage(int messageID, int time, int ttl, int test) {
super(messageID, time, ttl);
dummyTest = test;
}
public int getValue() {
return this.dummyTest;
}
}
|
package net.wurstclient.gui;
import java.util.ArrayList;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.wurstclient.WurstClient;
import net.wurstclient.events.KeyPressEvent;
import net.wurstclient.events.listeners.KeyPressListener;
import net.wurstclient.features.Feature;
import net.wurstclient.features.special_features.TabGuiSpf;
import net.wurstclient.font.Fonts;
public final class TabGui implements KeyPressListener
{
private final ArrayList<Tab> tabs = new ArrayList<>();
private final TabGuiSpf tabGuiSpf = WurstClient.INSTANCE.special.tabGuiSpf;
private int selected;
private boolean tabOpened;
public TabGui()
{
WurstClient.INSTANCE.events.add(KeyPressListener.class, this);
WurstClient wurst = WurstClient.INSTANCE;
Tab blocksTab = new Tab("Blocks");
blocksTab.add(wurst.mods.antiCactusMod);
blocksTab.add(wurst.mods.autoBuildMod);
blocksTab.add(wurst.mods.autoMineMod);
tabs.add(blocksTab);
Tab chatTab = new Tab("Chat");
chatTab.add(wurst.mods.antiSpamMod);
chatTab.add(wurst.mods.fancyChatMod);
chatTab.add(wurst.mods.forceOpMod);
tabs.add(chatTab);
}
@Override
public void onKeyPress(KeyPressEvent event)
{
if(tabOpened)
switch(event.getKeyCode())
{
case Keyboard.KEY_LEFT:
tabOpened = false;
break;
default:
tabs.get(selected).onKeyPress(event.getKeyCode());
break;
}
else
switch(event.getKeyCode())
{
case Keyboard.KEY_DOWN:
if(selected < tabs.size() - 1)
selected++;
else
selected = 0;
break;
case Keyboard.KEY_UP:
if(selected > 0)
selected
else
selected = tabs.size() - 1;
break;
case Keyboard.KEY_RIGHT:
tabOpened = true;
break;
}
}
public void render(float partialTicks)
{
if(tabGuiSpf.isHidden())
return;
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glPushMatrix();
ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft());
int x = 2;
int y = 23;
int width = 64;
for(Tab tab : tabs)
{
int tabWidth = Fonts.segoe18.getStringWidth(tab.name) + 4;
if(tabWidth > width)
width = tabWidth;
}
int height = tabs.size() * 10;
GL11.glTranslatef(x, y, 0);
drawBox(0, 0, width, height);
int factor = sr.getScaleFactor();
GL11.glScissor(x * factor, (sr.getScaledHeight() - height - y) * factor,
width * factor, height * factor);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
int textY = -2;
for(int i = 0; i < tabs.size(); i++)
{
String tabName = tabs.get(i).name;
if(i == selected)
tabName = (tabOpened ? "<" : ">") + tabName;
Fonts.segoe18.drawString(tabName, 2, textY, 0xffffffff);
textY += 10;
}
GL11.glDisable(GL11.GL_SCISSOR_TEST);
if(tabOpened)
{
GL11.glPushMatrix();
GL11.glDisable(GL11.GL_TEXTURE_2D);
Tab tab = tabs.get(selected);
int tabX = x + width + 2;
int tabY = y;
int tabWidth = 64;
for(Feature f : tab.features)
{
int fWidth = Fonts.segoe18.getStringWidth(f.getName()) + 4;
if(fWidth > tabWidth)
tabWidth = fWidth;
}
int tabHeight = tab.features.size() * 10;
GL11.glTranslatef(width + 2, 0, 0);
drawBox(0, 0, tabWidth, tabHeight);
GL11.glScissor(tabX * factor,
(sr.getScaledHeight() - tabHeight - tabY) * factor,
tabWidth * factor, tabHeight * factor);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
int tabTextY = -2;
for(int i = 0; i < tab.features.size(); i++)
{
String fName = tab.features.get(i).getName();
if(i == tab.selected)
fName = ">" + fName;
Fonts.segoe18.drawString(fName, 2, tabTextY, 0xffffffff);
tabTextY += 10;
}
GL11.glDisable(GL11.GL_SCISSOR_TEST);
GL11.glPopMatrix();
}
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_CULL_FACE);
}
private void drawBox(int x1, int y1, int x2, int y2)
{
// color
GL11.glColor4f(0.25F, 0.25F, 0.25F, 0.5F);
// box
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glVertex2i(x1, y1);
GL11.glVertex2i(x2, y1);
GL11.glVertex2i(x2, y2);
GL11.glVertex2i(x1, y2);
}
GL11.glEnd();
// outline positions
double xi1 = x1 - 0.1;
double xi2 = x2 + 0.1;
double yi1 = y1 - 0.1;
double yi2 = y2 + 0.1;
// outline
GL11.glLineWidth(1);
GL11.glColor4f(0, 0, 0, 0.5F);
GL11.glBegin(GL11.GL_LINE_LOOP);
{
GL11.glVertex2d(xi1, yi1);
GL11.glVertex2d(xi2, yi1);
GL11.glVertex2d(xi2, yi2);
GL11.glVertex2d(xi1, yi2);
}
GL11.glEnd();
// shadow positions
xi1 -= 0.9;
xi2 += 0.9;
yi1 -= 0.9;
yi2 += 0.9;
// top left
GL11.glBegin(GL11.GL_POLYGON);
{
GL11.glColor4f(0.125F, 0.125F, 0.125F, 0.75F);
GL11.glVertex2d(x1, y1);
GL11.glVertex2d(x2, y1);
GL11.glColor4f(0, 0, 0, 0);
GL11.glVertex2d(xi2, yi1);
GL11.glVertex2d(xi1, yi1);
GL11.glVertex2d(xi1, yi2);
GL11.glColor4f(0.125F, 0.125F, 0.125F, 0.75F);
GL11.glVertex2d(x1, y2);
}
GL11.glEnd();
// bottom right
GL11.glBegin(GL11.GL_POLYGON);
{
GL11.glVertex2d(x2, y2);
GL11.glVertex2d(x2, y1);
GL11.glColor4f(0, 0, 0, 0);
GL11.glVertex2d(xi2, yi1);
GL11.glVertex2d(xi2, yi2);
GL11.glVertex2d(xi1, yi2);
GL11.glColor4f(0.125F, 0.125F, 0.125F, 0.75F);
GL11.glVertex2d(x1, y2);
}
GL11.glEnd();
}
private static final class Tab
{
private final String name;
private final ArrayList<Feature> features = new ArrayList<>();
private int selected;
public Tab(String name)
{
this.name = name;
}
public void onKeyPress(int keyCode)
{
switch(keyCode)
{
case Keyboard.KEY_DOWN:
if(selected < features.size() - 1)
selected++;
else
selected = 0;
break;
case Keyboard.KEY_UP:
if(selected > 0)
selected
else
selected = features.size() - 1;
break;
case Keyboard.KEY_RETURN:
features.get(selected).doPrimaryAction();
break;
}
}
public void add(Feature feature)
{
features.add(feature);
}
}
}
|
package org.knowm.xchange.bibox;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.knowm.xchange.bibox.dto.BiboxMultipleResponses;
import org.knowm.xchange.bibox.dto.BiboxPagedResponses;
import org.knowm.xchange.bibox.dto.BiboxSingleResponse;
import org.knowm.xchange.bibox.dto.account.BiboxAssetsResult;
import org.knowm.xchange.bibox.dto.account.BiboxDeposit;
import org.knowm.xchange.bibox.dto.account.BiboxWithdrawal;
import org.knowm.xchange.bibox.dto.trade.BiboxOrders;
import si.mazi.rescu.ParamsDigest;
/** @author odrotleff */
@Path("v1")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public interface BiboxAuthenticated extends Bibox {
/**
* Retrieve balances of the account
*
* @return list of coins
*/
@POST
@Path("transfer")
BiboxSingleResponse<BiboxAssetsResult> assets(
@FormParam(FORM_CMDS) String cmds,
@FormParam(FORM_APIKEY) String apiKey,
@FormParam(FORM_SIGNATURE) ParamsDigest signature);
/**
* Retrieve deposits
*
* @return list of deposits
*/
@POST
@Path("transfer")
BiboxPagedResponses<BiboxDeposit> transferInList(
@FormParam(FORM_CMDS) String cmds,
@FormParam(FORM_APIKEY) String apiKey,
@FormParam(FORM_SIGNATURE) ParamsDigest signature);
/**
* Retrieve withdrawals
*
* @return list of withdrawals
*/
@POST
@Path("transfer")
BiboxPagedResponses<BiboxWithdrawal> transferOutList(
@FormParam(FORM_CMDS) String cmds,
@FormParam(FORM_APIKEY) String apiKey,
@FormParam(FORM_SIGNATURE) ParamsDigest signature);
/**
* Execute withdrawals
*
* @return withdrawal id
*/
@POST
@Path("transfer")
BiboxSingleResponse<String> transfer(
@FormParam(FORM_CMDS) String cmds,
@FormParam(FORM_APIKEY) String apiKey,
@FormParam(FORM_SIGNATURE) ParamsDigest signature);
/**
* Get deposit address for coin
*
* @return list of coins
*/
@POST
@Path("transfer")
BiboxSingleResponse<String> depositAddress(
@FormParam(FORM_CMDS) String cmds,
@FormParam(FORM_APIKEY) String apiKey,
@FormParam(FORM_SIGNATURE) ParamsDigest signature);
/**
* Create an order (market/limit)
*
* @return order id
*/
@POST
@Path("orderpending")
BiboxSingleResponse<String> trade(
@FormParam(FORM_CMDS) String cmds,
@FormParam(FORM_APIKEY) String apiKey,
@FormParam(FORM_SIGNATURE) ParamsDigest signature);
/**
* Cancel an order
*
* @return chinese for "cancelled", useless
*/
@POST
@Path("orderpending")
BiboxSingleResponse<String> cancelTrade(
@FormParam(FORM_CMDS) String cmds,
@FormParam(FORM_APIKEY) String apiKey,
@FormParam(FORM_SIGNATURE) ParamsDigest signature);
/**
* Obtain open order list / order history
*
* @return open orders
*/
@POST
@Path("orderpending")
BiboxSingleResponse<BiboxOrders> orderPendingList(
@FormParam(FORM_CMDS) String cmds,
@FormParam(FORM_APIKEY) String apiKey,
@FormParam(FORM_SIGNATURE) ParamsDigest signature);
/**
* Cancel multiple orders
*
* @return multiple times chinese for "cancelled", useless
*/
@POST
@Path("orderpending")
BiboxMultipleResponses<String> cancelTrades(
@FormParam(FORM_CMDS) String cmds,
@FormParam(FORM_APIKEY) String apiKey,
@FormParam(FORM_SIGNATURE) ParamsDigest signature);
}
|
package org.codehaus.xfire.attachments;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Header;
import javax.mail.MessagingException;
import javax.mail.internet.InternetHeaders;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.XFireRuntimeException;
import org.codehaus.xfire.util.CachedOutputStream;
public class StreamedAttachments
implements Attachments
{
public static final String ATTACHMENT_DIRECTORY = "attachment-directory";
public static final String ATTACHMENT_MEMORY_THRESHOLD = "attachment-memory-threshold";
private static final String NO_TEMP_ERR = "Unable to write tempoary files. "
+ "No temporary directory configured, and security settings prohibit "
+ "access to the \"java.io.tmpdir\" property.";
private boolean soapMessageRead = false;
private PushbackInputStream stream;
private String boundary;
private int threshold = 1024 * 100;
private File tempDirectory;
private Map parts = new HashMap();
private Attachment soapMessage;
private String contentType;
private List cache = new ArrayList();
private MessageContext context;
public StreamedAttachments(InputStream is, String contentType) throws IOException
{
this(null, is, contentType);
}
public StreamedAttachments(MessageContext context, InputStream is, String contentType)
throws IOException
{
int i = contentType.indexOf("boundary=\"");
int end;
int len;
if (i == -1)
{
i = contentType.indexOf("boundary=");
end = contentType.indexOf(";", i + 9);
if (end == -1)
end = contentType.length();
len = 9;
}
else
{
end = contentType.indexOf("\"", i + 10);
len = 10;
}
if (i == -1 || end == -1)
throw new IOException("Invalid content type: missing boundary! " + contentType);
this.boundary = "--" + contentType.substring(i + len, end);
this.stream = new PushbackInputStream(is, boundary.length());
this.contentType = contentType;
if (!readTillFirstBoundary(stream, boundary.getBytes()))
throw new IOException("Couldn't find MIME boundary: " + boundary);
this.context = context;
}
public void addPart(Attachment part)
{
throw new UnsupportedOperationException();
}
public String getContentType()
{
return contentType;
}
public Attachment getPart(String id)
{
if (!parts.containsKey(id))
readTo(id);
return (Attachment) parts.get(id);
}
public Iterator getParts()
{
ensureAllPartsRead();
return parts.values().iterator();
}
public String getSoapContentType()
{
ensureSoapAttachmentIsRead();
return soapMessage.getHeader("Content-Type");
}
public Attachment getSoapMessage()
{
ensureSoapAttachmentIsRead();
return soapMessage;
}
private void ensureSoapAttachmentIsRead()
{
if (soapMessageRead)
return;
try
{
soapMessage = readNextAttachment();
soapMessageRead = true;
}
catch (IOException e)
{
throw new XFireRuntimeException("Could not read message!", e);
}
}
private void ensureAllPartsRead()
{
readTo(null);
}
private void readTo(String id)
{
ensureSoapAttachmentIsRead();
try
{
for (Attachment a = readNextAttachment(); a != null; a = readNextAttachment())
{
parts.put(a.getId(), a);
if (a != null && id != null && a.getId().equals(id))
return;
}
}
catch (IOException e)
{
throw new XFireRuntimeException("Could not read message!", e);
}
}
private Attachment readNextAttachment()
throws IOException
{
int v = stream.read();
if (v == -1)
return null;
stream.unread(v);
try
{
InternetHeaders headers = new InternetHeaders(stream);
MimeBodyPartInputStream partStream = new MimeBodyPartInputStream(stream, boundary
.getBytes());
final CachedOutputStream cos = new CachedOutputStream(getThreshold(),
getTempDirectory());
copy(partStream, cos);
final String ct = headers.getHeader("Content-Type", null);
cache.add(cos);
DataSource source = new AttachmentDataSource(ct, cos);
DataHandler dh = new DataHandler(source);
String id = headers.getHeader("Content-ID", null);
if (id != null && id.startsWith("<"))
{
id = id.substring(1, id.length() - 1);
}
SimpleAttachment att = new SimpleAttachment(id, dh);
for (Enumeration e = headers.getAllHeaders(); e.hasMoreElements();)
{
Header header = (Header) e.nextElement();
att.setHeader(header.getName(), header.getValue());
}
return att;
}
catch (MessagingException e)
{
throw new IOException("Couldn't read headers.");
}
}
public void setSoapContentType(String soapMimeType)
{
throw new UnsupportedOperationException();
}
public void setSoapMessage(Attachment soapMessage)
{
throw new UnsupportedOperationException();
}
public int size()
{
ensureAllPartsRead();
return parts.size();
}
public void write(OutputStream out)
throws IOException
{
throw new UnsupportedOperationException();
}
public void dispose()
{
for (Iterator itr = cache.iterator(); itr.hasNext();)
{
CachedOutputStream cos = (CachedOutputStream) itr.next();
cos.dispose();
}
}
/**
* The directory where attachments will be written to if they exceed the
* Threshold.
*
* @return
*/
public File getTempDirectory()
{
File td = null;
if (context != null)
{
Object value = context.getContextualProperty(ATTACHMENT_DIRECTORY);
if (value instanceof File)
{
td = (File) value;
}
else if (value != null)
{
td = new File((String) value);
}
}
if (td == null)
{
td = tempDirectory;
}
if (td == null)
{
String defaultTempDir;
try
{
defaultTempDir = System.getProperty("java.io.tmpdir");
}
catch (SecurityException se)
{
throw new IllegalStateException(NO_TEMP_ERR);
}
td = new File(defaultTempDir);
}
return td;
}
public void setTempDirectory(File tempDirectory)
{
this.tempDirectory = tempDirectory;
}
/**
* Get the threshold in bytes. The threshold is the size an attachment needs
* to reach before it is written to a temporary directory.
*
* @return
*/
public int getThreshold()
{
if (context != null)
{
Object tObj = context.getContextualProperty(ATTACHMENT_MEMORY_THRESHOLD);
if (tObj != null)
{
if (tObj instanceof Integer)
{
Integer t = (Integer) tObj;
return t.intValue();
}
return Integer.valueOf(tObj.toString()).intValue();
}
}
return threshold;
}
public void setThreshold(int threshold)
{
this.threshold = threshold;
}
protected static void copy(InputStream input, OutputStream output)
throws IOException
{
try
{
final byte[] buffer = new byte[8096];
int n = input.read(buffer);
while (n > 0)
{
output.write(buffer, 0, n);
n = input.read(buffer);
}
}
finally
{
input.close();
output.close();
}
}
/**
* Move the read pointer to the begining of the first part read till the end
* of first boundary
*
* @param pushbackInStream
* @param boundary
* @throws MessagingException
*/
private boolean readTillFirstBoundary(PushbackInputStream pushbackInStream, byte[] boundary)
throws IOException
{
// work around a bug in PushBackInputStream where the buffer isn't
// initialized
// and available always returns 0.
int value = pushbackInStream.read();
pushbackInStream.unread(value);
while (value != -1)
{
value = pushbackInStream.read();
if ((byte) value == boundary[0])
{
int boundaryIndex = 0;
while (value != -1 && (boundaryIndex < boundary.length)
&& ((byte) value == boundary[boundaryIndex]))
{
value = pushbackInStream.read();
if (value == -1)
throw new IOException(
"Unexpected End of Stream while searching for first Mime Boundary");
boundaryIndex++;
}
if (boundaryIndex == boundary.length)
{ // boundary found
pushbackInStream.read();
return true;
}
}
}
return false;
}
private class MimeBodyPartInputStream
extends InputStream
{
PushbackInputStream inStream;
boolean boundaryFound = false;
byte[] boundary;
public MimeBodyPartInputStream(PushbackInputStream inStream, byte[] boundary)
{
super();
this.inStream = inStream;
this.boundary = boundary;
}
public int read()
throws IOException
{
if (boundaryFound)
{
return -1;
}
// read the next value from stream
int value = inStream.read();
// Used to add back a new line if a boundary is not found.
boolean encounteredNewLine = false;
// A problem occured because all the mime parts tends to have a /r/n
// at the end. Making it hard to transform them to correct
// DataSources.
// This logic introduced to handle it
// TODO look more in to this && for a better way to do this
if (value == 13)
{
value = inStream.read();
if (value != 10)
{
inStream.unread(value);
return 13;
}
else
{
value = inStream.read();
if ((byte) value != boundary[0])
{
inStream.unread(value);
inStream.unread(10);
return 13;
}
else
{
encounteredNewLine = true;
}
}
}
else if ((byte) value != boundary[0])
{
return value;
}
// read value is the first byte of the boundary. Start matching the
// next characters to find a boundary
int boundaryIndex = 0;
while ((boundaryIndex < boundary.length) && ((byte) value == boundary[boundaryIndex]))
{
value = inStream.read();
boundaryIndex++;
}
if (boundaryIndex == boundary.length)
{ // boundary found
boundaryFound = true;
// read the end of line character
if (inStream.read() == 45 && value == 45)
{
// Last mime boundary should have a succeeding "--"
// as we are on it, read the terminating CRLF
int value1 = inStream.read();
int value2 = inStream.read();
}
return -1;
}
// Boundary not found. Restoring bytes skipped.
// write first skipped byte, push back the rest
if (value != -1)
{ // Stream might have ended
inStream.unread(value);
}
inStream.unread(boundary, 1, boundaryIndex - 1);
if (encounteredNewLine)
{
// Put back 45
inStream.unread(boundary[0]);
// Put back 10
inStream.unread(10);
// Return the first character we read.
return 13;
}
else
{
// No new line encountered, return as usual.
return boundary[0];
}
}
}
}
|
package com.xpn.xwiki.doc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.xwiki.bridge.AttachmentName;
import org.xwiki.bridge.DocumentAccessBridge;
import org.xwiki.bridge.DocumentModelBridge;
import org.xwiki.bridge.DocumentName;
import org.xwiki.bridge.DocumentNameFactory;
import org.xwiki.bridge.DocumentNameSerializer;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.context.Execution;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.classes.PropertyClass;
/**
* Exposes methods for accessing Document data. This is temporary until we remodel the Model classes and the Document
* services. The implementation is inside the old core, and not in a component because it has dependencies on the old
* core.
*
* @version $Id$
* @since 1.6M1
*/
@Component
public class DefaultDocumentAccessBridge implements DocumentAccessBridge
{
/** Execution context handler, needed for accessing the XWikiContext. */
@Requirement
private Execution execution;
@Requirement
private DocumentNameSerializer documentNameSerializer;
@Requirement
private DocumentNameFactory documentNameFactory;
private XWikiContext getContext()
{
return (XWikiContext) this.execution.getContext().getProperty("xwikicontext");
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getDocument(String)
*/
public DocumentModelBridge getDocument(String documentName) throws Exception
{
XWikiContext xcontext = getContext();
return xcontext.getWiki().getDocument(documentName, xcontext);
}
/**
* {@inheritDoc}
*
* @see org.xwiki.bridge.DocumentAccessBridge#getDocument(org.xwiki.bridge.DocumentName)
*/
public DocumentModelBridge getDocument(DocumentName documentName) throws Exception
{
XWikiContext xcontext = getContext();
XWikiDocument doc = new XWikiDocument();
doc.setDatabase(documentName.getWiki());
doc.setSpace(documentName.getSpace());
doc.setName(documentName.getPage());
return xcontext.getWiki().getDocument(doc, xcontext);
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getDocumentName(String)
*/
public DocumentName getDocumentName(String documentName)
{
XWikiDocument document = new XWikiDocument();
document.setFullName(documentName, getContext());
return new DocumentName(document.getWikiName(), document.getSpaceName(), document.getPageName());
}
/**
* {@inheritDoc}
*
* @see org.xwiki.bridge.DocumentAccessBridge#getCurrentDocumentName()
*/
public DocumentName getCurrentDocumentName()
{
XWikiDocument currentDocument = getContext().getDoc();
return currentDocument == null ? null : new DocumentName(currentDocument.getWikiName(),
currentDocument.getSpaceName(), currentDocument.getPageName());
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getDocumentContent(String)
*/
public String getDocumentContent(String documentName) throws Exception
{
XWikiContext xcontext = getContext();
return getDocumentContent(documentName, xcontext.getLanguage());
}
/**
* {@inheritDoc}
*
* @see org.xwiki.bridge.DocumentAccessBridge#getDocumentContentForDefaultLanguage(java.lang.String)
*/
public String getDocumentContentForDefaultLanguage(String documentName) throws Exception
{
XWikiContext xcontext = getContext();
return xcontext.getWiki().getDocument(documentName, xcontext).getContent();
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getDocumentContent(String, String)
*/
public String getDocumentContent(String documentName, String language) throws Exception
{
XWikiContext xcontext = getContext();
String originalRev = (String) xcontext.get("rev");
try {
xcontext.remove("rev");
return xcontext.getWiki().getDocument(documentName, xcontext).getTranslatedContent(language, xcontext);
} finally {
if (originalRev != null) {
xcontext.put("rev", originalRev);
}
}
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#exists(String)
*/
public boolean exists(String documentName)
{
boolean exists = false;
try {
XWikiContext xcontext = getContext();
XWikiDocument doc = xcontext.getWiki().getDocument(documentName, xcontext);
exists = (!doc.isNew());
} catch (XWikiException e) {
// If we failed to get the document we consider it doesn't exist.
// Note that this can happen when the storage subsystem is down for example.
}
return exists;
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#setDocumentContent(String, String, String, boolean)
*/
public void setDocumentContent(String documentName, String content, String editComment, boolean isMinorEdit)
throws Exception
{
XWikiContext xcontext = getContext();
XWikiDocument doc = xcontext.getWiki().getDocument(documentName, xcontext);
doc.setContent(content);
saveDocument(doc, editComment, isMinorEdit);
}
/**
* {@inheritDoc}
*
* @see org.xwiki.bridge.DocumentAccessBridge#getDocumentSyntaxId(java.lang.String)
*/
public String getDocumentSyntaxId(String documentName) throws Exception
{
XWikiContext xcontext = getContext();
XWikiDocument doc = xcontext.getWiki().getDocument(documentName, xcontext);
return doc.getSyntaxId();
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#setDocumentSyntaxId(String, String)
*/
public void setDocumentSyntaxId(String documentName, String syntaxId) throws Exception
{
XWikiContext xcontext = getContext();
XWikiDocument doc = xcontext.getWiki().getDocument(documentName, xcontext);
String oldSyntaxId = doc.getSyntaxId();
doc.setSyntaxId(syntaxId);
saveDocument(doc, String.format("Changed document syntax from [%s] to [%s].", oldSyntaxId, syntaxId), true);
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getProperty(String, String, int, String)
*/
public Object getProperty(String documentName, String className, int objectNumber, String propertyName)
{
try {
XWikiContext xcontext = getContext();
return ((BaseProperty) xcontext.getWiki().getDocument(documentName, xcontext).getObject(className,
objectNumber).get(propertyName)).getValue();
} catch (Exception ex) {
return null;
}
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getProperty(String, String, String)
*/
public Object getProperty(String documentName, String className, String propertyName)
{
Object value;
try {
XWikiContext xcontext = getContext();
XWikiDocument doc = xcontext.getWiki().getDocument(documentName, xcontext);
BaseObject object = doc.getObject(className);
BaseProperty property = (BaseProperty) object.get(propertyName);
value = property.getValue();
} catch (Exception ex) {
value = null;
}
return value;
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getProperty(String, String)
*/
public Object getProperty(String documentName, String propertyName)
{
try {
XWikiContext xcontext = getContext();
return ((BaseProperty) xcontext.getWiki().getDocument(documentName, xcontext).getFirstObject(propertyName,
xcontext).get(propertyName)).getValue();
} catch (Exception ex) {
return null;
}
}
public List<Object> getProperties(String documentName, String className)
{
List<Object> result;
try {
XWikiContext xcontext = getContext();
result = new ArrayList<Object>(
xcontext.getWiki().getDocument(documentName, xcontext).getObject(className).getFieldList());
} catch (Exception ex) {
result = Collections.emptyList();
}
return result;
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getPropertyType(String, String)
*/
public String getPropertyType(String className, String propertyName) throws Exception
{
XWikiContext xcontext = getContext();
PropertyClass pc = xcontext.getWiki().getPropertyClassFromName(className + "_" + propertyName, xcontext);
if (pc == null) {
return null;
} else {
return pc.newProperty().getClass().getName();
}
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#isPropertyCustomMapped(String, String)
*/
public boolean isPropertyCustomMapped(String className, String property) throws Exception
{
XWikiContext xcontext = getContext();
if (!xcontext.getWiki().hasCustomMappings()) {
return false;
}
List<String> lst = xcontext.getWiki().getClass(className, xcontext).getCustomMappingPropertyList(xcontext);
return lst != null && lst.contains(property);
}
/**
* {@inheritDoc}
*/
public void setProperty(String documentName, String className, String propertyName, Object propertyValue)
throws Exception
{
XWikiContext xcontext = getContext();
XWikiDocument doc = xcontext.getWiki().getDocument(documentName, xcontext);
BaseObject obj = doc.getObject(className, true, xcontext);
if (obj != null) {
obj.set(propertyName, propertyValue, xcontext);
saveDocument(doc, String.format("Property [%s] set.", propertyName), true);
}
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getAttachmentContent(String, String)
*/
public byte[] getAttachmentContent(String documentName, String attachmentName) throws Exception
{
XWikiContext xcontext = getContext();
return xcontext.getWiki().getDocument(documentName, xcontext).getAttachment(attachmentName).getContent(xcontext);
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#setAttachmentContent(String, String, byte[])
*/
public void setAttachmentContent(String documentName, String attachmentName, byte[] attachmentData)
throws Exception
{
XWikiContext xcontext = getContext();
XWikiDocument doc = xcontext.getWiki().getDocument(documentName, xcontext);
XWikiAttachment attachment = doc.getAttachment(attachmentName);
if (attachment == null) {
attachment = new XWikiAttachment();
doc.getAttachmentList().add(attachment);
doc.setComment("Add new attachment " + attachmentName);
} else {
doc.setComment("Update attachment " + attachmentName);
}
attachment.setContent(attachmentData);
attachment.setFilename(attachmentName);
attachment.setAuthor(getCurrentUser());
attachment.setDoc(doc);
doc.setAuthor(getCurrentUser());
if (doc.isNew()) {
doc.setCreator(getCurrentUser());
}
doc.saveAttachmentContent(attachment, xcontext);
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getURL(String, String, String, String)
*/
public String getURL(String documentName, String action, String queryString, String anchor)
{
XWikiContext xcontext = getContext();
// If the document name is empty then use the current document
String computedDocumentName = documentName;
if (StringUtils.isEmpty(documentName)) {
computedDocumentName = xcontext.getDoc().getFullName();
}
return xcontext.getWiki().getURL(computedDocumentName, action, queryString, anchor, xcontext);
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getAttachmentURL(String, String)
* @deprecated use {@link #getAttachmentURL(AttachmentName)} instead
*/
public String getAttachmentURL(String documentName, String attachmentName)
{
XWikiContext xcontext = getContext();
String attachmentURL;
try {
attachmentURL = xcontext.getWiki().getAttachmentURL(
documentName == null ? xcontext.getDoc().getFullName() : documentName, attachmentName, xcontext);
} catch (XWikiException e) {
// This cannot happen. There's a bug in the definition of XWiki.getAttachmentURL: it says it can generate
// an exception but in fact no exception is raised in the current implementation.
throw new RuntimeException("Failed to get attachment URL", e);
}
return attachmentURL;
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getAttachmentURL(AttachmentName, boolean)
* @since 2.0RC1
*/
public String getAttachmentURL(AttachmentName attachmentName, boolean isFullURL)
{
String url;
if (isFullURL) {
XWikiContext xcontext = getContext();
url = xcontext.getURLFactory().createAttachmentURL(attachmentName.getFileName(),
attachmentName.getDocumentName().getSpace(), attachmentName.getDocumentName().getPage(),
"download", null, attachmentName.getDocumentName().getWiki(), xcontext).toString();
} else {
url = getAttachmentURL(this.documentNameSerializer.serialize(attachmentName.getDocumentName()),
attachmentName.getFileName());
}
return url;
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getAttachmentURLs(DocumentName, boolean)
* @since 2.0RC1
*/
public List<String> getAttachmentURLs(DocumentName documentName, boolean isFullURL) throws Exception
{
List<String> urls = new ArrayList<String>();
XWikiContext xcontext = getContext();
DocumentName resolvedName = documentName;
if (documentName == null) {
resolvedName = this.documentNameFactory.createDocumentName(xcontext.getDoc().getFullName());
}
List<XWikiAttachment> attachments = xcontext.getWiki().getDocument(
this.documentNameSerializer.serialize(resolvedName), xcontext).getAttachmentList();
for (XWikiAttachment attachment : attachments) {
urls.add(getAttachmentURL(new AttachmentName(resolvedName, attachment.getFilename()), isFullURL));
}
return urls;
}
/**
* {@inheritDoc}
*
* @see org.xwiki.bridge.DocumentAccessBridge#isDocumentViewable(java.lang.String)
*/
public boolean isDocumentViewable(String documentName)
{
return hasRight(documentName, "view");
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#isDocumentEditable(String)
*/
public boolean isDocumentEditable(String documentName)
{
return hasRight(documentName, "edit");
}
/**
* {@inheritDoc}
*
* @see org.xwiki.bridge.DocumentAccessBridge#hasProgrammingRights()
*/
public boolean hasProgrammingRights()
{
XWikiContext xcontext = getContext();
return xcontext.getWiki().getRightService().hasProgrammingRights(xcontext.getDoc(), xcontext);
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getCurrentUser()
*/
public String getCurrentUser()
{
return getContext().getUser();
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#getDefaultEncoding()
*/
public String getDefaultEncoding()
{
return getContext().getWiki().getEncoding();
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#popDocumentFromContext(Map)
*/
public void popDocumentFromContext(Map<String, Object> backupObjects)
{
XWikiDocument.restoreContext(backupObjects, getContext());
}
/**
* {@inheritDoc}
*
* @see DocumentAccessBridge#pushDocumentInContext(Map, String)
*/
public void pushDocumentInContext(Map<String, Object> backupObjects, String documentName) throws Exception
{
XWikiContext xcontext = getContext();
XWikiDocument.backupContext(backupObjects, xcontext);
xcontext.getWiki().getDocument(documentName, xcontext).setAsContextDoc(xcontext);
}
/**
* Utility method for checking access rights of the current user on a target document.
*
* @param documentName The name of the document.
* @param right Access right requested.
* @return True if the current user has the given access right, false otherwise.
*/
private boolean hasRight(String documentName, String right)
{
boolean hasRight = false;
XWikiContext xcontext = getContext();
try {
hasRight =
xcontext.getWiki().getRightService().hasAccessLevel(right, xcontext.getUser(), documentName, xcontext);
} catch (XWikiException e) {
// Do nothing
}
return hasRight;
}
/**
* Utility method for saving an {@link XWikiDocument}. This method takes care of setting authors and creators
* appropriately.
*
* @param doc the {@link XWikiDocument} to be saved.
* @param comment the edit comment.
* @param isMinorEdit if the change in document is minor.
* @throws Exception if an error occurs while saving the document.
*/
private void saveDocument(XWikiDocument doc, String comment, boolean isMinorEdit) throws Exception
{
doc.setAuthor(getCurrentUser());
if (doc.isNew()) {
doc.setCreator(getCurrentUser());
}
getContext().getWiki().saveDocument(doc, comment, isMinorEdit, getContext());
}
}
|
package info.novatec.inspectit.cmr.service.rest;
import info.novatec.inspectit.cmr.model.PlatformIdent;
import info.novatec.inspectit.cmr.service.IGlobalDataAccessService;
import info.novatec.inspectit.cmr.service.rest.error.JsonError;
import info.novatec.inspectit.cmr.util.AgentStatusDataProvider;
import info.novatec.inspectit.communication.data.cmr.AgentStatusData;
import info.novatec.inspectit.communication.data.cmr.AgentStatusData.AgentConnection;
import info.novatec.inspectit.exception.BusinessException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Simon Becker
*
*/
@Controller
@RequestMapping(value = "/agentdata")
public class AgentDataRestfulService {
/**
* Reference to the existing {@link IGlobalDataAccessService}.
*/
@Autowired
private IGlobalDataAccessService globalDataAccessService;
/**
* {@link AgentStatusDataProvider}.
*/
@Autowired
AgentStatusDataProvider agentStatusProvider;
@RequestMapping(method = RequestMethod.GET, value = "overview")
@ResponseBody
public Map<PlatformIdent, AgentStatusData> getAgentsOverview() {
return globalDataAccessService.getAgentsOverview();
}
@RequestMapping(method = RequestMethod.GET, value = "myOverview")
@ResponseBody
// returns Map like this one: {"tomcat":"CONNECTED","jetty":"DISCONNECTED"}
public Map<String, AgentStatusData.AgentConnection> getMyAgentsOverview() {
Map<PlatformIdent, AgentStatusData> agentsOverviewMap = getAgentsOverview();
Map<String, AgentStatusData.AgentConnection> agentsMap = new HashMap<String, AgentStatusData.AgentConnection>();
for (PlatformIdent platformIdent : agentsOverviewMap.keySet()) {
agentsMap.put(platformIdent.getAgentName(), agentsOverviewMap.get(platformIdent).getAgentConnection());
}
return agentsMap;
}
/**
* Returns complete Agent Data
* <p>
*
* <i> Example URL: /agentdata/get-complete-agent?id=30</i>
*
* @param id
* @return
* @throws BusinessException
* @throws ServiceException
*/
@RequestMapping(method = RequestMethod.GET, value = "get-complete-agent")
@ResponseBody
public PlatformIdent getCompleteAgent(@RequestParam(value = "id", required = true) long id) throws BusinessException {
return globalDataAccessService.getCompleteAgent(id);
}
/**
* Handling of all the exceptions happening in this controller.
*
* @param exception
* Exception being thrown
* @return {@link ModelAndView}
*/
@ExceptionHandler(Exception.class)
public ModelAndView handleAllException(Exception exception) {
return new JsonError(exception).asModelAndView();
}
}
|
package com.irina.xcep;
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.irina.xcep.adapters.MenuAdapter;
import com.irina.xcep.adapters.MergeAdapter;
import com.irina.xcep.menu.navitems.NavDrawerItem;
import com.irina.xcep.menu.navitems.NavMenuItem;
import com.irina.xcep.menu.navitems.NavTitleItem;
import com.irina.xcep.utils.FragmentIndexes;
public class MenuActivity extends Activity implements MenuAdapter.SelectedListButton, AdapterView.OnItemClickListener{
public int mCurrentFragmentIndex;
private static final String CURRENT_FRAGMENT_INDEX = "current_fragment";
private DrawerLayout mDrawerLayout;
private ListView mListView;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
mTitle = this.mDrawerTitle = getTitle();
/*Setting up all views*/
initViews();
mDrawerLayout.setDrawerListener(this.mDrawerToggle);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
if (savedInstanceState == null) {
loadFragment(FragmentIndexes.FRAGMENT_HOME);
mCurrentFragmentIndex = FragmentIndexes.FRAGMENT_HOME;
mDrawerLayout.setSelected(true);
} else {
mCurrentFragmentIndex = savedInstanceState.getInt(CURRENT_FRAGMENT_INDEX);
loadFragment(mCurrentFragmentIndex);
mDrawerLayout.setSelected(true);
}
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayShowHomeEnabled(true);
}
/**
* method use to initialize all views and listeners
*/
public void initViews() {
this.mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
this.mListView = (ListView) findViewById(R.id.list_drawer);
this.mListView.setOnItemClickListener(/*OnItemClickListener*/this);
MenuAdapter menuAdapter = new MenuAdapter(this, R.layout.item_list_menu, menu,/*SelectedListButton*/this);
MergeAdapter mergeAdapter = new MergeAdapter();
mergeAdapter.addAdapter(menuAdapter);
this.mListView.setAdapter(mergeAdapter);
this.mDrawerToggle = new ActionBarDrawerToggle(MenuActivity.this,
this.mDrawerLayout, R.drawable.ic_menu_drawer,
R.string.drawer_open,
R.string.drawer_close) {
@Override
public void onDrawerClosed(View drawerView) {
getActionBar().setTitle(mTitle);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
invalidateOptionsMenu();
}
}
@Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
invalidateOptionsMenu();
}
}
};
}
/*
* @param title: action's bar title depends on current fragment
* */
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(title);
}
/*onItemClick del navigation drawer*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (((NavDrawerItem) parent.getItemAtPosition(position)).isClickable() &&
NavDrawerItem.SECTION_MENU_ITEM == ((NavDrawerItem) parent.getItemAtPosition(position)).getType()) {
loadFragment(menu[position].getId());
}
}
/*Static Navigation Drawer items*/
private NavDrawerItem[] menu = new NavDrawerItem[]{
NavTitleItem.create(100, R.string.app_name),
NavMenuItem.create(101, R.string.my_list, R.drawable.list, true, this),
NavMenuItem.create(102, R.string.catalog, R.drawable.ic_maps_store_mall_directory, true, this),
NavMenuItem.create(103, R.string.scan, R.drawable.ic_navigation_fullscreen, true, this),
NavTitleItem.create(200, R.string.setting),
NavMenuItem.create(201, R.string.facebook, R.drawable.facebook, true, this),
NavMenuItem.create(202, R.string.twitter, R.drawable.twitter, true, this),
NavMenuItem.create(203, R.string.language, R.drawable.comments, true, this),
// NavMenuItem.create(204, R.string.reset_bd, R.drawable.recycle, true, this),
NavMenuItem.create(205, R.string.help, R.drawable.help, true, this)};
public void loadFragment(int index) {
Fragment fragment = null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (index) {
case FragmentIndexes.FRAGMENT_HOME:
fragment = HomeFragment.newInstance(FragmentIndexes.FRAGMENT_HOME);
break;
case FragmentIndexes.FRAGMENT_LIST:
fragment = DetailListFragment.newInstance(FragmentIndexes.FRAGMENT_LIST);
// transaction.add(R.id.container, fragment).commit();
break;
case FragmentIndexes.FACEBOOK:
shareFacebook();
return;
case FragmentIndexes.TWITTER:
shareTwitter();
return;
// case FragmentIndexes.FRAGMENT_CATALOG:
// //fragment = QuotesFragment.newInstance(FragmentIndexes.MY_QUOTES_INDEX);
// break;
// case FragmentIndexes.FRAGMENT_SCAN:
// //fragment = QuotesFragment.newInstance(FragmentIndexes.FAVORITES_QUOTES_INDEX);
// break;
default:
Toast.makeText(this, "Funcionalidade en cosntruccin", Toast.LENGTH_LONG).show();
return;
}
//Store current index
mCurrentFragmentIndex = index;
//Add fragment to layout
transaction.replace(R.id.container, fragment).commit();
mListView.setItemChecked(index, true);
mDrawerLayout.closeDrawer(mListView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(CURRENT_FRAGMENT_INDEX,mCurrentFragmentIndex);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onSelectedButton(int type) {
}
/**
* Redes sociales
* */
public void shareFacebook(){
//FIXME actualizar enlace hacia el oficial de Xecp
String urlToShare = "https://play.google.com/store/apps/details?id=com.bandainamcogames.dbzdokkanww";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, urlToShare);
boolean facebookAppFound = false;
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana")) {
intent.setPackage(info.activityInfo.packageName);
facebookAppFound = true;
break;
}
}
if (!facebookAppFound) {
String sharerUrl = "https:
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
}
startActivity(intent);
}
public void shareTwitter(){
//FIXME actualizar enlace hacia el oficial de Xecp
String urlToShare = "https://play.google.com/store/apps/details?id=com.bandainamcogames.dbzdokkanww";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, urlToShare);
boolean twitterAppFound = false;
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
if (info.activityInfo.packageName.toLowerCase().startsWith("com.twitter")) {
intent.setPackage(info.activityInfo.packageName);
twitterAppFound = true;
break;
}
}
if (!twitterAppFound) {
urlToShare = "http://twitter.com/share?text="+urlToShare;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlToShare));
}
startActivity(intent);
}
}
|
package com.cst242.finalproject.server.model;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author James Decarlo
*/
public class FileIOTest {
public FileIOTest() {
}
/**
* Test of register method, of class FileIO.
*/
@Test
public void testRegister() {
System.out.println("register");
String loginId = "test252";
int hashedPassword = 6973;
String firstName = "Tom";
String lastName = "Jones";
String screenName = "Tom_Jones";
FileIO instance1 = new FileIO();
boolean expResult = true;
boolean result = instance1.register(loginId, hashedPassword, firstName, lastName, screenName);
assertEquals(expResult, result);
}
/**
* Test of register method, of class FileIO.
*/
@Test
public void testDuplicateRegister() {
System.out.println("duplicateRegister");
String loginId = "test232";
int hashedPassword = 6969;
String firstName = "John";
String lastName = "Doe";
String screenName = "sir_john_doe";
FileIO instance = new FileIO();
boolean expResult = false;
boolean result = instance.register(loginId, hashedPassword, firstName, lastName, screenName);
assertEquals(expResult, result);
}
/**
* Test of loginUser method, of class FileIO.
*/
@Test
public void testLoginUser() {
System.out.println("loginUser");
String loginId = "unknown";
int hashedPassword = 0;
FileIO instance = new FileIO();
User expResult = null;
User result = instance.loginUser(loginId, hashedPassword);
assertEquals(expResult, result);
loginId = "test212";
hashedPassword = 6969;
if(instance.loginUser(loginId, hashedPassword) == null){
fail("Login Failed");
}
}
/**
* Test of updateUser method, of class FileIO.
*/
@Test
public void testUpdateUser() {
System.out.println("updateUser");
User user = new FileIO().loginUser("test212", 6969);
if(user == null){
fail("Failed to login user");
}
int accountNumber = user.getAccountNumber();
int hashedPassword = 6969;
String firstName = "Jane";
String lastName = "Doe";
String screenName = "Jane_Doe";
FileIO instance = new FileIO();
boolean expResult = true;
boolean result = instance.updateUser(accountNumber, hashedPassword, firstName, lastName, screenName);
assertEquals(expResult, result);
user = new FileIO().loginUser("test212", 6969);
if(!firstName.equals(user.getFirstName()) || !screenName.equals(user.getScreenName())){
fail("Failed to update the user");
}
}
}
|
package simpledb;
import java.io.*;
import java.util.*;
public interface DbIterator extends Serializable {
/**
* Opens the iterator. This must be called before any of the other methods.
*
* @throws DbException
* when there are problems opening/accessing the database.
*/
public void open() throws DbException, TransactionAbortedException;
public boolean hasNext() throws DbException, TransactionAbortedException;
public Tuple next() throws DbException, TransactionAbortedException, NoSuchElementException;
public void rewind() throws DbException, TransactionAbortedException;
/**
* Returns the TupleDesc associated with this DbIterator.
*
* @return the TupleDesc associated with this DbIterator.
*/
public TupleDesc getTupleDesc();
public void close();
public DbIterator[] getChildren();
public default double error(DbIterator actual) throws DbException, TransactionAbortedException {
double err = 0.0;
while (hasNext()) {
try {
if (actual.hasNext()) {
err += next().error(actual.next());
// throw new RuntimeException("BUG: Iterators have different
// lengths.");
} else {
err += next().error();
}
} catch (NoSuchElementException e) {
throw new RuntimeException("BUG: No more tuples.");
}
}
return err;
}
public default void print(PrintStream strm) throws DbException, TransactionAbortedException {
while (hasNext()) {
strm.println(next());
}
}
public default void print() throws DbException, TransactionAbortedException {
print(System.out);
}
public default boolean contains(Class<?> op) {
if (op.isInstance(this)) {
return true;
}
for (DbIterator child : getChildren()) {
if (child.contains(op)) {
return true;
}
}
return false;
}
}
|
package ru.job4j.array;
/**
* Class Turn.
* @author Alexey Rastorguev (rastorguev00@gmail.com)
* @version $1d$
* @since 24.09.2017
*/
public class Turn {
public int[] back(int[] array) {
int arraySize = array.length;
int sizeMass = (arraySize % 2 == 0) ? (array.length / 2) : ((array.length - 1) / 2);
int finish = array.length - 1;
for (int i = 0; i < sizeMass; i++) {
int temp = array[i];
array[i] = array[finish];
array[finish--] = temp;
}
return array;
}
}
|
package tatai;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TataiController {
// Stage to swap scenes in and out of.
private Stage _stage = null;
// Scenes.
private TataiLoader _loader;
// Current level.
private int _level = 0;
// Total number of questions.
final static private int NUM_QUESTIONS = 10;
// Current question number up to.
private int _currentQuestionNumber = 0;
// Number of correct answers this level.
private int _numCorrect = 0;
// Number of previous attempts.
private int _tries = 0;
// Player.
private MediaPlayer _mediaPlayer;
// Filename.
final static private String FILENAME = "recording.mp3";
// Filename.
final static private String FILENAMEBASE = "recording";
// List of statistics.
private List<TataiStatistic> _statistics = new ArrayList<TataiStatistic>();
// Statistics table to update.
private TableView<TataiStatistic> _table = new TableView<TataiStatistic>();
// Number that user has to pronounce in Maori
private int _numToSay = 0;
// Boolean to determine if sounds should stop loading. If not on the same page as it was when it started loading, it will not play the sound.
private boolean _samePage = true;
@FXML private Text number;
@FXML private Button recordButton;
@FXML private Button returnButton;
@FXML private Button redoButton;
@FXML private Button playButton;
@FXML private Button nextButton;
@FXML private Text announceRight;
@FXML private Text announceWrong;
@FXML private Text announceRecording;
@FXML private Text numberCorrect;
@FXML private Button nextLevelButton;
@FXML private HBox statsPanel;
@FXML private Text questionNumber;
@FXML private ProgressBar progressBar;
@FXML private ImageView imageRight;
@FXML private ImageView imageWrong;
@FXML private BorderPane root;
public TataiController(Stage stage) {
_stage = stage;
_loader = new TataiLoader(this);
}
// Executes some bash command received as an argument.
private List<String> executeCommand(String cmd) {
// Read output from the bash.
List<String> output = new ArrayList<>();
ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", cmd);
try {
Process process = builder.start();
InputStream stdout = process.getInputStream();
BufferedReader stdoutBuffered = new BufferedReader(new InputStreamReader(stdout));
String line = null;
while ((line = stdoutBuffered.readLine()) != null ) {
output.add(line);
}
} catch (Exception e) {
}
return output;
}
public void init() {
// Initialize the statistics page with a table.
ObservableList<TataiStatistic> data = FXCollections.observableArrayList(_statistics);
TableColumn timeCol = new TableColumn("Time completed");
timeCol.setMinWidth(195);
timeCol.setCellValueFactory(new PropertyValueFactory<TataiStatistic,String>("time"));
TableColumn scoreCol = new TableColumn("Score");
scoreCol.setMinWidth(95);
scoreCol.setCellValueFactory(new PropertyValueFactory<TataiStatistic,String>("score"));
TableColumn levelCol = new TableColumn("Level");
levelCol.setMinWidth(195);
levelCol.setCellValueFactory(new PropertyValueFactory<TataiStatistic,String>("level"));
_table.setItems(data);
_table.getColumns().addAll(timeCol, scoreCol, levelCol);
// Add placeholder text while empty.
_table.setPlaceholder(new Label("No scores to display."));
// Prevent horizontal scrollbars.
_table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// Add the table to the panel.
statsPanel.getChildren().addAll(_table);
// Show menu.
Scene scene = _loader.getScene("menu");
_stage.setTitle("Welcome to Tatai!");
_stage.setScene(scene);
_stage.show();
}
@FXML protected void showLevel1(ActionEvent event) {
_level = 1;
initLevel();
}
@FXML protected void showLevel2(ActionEvent event) {
_level = 2;
initLevel();
}
private void initLevel() {
_numCorrect = 0;
_currentQuestionNumber = 1;
_tries = 0;
showLevel();
}
@FXML protected void showMenu(ActionEvent event) {
stopSound();
Scene scene = _loader.getScene("menu");
_stage.setScene(scene);
_stage.show();
}
@FXML protected void record(ActionEvent event) {
// Hide recording button, show recording dialog.
minimizeButtons();
announceRecording.setVisible(true);
announceRecording.setManaged(true);
// Ensure GUI concurrency by doing in background
Task<Void> task = new Task<Void>() {
@Override public Void call(){
// Remove any previous recording files so overwrite prompt doesn't hold up thread
executeCommand("rm "+FILENAMEBASE+".wav ");
executeCommand("rm "+FILENAMEBASE+".mp3 ");
// Record the user with ffmpeg.
executeCommand("ffmpeg -f alsa -ar 22050 -i default -loglevel quiet -t 3 "+FILENAMEBASE+".wav ");
// Run HVite and write output to file
executeCommand("mv " + FILENAMEBASE + ".wav /home/se206/Documents/HTK/MaoriNumbers/");
executeCommand("cd /home/se206/Documents/HTK/MaoriNumbers/; HVite -H HMMs/hmm15/macros -H HMMs/hmm15/hmmdefs -C user/configLR -w user/wordNetworkNum -o SWT -l '*' -i recout.mlf -p 0.0 -s 5.0 user/dictionaryD user/tiedList " + FILENAMEBASE + ".wav ");
// convert wav file to mp3
executeCommand("cd -; ffmpeg -loglevel quiet -i "+FILENAMEBASE+".wav -f mp3 "+FILENAMEBASE+".mp3");
return null;
}
};
new Thread(task).start();
// When recording has finished:
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent t) {
minimizeButtons();
// TODO Process here.
// Equivalent of pseudo-randomly allocating a correctness. This is only for testing while the speech recognition is being developed.
// TODO Finish speech recognition and remove this.
boolean isCorrect = _numToSay % 2 == 0;
// If correct, hide the redo button and increase the number correct.
if (isCorrect) {
_numCorrect++;
announceRight.setVisible(true);
announceRight.setManaged(true);
imageRight.setVisible(true);
imageRight.setManaged(true);
root.setStyle("-fx-background-color:#388E3C;");
}
else {
announceWrong.setVisible(true);
announceWrong.setManaged(true);
imageWrong.setVisible(true);
imageWrong.setManaged(true);
root.setStyle("-fx-background-color:#D32F2F;");
// If this is your first time wrong, you get to try again.
if (_tries == 0) {
redoButton.setVisible(true);
redoButton.setManaged(true);
}
}
// Always show the play button and the next button and hide the record button.
// Show next button.
nextButton.setVisible(true);
nextButton.setManaged(true);
// Show play button.
playButton.setVisible(true);
playButton.setManaged(true);
}
});
}
@FXML protected void redo(ActionEvent event) {
stopSound();
_tries++;
record(null);
}
@FXML protected void play(ActionEvent event) {
// Play audio here.
String filename = FILENAME;
// Ensure GUI concurrency by doing in background
Task<Void> task = new Task<Void>() {
@Override public Void call(){
_samePage = true;
// Create new MediaPlayer
Media sound = new Media(new File(filename).toURI().toString());
_mediaPlayer = new MediaPlayer(sound);
System.out.println("make media");
return null;
}
};
new Thread(task).start();
// When audio has finished loading.
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent t) {
if (_samePage) {
_mediaPlayer.play();
}
}
});
}
// Stop any currently playing sounds.
private void stopSound() {
_samePage = false;
if (_mediaPlayer != null) {
_mediaPlayer.stop();
}
}
@FXML protected void next(ActionEvent event) {
_tries = 0;
stopSound();
if(_currentQuestionNumber >= NUM_QUESTIONS) {
showEndLevel(_numCorrect);
}
else {
// Show the next question.
_currentQuestionNumber++;
showLevel();
}
}
// Shows the next level. Only two levels, so show level 2.
@FXML protected void nextLevel(ActionEvent event) {
showLevel2(null);
}
// Replay current level
@FXML protected void replay(ActionEvent event) {
initLevel();
}
// Function to minimize all the buttons. Show as necessary.
private void minimizeButtons() {
// Hide redo button.
redoButton.setVisible(false);
redoButton.setManaged(false);
// Hide next button.
nextButton.setVisible(false);
nextButton.setManaged(false);
// Hide play button.
playButton.setVisible(false);
playButton.setManaged(false);
recordButton.setVisible(false);
recordButton.setManaged(false);
// Hide announcements.
announceRight.setVisible(false);
announceRight.setManaged(false);
announceRecording.setVisible(false);
announceRecording.setManaged(false);
announceWrong.setVisible(false);
announceWrong.setManaged(false);
// Hide images.
imageRight.setVisible(false);
imageRight.setManaged(false);
imageWrong.setVisible(false);
imageWrong.setManaged(false);
}
// Show a question for this level.
private void showLevel() {
stopSound();
Scene scene = _loader.getScene("level");
// Hide all buttons.
minimizeButtons();
// Reset colour of background.
root.setStyle("-fx-background-color:#37474F;");
// Show record button
recordButton.setVisible(true);
recordButton.setManaged(true);
// Question setup here.
_numToSay = generateNum(); // generate number to test for current question
number.setText(Integer.toString(_numToSay)); // edit display text for number to say
// Show progress bar.
progressBar.setProgress((float) _currentQuestionNumber/NUM_QUESTIONS);
// Show question number.
questionNumber.setText(Integer.toString(_currentQuestionNumber) + "/" + Integer.toString(NUM_QUESTIONS));
_stage.setScene(scene);
_stage.show();
}
private void showEndLevel(int numCorrect) {
// If on level 1 and number correct is greater than or equal to 8, show next level button, else hide it
if (_level == 1 && numCorrect >= 8) {
nextLevelButton.setVisible(true);
nextLevelButton.setManaged(true);
}
else {
nextLevelButton.setVisible(false);
nextLevelButton.setManaged(false);
}
// Show number correct.
numberCorrect.setText(Integer.toString(numCorrect) + "/" + NUM_QUESTIONS);
// Create a new TataiStatistic entry.
TataiStatistic entry = new TataiStatistic(numCorrect, _level);
// Add it to the statistics list.
_statistics.add(entry);
Scene scene = _loader.getScene("endlevel");
_stage.setScene(scene);
_stage.show();
}
@FXML private void showStatistics() {
ObservableList<TataiStatistic> data = FXCollections.observableArrayList(_statistics);
_table.setItems(data);
Scene scene = _loader.getScene("statistics");
_stage.setScene(scene);
_stage.show();
}
@FXML protected void quit() {
Platform.exit();
}
private int generateNum() {
// define Random object and boundaries for random number generation
Random rand = new Random();
int upperLimit = 1;
int lowerLimit = 1;
// if on level 1, set upper boundary to 9
if (_level == 1) {
upperLimit = 9;
} // if level 2, set upper boundary to 99
else if (_level == 2) {
upperLimit = 99;
}
// return randomly generated integer within boundaries (inclusive)
return rand.nextInt(upperLimit) + lowerLimit;
}
}
|
package org.voovan.db;
import org.voovan.tools.TObject;
import org.voovan.tools.TSQL;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import javax.sql.DataSource;
import java.sql.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class JdbcOperate {
private static Map<Long, JdbcOperate> JDBCOPERATE_THREAD_LIST = new ConcurrentHashMap<Long, JdbcOperate>();
private DataSource dataSource;
private Connection connection;
private TranscationType transcationType;
private Savepoint savepoint = null;
private List<JdbcOperate> bindedJdbcOperate = new ArrayList<JdbcOperate>();
private boolean isTransactionFinished = false;
/**
*
* @param dataSource
*/
public JdbcOperate(DataSource dataSource) {
this.dataSource = dataSource;
this.transcationType = TranscationType.NONE;
}
/**
*
* @param dataSource
* @param isTrancation , `NEST`()
*/
public JdbcOperate(DataSource dataSource,boolean isTrancation){
this.dataSource = dataSource;
this.transcationType = (isTrancation? TranscationType.NEST : TranscationType.NONE);
}
/**
*
* @param dataSource
* @param transcationType ,
*/
public JdbcOperate(DataSource dataSource,TranscationType transcationType){
this.dataSource = dataSource;
this.transcationType = transcationType;
}
/**
*
* TranscationType NEST
* @param subJdbcOperate
* @param bothway true: , false: ,
* commit rollback , ,
* @return true: , false:
*/
public synchronized boolean addBind(JdbcOperate subJdbcOperate, boolean bothway){
if(subJdbcOperate.transcationType == TranscationType.NEST) {
if(!bindedJdbcOperate.contains(subJdbcOperate)) {
if(bothway) {
subJdbcOperate.bindedJdbcOperate.add(this);
}
return bindedJdbcOperate.add(subJdbcOperate);
}
}
return false;
}
/**
*
* @param subJdbcOperate
* @param bothway true: , , : ,
* @return true: , false:
*/
public synchronized boolean removeBind(JdbcOperate subJdbcOperate, boolean bothway){
if(bothway) {
subJdbcOperate.bindedJdbcOperate.remove(this);
}
return bindedJdbcOperate.remove(subJdbcOperate);
}
/**
*
*
* @return
* @throws SQLException SQL
*/
public synchronized Connection getConnection() throws SQLException {
long threadId = Thread.currentThread().getId();
if (connection == null || connection.isClosed()) {
if (transcationType == TranscationType.NEST) {
if (JDBCOPERATE_THREAD_LIST.containsKey(threadId)) {
connection = JDBCOPERATE_THREAD_LIST.get(threadId).connection;
savepoint = connection.setSavepoint();
} else {
connection = dataSource.getConnection();
connection.setAutoCommit(false);
JDBCOPERATE_THREAD_LIST.put(threadId, this);
}
}
else if (transcationType == TranscationType.ALONE){
connection = dataSource.getConnection();
connection.setAutoCommit(false);
}
else if (transcationType == TranscationType.NONE){
connection = dataSource.getConnection();
connection.setAutoCommit(true);
}
}
return connection;
}
/**
*
* @return
*/
public TranscationType getTranscationType() {
return transcationType;
}
/**
*
* @param isClose
* @throws SQLException SQL
*/
public synchronized void commit(boolean isClose) throws SQLException {
if(connection==null){
return ;
}
for(JdbcOperate bindJdbcOperate : bindedJdbcOperate){
if(this.equals(bindJdbcOperate)) {
if(!bindJdbcOperate.isTransactionFinished) {
bindJdbcOperate.commit(isClose);
}
}
}
connection.commit();
if(isClose) {
closeConnection(connection);
}
isTransactionFinished = true;
}
/**
*
* @param isClose
* @throws SQLException SQL
*/
public synchronized void rollback(boolean isClose) throws SQLException {
if(connection==null){
return ;
}
if(savepoint!=null) {
connection.rollback(savepoint);
} else {
for(JdbcOperate bindJdbcOperate : bindedJdbcOperate){
if(this.equals(bindJdbcOperate)) {
if(!bindJdbcOperate.isTransactionFinished) {
bindJdbcOperate.rollback(isClose);
}
}
}
connection.rollback();
if(isClose) {
closeConnection(connection);
}
isTransactionFinished = true;
}
}
/**
*
* @throws SQLException SQL
*/
public void commit() throws SQLException {
commit(true);
}
/**
*
* @throws SQLException SQL
*/
public void rollback() throws SQLException {
rollback(true);
}
/**
*
* @param sqlText
* sql
* @param mapArg
*
* @return
* @throws SQLException SQL
*/
private ResultInfo baseQuery(String sqlText, Map<String, Object> mapArg) throws SQLException {
Connection conn = getConnection();
SQLException exception = null;
try {
//PreparedStatement
PreparedStatement preparedStatement = TSQL.createPreparedStatement(conn, sqlText, mapArg);
ResultSet rs = preparedStatement.executeQuery();
return new ResultInfo(rs,this);
} catch (SQLException e) {
closeConnection(conn);
Logger.error("Query execution SQL Error! \n SQL is : \n\t" + sqlText + ": \n\t " ,e);
exception = e;
}
if(exception!=null){
throw exception;
}
return null;
}
/**
*
*
* @param sqlText
* sql
* @param mapArg
*
* @return
* @throws SQLException SQL
*/
private int baseUpdate(String sqlText, Map<String, Object> mapArg) throws SQLException {
Connection conn = getConnection();
PreparedStatement preparedStatement = null;
SQLException exception = null;
try {
preparedStatement = TSQL.createPreparedStatement(conn, sqlText, mapArg);
return preparedStatement.executeUpdate();
} catch (SQLException e) {
Logger.error("Update execution SQL Error! \n SQL is :\n\t " + sqlText + "\nError is: \n\t" ,e);
exception = e;
} finally {
if (transcationType == TranscationType.NONE) {
closeConnection(preparedStatement);
}else{
if(exception!=null) {
rollback();
}
closeStatement(preparedStatement);
}
}
if(exception!=null){
throw exception;
}
return -1;
}
/**
*
*
* @param sqlText
* sql
* @param mapArgs
*
* @return SQL
* @throws SQLException SQL
*/
private int[] baseBatch(String sqlText, List<Map<String, Object>> mapArgs) throws SQLException {
Connection conn = getConnection();
PreparedStatement preparedStatement = null;
SQLException exception = null;
try {
// SQL
List<String> sqlParams = TSQL.getSqlParamNames(sqlText);
preparedStatement = (PreparedStatement) conn.prepareStatement(TSQL.preparedSql(sqlText));
if (mapArgs != null) {
for (Map<String, Object> magArg : mapArgs) {
// sqlParams preparestatement
TSQL.setPreparedParams(preparedStatement, sqlParams, magArg);
preparedStatement.addBatch();
}
}
if(Logger.isLogLevel("DEBUG")) {
Logger.fremawork("[SQL_Executed]: " + sqlText);
}
int[] result = preparedStatement.executeBatch();
return result;
} catch (SQLException e) {
Logger.error("Batch execution SQL Error! \n SQL is : \n\t" + sqlText + ":\n\t" ,e);
exception = e;
} finally {
if (transcationType == TranscationType.NONE) {
closeConnection(preparedStatement);
}else{
if(exception!=null) {
rollback();
}
closeStatement(preparedStatement);
}
}
if(exception!=null){
throw exception;
}
return new int[0];
}
private List<Object> baseCall(String sqlText, CallType[] callTypes,Map<String, Object> mapArg) throws SQLException {
Connection conn = getConnection();
CallableStatement callableStatement = null;
SQLException exception = null;
try {
callableStatement = TSQL.createCallableStatement(conn, sqlText, mapArg, callTypes);
callableStatement.executeUpdate();
List<Object> objList = TSQL.getCallableStatementResult(callableStatement);
return objList;
} catch (SQLException e) {
Logger.error("Query execution SQL Error! \n SQL is : \n\t" + sqlText + ": \n\t " ,e);
exception = e;
} finally {
if (transcationType == TranscationType.NONE) {
closeConnection(callableStatement);
}else{
if(exception!=null) {
rollback();
}
closeStatement(callableStatement);
}
}
if(exception!=null){
throw exception;
}
return null;
}
/**
*
*
* @param sqlText
* sql "::",where id=::id
* @return
* @throws SQLException SQL
*/
public int update(String sqlText) throws SQLException {
return this.baseUpdate(sqlText, null);
}
/**
* ,Object
*
* @param sqlText
* sql "::",where id=::id
* @param arg
* object
* @return SQL
* @throws ReflectiveOperationException
* @throws SQLException SQL
*/
public int update(String sqlText, Object arg) throws SQLException, ReflectiveOperationException {
if(TReflect.isBasicType(arg.getClass())){
return update(sqlText, arg, null);
}else{
Map<String, Object> paramsMap = TReflect.getMapfromObject(arg);
return this.baseUpdate(sqlText, paramsMap);
}
}
/**
* ,Map,Map
*
* @param sqlText
* sql "::",where id=::id
* @param mapArg
* map
* @return
* @throws SQLException SQL
*/
public int update(String sqlText, Map<String, Object> mapArg) throws SQLException {
return this.baseUpdate(sqlText, mapArg);
}
/**
* ,Map,Map
*
* @param sqlText
* sql "::",,1,where id=::1
* @param args
*
* @return
* @throws SQLException SQL
*/
public int update(String sqlText, Object... args) throws SQLException {
Map<String, Object> paramsMap = TObject.arrayToMap(args);
return this.baseUpdate(sqlText, paramsMap);
}
/**
* ,
*
* @param <T>
*
* @param sqlText
* sql
* @param t
*
* @return List
* @throws SQLException SQL
*/
public <T> List<T> queryObjectList(String sqlText, Class<T> t) throws SQLException{
ResultInfo resultInfo = this.baseQuery(sqlText, null);
if(resultInfo!=null){
return (List<T>) resultInfo.getObjectList(t);
}
return new ArrayList<T>();
}
/**
* ,Object
*
* @param <T>
*
* @param sqlText
* sql "::",where id=::id
* @param arg
* Object
* @param t
*
* @return List
* @throws ReflectiveOperationException
* @throws SQLException SQL
*/
public <T> List<T> queryObjectList(String sqlText, Class<T> t, Object arg) throws SQLException, ReflectiveOperationException{
if(TReflect.isBasicType(arg.getClass())){
return queryObjectList(sqlText, t, arg,null);
}else{
Map<String, Object> paramsMap = TReflect.getMapfromObject(arg);
ResultInfo resultInfo = this.baseQuery(sqlText, paramsMap);
if(resultInfo!=null){
return (List<T>) resultInfo.getObjectList(t);
}
return new ArrayList<T>();
}
}
/**
* ,map,Map
*
* @param <T>
*
* @param sqlText
* sql "::",where id=::id
* @param mapArg
* map
* @param t
*
* @return List
* @throws SQLException SQL
*/
public <T> List<T> queryObjectList(String sqlText, Class<T> t, Map<String, Object> mapArg) throws SQLException {
ResultInfo resultInfo = this.baseQuery(sqlText, mapArg);
if(resultInfo!=null){
return (List<T>) resultInfo.getObjectList(t);
}
return new ArrayList<T>();
}
/**
* ,map,Map
*
* @param <T>
*
* @param sqlText
* sql "::",,1,where id=::1
* @param args
* map
* @param t
*
* @return List
* @throws SQLException SQL
*/
public <T> List<T> queryObjectList(String sqlText, Class<T> t, Object... args) throws SQLException{
Map<String, Object> paramsMap = TObject.arrayToMap(args);
ResultInfo resultInfo = this.baseQuery(sqlText, paramsMap);
if(resultInfo!=null){
return (List<T>) resultInfo.getObjectList(t);
}
return new ArrayList<T>();
}
/**
* ,
*
* @param sqlText
* sql
* @return List[Map]
* @throws SQLException SQL
*/
public List<Map<String, Object>> queryMapList(String sqlText) throws SQLException {
ResultInfo resultInfo = this.baseQuery(sqlText, null);
if(resultInfo!=null){
return resultInfo.getMapList();
}
return new ArrayList<Map<String, Object>>();
}
/**
* ,Object
*
* @param sqlText
* sql "::",where id=::id
* @param arg
* Object
* @return List[Map]
* @throws ReflectiveOperationException
* @throws SQLException SQL
*/
public List<Map<String, Object>> queryMapList(String sqlText, Object arg) throws SQLException, ReflectiveOperationException {
if(TReflect.isBasicType(arg.getClass())){
return queryMapList(sqlText, arg, null);
}else{
Map<String, Object> paramsMap = TReflect.getMapfromObject(arg);
ResultInfo resultInfo = this.baseQuery(sqlText, paramsMap);
if(resultInfo!=null){
return resultInfo.getMapList();
}
return new ArrayList<Map<String, Object>>();
}
}
/**
* ,map,Map
*
* @param sqlText
* sql "::",where id=::id
* @param mapArg
* map
* @return List[Map]
* @throws SQLException SQL
*/
public List<Map<String, Object>> queryMapList(String sqlText, Map<String, Object> mapArg) throws SQLException{
ResultInfo resultInfo = this.baseQuery(sqlText, mapArg);
if(resultInfo!=null){
return resultInfo.getMapList();
}
return new ArrayList<Map<String, Object>>();
}
/**
* ,Object
*
* @param sqlText
* sql "::",,1,where id=::1
* @param args
* Object
* @return List[Map]
* @throws SQLException SQL
*/
public List<Map<String, Object>> queryMapList(String sqlText, Object... args) throws SQLException {
Map<String, Object> paramsMap = TObject.arrayToMap(args);
ResultInfo resultInfo = this.baseQuery(sqlText, paramsMap);
if(resultInfo!=null){
return resultInfo.getMapList();
}
return new ArrayList<Map<String, Object>>();
}
/**
* ,
*
* @param <T>
*
* @param sqlText
* sql
* @param t
*
* @return List[Map]
* @throws SQLException SQL
*/
@SuppressWarnings("unchecked")
public <T> T queryObject(String sqlText, Class<T> t) throws SQLException {
ResultInfo resultInfo = this.baseQuery(sqlText, null);
if(resultInfo!=null){
return (T) resultInfo.getObject(t);
}
return null;
}
/**
* ,Object
*
* @param <T>
*
* @param sqlText
* sql "::",where id=::id
* @param t
*
* @param arg
* Object
* @return
* @throws ReflectiveOperationException
* @throws SQLException SQL
* @throws ParseException
*/
@SuppressWarnings("unchecked")
public <T> T queryObject(String sqlText, Class<T> t, Object arg) throws SQLException, ReflectiveOperationException, ParseException {
if(TReflect.isBasicType(arg.getClass())){
return queryObject(sqlText,t,arg,null);
}else{
Map<String, Object> paramsMap = TReflect.getMapfromObject(arg);
ResultInfo resultInfo = this.baseQuery(sqlText, paramsMap);
if(resultInfo!=null){
return (T) resultInfo.getObject(t);
}
return null;
}
}
/**
* ,map,Map
*
* @param <T>
*
* @param sqlText
* sql "::",where id=::id
* @param mapArg
* map
* @param t
*
* @return
* @throws SQLException SQL
*/
@SuppressWarnings("unchecked")
public <T> T queryObject(String sqlText, Class<T> t, Map<String, Object> mapArg) throws SQLException {
ResultInfo resultInfo = this.baseQuery(sqlText, mapArg);
if(resultInfo!=null){
return (T) resultInfo.getObject(t);
}
return null;
}
/**
* ,map,Map
*
* @param <T>
*
* @param sqlText
* sql "::",,1,where id=::1
* @param args
* map
* @param t
*
* @return
* @throws SQLException SQL
*/
@SuppressWarnings("unchecked")
public <T> T queryObject(String sqlText, Class<T> t, Object... args) throws SQLException{
Map<String, Object> paramsMap = TObject.arrayToMap(args);
ResultInfo resultInfo = this.baseQuery(sqlText, paramsMap);
if(resultInfo!=null){
return (T) resultInfo.getObject(t);
}
return null;
}
/**
* , Map,
*
* @param sqlText
* sql
* @return Map
* @throws SQLException SQL
*/
public Map<String, Object> queryMap(String sqlText) throws SQLException {
ResultInfo resultInfo = this.baseQuery(sqlText, null);
if(resultInfo!=null){
return resultInfo.getMap();
}
return null;
}
/**
* , Map,Object
*
* @param sqlText
* sql "::",where id=::id, id
* @param arg
* arg SQL,SQL
* @return Map
* @throws SQLException SQL
* @throws ReflectiveOperationException
*
*/
public Map<String, Object> queryMap(String sqlText, Object arg) throws SQLException, ReflectiveOperationException {
if(TReflect.isBasicType(arg.getClass())){
return queryMap(sqlText,arg,null);
}else{
Map<String, Object> paramsMap = TReflect.getMapfromObject(arg);
ResultInfo resultInfo = this.baseQuery(sqlText, paramsMap);
if(resultInfo!=null){
return resultInfo.getMap();
}
return null;
}
}
/**
* , Map,map,Map
*
* @param sqlText
* sql "::",where id=::id, id
* @param mapArg
* mapkeySQL,valueSQL
* @return Map
* @throws SQLException SQL
*/
public Map<String, Object> queryMap(String sqlText, Map<String, Object> mapArg) throws SQLException {
ResultInfo resultInfo = this.baseQuery(sqlText, mapArg);
if(resultInfo!=null){
return resultInfo.getMap();
}
return null;
}
/**
* , Map,Array
*
* @param sqlText
* sql "::",,1,where id=::1
* @param args
* args
* @return
* @throws SQLException SQL
*/
public Map<String, Object> queryMap(String sqlText, Object... args) throws SQLException {
Map<String, Object> paramsMap = TObject.arrayToMap(args);
ResultInfo resultInfo = this.baseQuery(sqlText, paramsMap);
if(resultInfo!=null){
return resultInfo.getMap();
}
return null;
}
/**
*
*
* @param sqlText
* sql "::",where id=::id
* @param objects
*
* @return SQL
* @throws SQLException SQL
* @throws ReflectiveOperationException
*/
public int[] batchObject(String sqlText, List<?> objects) throws SQLException, ReflectiveOperationException {
List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
for (Object object : objects) {
mapList.add(TReflect.getMapfromObject(object));
}
return this.baseBatch(sqlText, mapList);
}
/**
*
*
* @param sqlText sql "::",where id=::id
* @param maps SQL
* @return SQL
* @throws SQLException SQL
*/
public int[] batchMap(String sqlText, List<Map<String, Object>> maps) throws SQLException {
return this.baseBatch(sqlText, maps);
}
/**
* ,
* @param sqlText sql "::",where id=::id
* @return
* @throws SQLException SQL
*/
public List<Object> call(String sqlText) throws SQLException {
return this.baseCall(sqlText,null,null);
}
/**
* ,map,Map
*
* @param sqlText
* sql "::",where id=::id
* @param callTypes
* IN,OUT,INOUT
* @param maps
* map
* @return
* @throws SQLException SQL
*/
public List<Object> call(String sqlText, CallType[] callTypes, Map<String, Object> maps) throws SQLException {
return this.baseCall(sqlText ,callTypes ,maps);
}
/**
* ,
*
* @param sqlText
* sql "::",where id=::id
* @param callTypes
* IN,OUT,INOUT
* @param arg
*
* @return
* @throws SQLException SQL
* @throws ReflectiveOperationException
*/
public List<Object> call(String sqlText, CallType[] callTypes, Object arg) throws SQLException, ReflectiveOperationException {
if(TReflect.isBasicType(arg.getClass())){
return call(sqlText, callTypes, arg, null);
}else{
Map<String, Object> paramsMap = TReflect.getMapfromObject(arg);
return this.baseCall(sqlText,callTypes, paramsMap);
}
}
/**
* ,Array
* @param sqlText
* sql "::",where id=::id
* @param callTypes
* IN,OUT,INOUT
* @param args
*
* @return
* @throws SQLException SQL
*/
public List<Object> call(String sqlText, CallType[] callTypes, Object ... args) throws SQLException {
Map<String, Object> paramsMap = TObject.arrayToMap(args);
return this.baseCall(sqlText,callTypes, paramsMap);
}
/**
*
* @param resultSet
*/
protected static void closeConnection(ResultSet resultSet) {
try {
if (resultSet != null) {
Statement statement = resultSet.getStatement();
resultSet.close();
closeConnection(statement);
}
} catch (SQLException e) {
Logger.error(e);
}
}
/**
*
* @param statement Statement
*/
protected static void closeConnection(Statement statement) {
try {
if(statement!=null) {
Connection connection = statement.getConnection();
statement.close();
closeConnection(connection);
}
} catch (SQLException e) {
Logger.error(e);
}
}
/**
*
* @param connection
*/
private static void closeConnection(Connection connection) {
try {
if (connection != null) {
JDBCOPERATE_THREAD_LIST.remove(Thread.currentThread().getId());
connection.close();
}
} catch (SQLException e) {
Logger.error(e);
}
}
/**
*
* @param resultSet
*/
protected static void closeResult(ResultSet resultSet){
try {
if(resultSet!=null) {
Statement statement = resultSet.getStatement();
resultSet.close();
closeStatement(statement);
}
} catch (SQLException e) {
Logger.error(e);
}
}
/**
* Statement
* @param statement Statement
*/
protected static void closeStatement(Statement statement){
try {
if(statement!=null) {
statement.close();
}
} catch (SQLException e) {
Logger.error(e);
}
}
}
|
package itesla.converter;
import java.util.ArrayList;
import java.util.List;
/*
* Class representing the iPSL model that corresponds to the Eurostag device.
* idEu: each block inside the macroblock has an Eurostag id.
* nameEu: name of the block in Eurostag.
* pathModelica: path of the iPSL model that represents this block.
* nameModelica: name of the iPSL model that represents this block.
* nInputpins: number of the input pins in Modelica.
* param: name of the parameters in the Modelica model.
* @author Marc Sabate <sabatem@aia.es>
* @author Raul Viruez <viruezr@aia.es>
*/
public class Element {
public Integer idEu;
public String nameEu;
public String pathModelica;
public String nameModelica;
public List<String> param = new ArrayList<String>();
public double offset;
public double init_double;
public Integer nInputPins;
public Element(int idEu, String nameEu, String nameModelica, List<String> param, Integer nInputPins) {
this.idEu = idEu;
this.nameEu = nameEu;
this.pathModelica = nameModelica;
this.nameModelica = nameModelica.split("\\.")[nameModelica.split("\\.").length-1];
this.param = param;
this.nInputPins = nInputPins;
}
}
|
package org.skyve.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.comparator.NameFileComparator;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.skyve.content.MimeType;
import org.skyve.metadata.SortDirection;
import org.skyve.metadata.controller.DownloadAction.Download;
import org.skyve.web.WebContext;
/**
* Basic file utilities
*
* @author RB
*
*/
public class FileUtil {
public FileUtil() {
// no op
}
/**
* Return a byte array from an input stream
*
* WARNING: If the input stream is large, this may have impacts on
* performance.
*
* @param inputStream
* @return
* @throws IOException
*/
public static final byte[] getFileBytes(InputStream inputStream) throws IOException {
byte[] bytes = null;
InputStream stream = inputStream;
try {
try (BufferedInputStream bis = new BufferedInputStream(stream)) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
byte[] temp = new byte[1024];
int bytesRead = 0;
while ((bytesRead = bis.read(temp)) > 0) {
baos.write(temp, 0, bytesRead);
}
bytes = baos.toByteArray();
}
}
} finally {
stream.close();
stream = null;
}
return bytes;
}
/**
* Returns a safe filename from the unsafeName
*
* @param unsafeName
* @return
*/
public static String safeFileName(String unsafeName) {
return unsafeName.replace(',', '_').replace('&', '_').replace('/', '_').replace('\\', '_').replace(" ", "").replace(":", "_").replace("-","_");
}
/**
* Construct a safe file path and name
*
* @param safeBasePath
* @param unsafeFileName
* @param extension
* @param makeDirectories
* @param unsafeFolderNames
* @return the full filepath (and filename with extension if provided)
*/
public static String constructSafeFilePath(String safeBasePath, String unsafeFileName, String extension, boolean makeDirectories, String... unsafeFolderNames) {
StringBuilder filePath = new StringBuilder();
filePath.append(safeBasePath);
//construct subfolders as required
String separator = System.getProperty("file.separator");
if (!safeBasePath.endsWith(separator)) {
filePath.append(separator);
}
if(unsafeFolderNames!=null){
for (String folder : unsafeFolderNames) {
filePath.append(FileUtil.safeFileName(folder));
}
}
if (!filePath.toString().endsWith(separator)) {
filePath.append(separator);
}
//make directories if requested
if (makeDirectories) {
new File(filePath.toString()).mkdirs();
}
//append the file name with extension
filePath.append(safeFileName(unsafeFileName));
if (extension != null) {
if (!extension.startsWith(".")) {
filePath.append('.');
}
filePath.append(extension);
}
return filePath.toString();
}
/**
* Prepare a zip download for the directory
*
* @param directoryPath
* @param zipName
* @param webContext
* @return
* @throws IOException
*/
public static Download prepareZipDownload(String directoryPath, String zipName, WebContext webContext)
throws IOException {
try (ByteArrayOutputStream out = new ByteArrayOutputStream(20480)) {
File backupDir = new File(directoryPath);
createZipArchive(backupDir, out);
return new Download(zipName, new ByteArrayInputStream(out.toByteArray()), MimeType.zip);
}
}
/**
* Create a zip archive for the directory
*
* @param directory
* @param zip The archive file.
* @throws IOException
*/
public static void createZipArchive(File directory, File zip)
throws IOException {
try (FileOutputStream fos = new FileOutputStream(zip)) {
createZipArchive(directory, fos);
}
}
/**
* Create a zip archive for the directory.
*
* @param directory
* @param out
* @throws IOException
*/
public static void createZipArchive(File directory, OutputStream out) throws IOException {
if (directory.exists() && directory.isDirectory()) {
try (ZipOutputStream zos = new ZipOutputStream(out)) {
List<File> fileList = new ArrayList<>();
getAllFiles(directory, fileList);
for (File file : fileList) {
if (! file.isDirectory()) { // we only zip files, not directories
addToZip(directory, file, zos);
}
}
zos.flush();
}
}
out.flush();
}
/**
* Get all files from a directory recursively.
*
* @param dir
* @param fileList
*/
private static void getAllFiles(File dir, List<File> fileList) {
File[] files = dir.listFiles();
for (File file : files) {
fileList.add(file);
if (file.isDirectory()) {
getAllFiles(file, fileList);
}
}
}
/**
* Add a file within a directory to a zip file.
*
* @param directoryToZip
* @param file
* @param zos
* @throws FileNotFoundException
* @throws IOException
*/
public static void addToZip(File directoryToZip, File file, ZipOutputStream zos)
throws FileNotFoundException, IOException {
try (FileInputStream fis = new FileInputStream(file)) {
// we want the zipEntry's path to be a relative path that is relative
// to the directory being zipped, so chop off the rest of the path
String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
file.getCanonicalPath().length());
zipFilePath = zipFilePath.replace('\\', '/');
Util.LOGGER.info(String.format("Writing '%s' to zip file", zipFilePath));
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length = 0;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
}
}
private static void extractFile(ZipInputStream in, File outdir, String name)
throws IOException {
File file = new File(outdir, name);
Util.LOGGER.info(String.format("Writing '%s' from zip file to %s", name, file));
try (FileOutputStream fos = new FileOutputStream(file)) {
try (BufferedOutputStream out = new BufferedOutputStream(fos)) {
byte[] bytes = new byte[1024];
int length = 0;
while ((length = in.read(bytes)) >= 0) {
out.write(bytes, 0, length);
}
}
}
}
private static void mkdirs(File outdir, String path) {
File d = new File(outdir, path);
if (! d.exists()) {
d.mkdirs();
}
}
private static String dirpart(String name) {
int s = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'));
return (s == -1) ? null : name.substring( 0, s );
}
/**
* Extract zipfile to outdir with complete directory structure
*
* @param zipfile Input .zip file
* @param outdir Output directory
*/
public static void extractZipArchive(File zipfile, File outdir)
throws IOException {
outdir.mkdirs();
try (FileInputStream fis = new FileInputStream(zipfile)) {
try (ZipInputStream zin = new ZipInputStream(fis)) {
ZipEntry entry = null;
while ((entry = zin.getNextEntry()) != null) {
String name = entry.getName();
if (entry.isDirectory()) {
mkdirs(outdir, name);
Util.LOGGER.info("create dir " + name);
continue;
}
/* this part is necessary because file entry can come before
* directory entry where is file located
* i.e.:
* /foo/foo.txt
* /foo/
*/
String dir = dirpart(name);
if (dir != null) {
mkdirs(outdir, dir);
Util.LOGGER.info("create dir " + name);
}
extractFile(zin, outdir, name);
}
}
}
}
/**
* Delete file with exception if unsuccessful
*
* @param f The file to delete
* @throws IOException
*/
public static void delete(File f) throws IOException {
if (f.isDirectory()) {
for (File c : f.listFiles()) {
delete(c);
}
}
if (! f.delete()) {
throw new IOException(f.getAbsolutePath() + " was not deleted");
}
}
/**
* Copy the src file to the dest file, overwriting if necessary.
* @param src
* @param dest
* @throws IOException
*/
public static void copy(File src, File dest) throws IOException {
FileUtils.copyFile(src, dest);
}
/**
* List files (non-recursive) for a directory.
* @param dir The directory to list for.
* @param regexPattern File pattern to match, or null for all files
* @param direction If defined, perform a case insensitive sort by the file name (not the whole path).
* @return The files.
*/
public static File[] listFiles(File dir, String regexPattern, SortDirection direction) {
File[] files = (regexPattern == null) ?
dir.listFiles() :
dir.listFiles((FilenameFilter) new RegexFileFilter(regexPattern));
if (files != null) {
if (SortDirection.ascending.equals(direction)) {
Arrays.sort(files, NameFileComparator.NAME_INSENSITIVE_COMPARATOR);
}
else if (SortDirection.descending.equals(direction)) {
Arrays.sort(files, NameFileComparator.NAME_INSENSITIVE_REVERSE);
}
}
return files;
}
}
|
package org.slf4j;
import java.io.Closeable;
import java.util.Map;
import org.slf4j.helpers.NOPMDCAdapter;
import org.slf4j.helpers.BasicMDCAdapter;
import org.slf4j.helpers.Util;
import org.slf4j.impl.StaticMDCBinder;
import org.slf4j.spi.MDCAdapter;
public class MDC {
static final String NULL_MDCA_URL = "http://www.slf4j.org/codes.html#null_MDCA";
static final String NO_STATIC_MDC_BINDER_URL = "http://www.slf4j.org/codes.html#no_static_mdc_binder";
static MDCAdapter mdcAdapter;
/**
* An adapter to remove the key when done.
*/
public static class MDCCloseable implements Closeable {
private final String key;
private MDCCloseable(String key) {
this.key = key;
}
public void close() {
MDC.remove(this.key);
}
}
private MDC() {
}
static {
try {
mdcAdapter = StaticMDCBinder.SINGLETON.getMDCA();
} catch (NoClassDefFoundError ncde) {
mdcAdapter = new NOPMDCAdapter();
String msg = ncde.getMessage();
if (msg != null && msg.indexOf("StaticMDCBinder") != -1) {
Util.report("Failed to load class \"org.slf4j.impl.StaticMDCBinder\".");
Util.report("Defaulting to no-operation MDCAdapter implementation.");
Util.report("See " + NO_STATIC_MDC_BINDER_URL + " for further details.");
} else {
throw ncde;
}
} catch (Exception e) {
// we should never get here
Util.report("MDC binding unsuccessful.", e);
}
}
public static void put(String key, String val)
throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException("key parameter cannot be null");
}
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
mdcAdapter.put(key, val);
}
public static MDCCloseable putCloseable(String key, String val)
throws IllegalArgumentException {
put(key, val);
return new MDCCloseable(key);
}
public static String get(String key) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException("key parameter cannot be null");
}
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
return mdcAdapter.get(key);
}
public static void remove(String key) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException("key parameter cannot be null");
}
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
mdcAdapter.remove(key);
}
/**
* Clear all entries in the MDC of the underlying implementation.
*/
public static void clear() {
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
mdcAdapter.clear();
}
/**
* Return a copy of the current thread's context map, with keys and values of
* type String. Returned value may be null.
*
* @return A copy of the current thread's context map. May be null.
* @since 1.5.1
*/
public static Map<String, String> getCopyOfContextMap() {
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
return mdcAdapter.getCopyOfContextMap();
}
/**
* Set the current thread's context map by first clearing any existing map and
* then copying the map passed as parameter. The context map passed as
* parameter must only contain keys and values of type String.
*
* @param contextMap
* must contain only keys and values of type String
* @since 1.5.1
*/
public static void setContextMap(Map<String, String> contextMap) {
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
mdcAdapter.setContextMap(contextMap);
}
/**
* Returns the MDCAdapter instance currently in use.
*
* @return the MDcAdapter instance currently in use.
* @since 1.4.2
*/
public static MDCAdapter getMDCAdapter() {
return mdcAdapter;
}
}
|
package org.jetel.component;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.BufferOverflowException;
import org.jetel.graph.*;
import org.jetel.data.DataRecord;
import org.jetel.data.SortDataRecordInternal;
import org.jetel.data.Defaults;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.util.ComponentXMLAttributes;
/**
* <h3>Sort Component</h3>
*
* <!-- Sorts the incoming records based on specified key -->
*
* <table border="1">
* <th>Component:</th>
* <tr><td><h4><i>Name:</i></h4></td>
* <td>Sort</td></tr>
* <tr><td><h4><i>Category:</i></h4></td>
* <td></td></tr>
* <tr><td><h4><i>Description:</i></h4></td>
* <td>Sorts the incoming records based on specified key.<br>
* The key is name (or combination of names) of field(s) from input record.
* The sort order is either Ascending (default) or Descending.</td></tr>
* <tr><td><h4><i>Inputs:</i></h4></td>
* <td>[0]- input records</td></tr>
* <tr><td><h4><i>Outputs:</i></h4></td>
* <td>At least one connected output port.</td></tr>
* <tr><td><h4><i>Comment:</i></h4></td>
* <td></td></tr>
* </table>
* <br>
* <table border="1">
* <th>XML attributes:</th>
* <tr><td><b>type</b></td><td>"SORT"</td></tr>
* <tr><td><b>id</b></td><td>component identification</td>
* <tr><td><b>sortKey</b></td><td>field names separated by :;| {colon, semicolon, pipe}</td>
* <tr><td><b>sortOrder</b><br><i>optional</i></td><td>one of "Ascending|Descending" {the fist letter is sufficient, if not defined, then Ascending}</td>
* </tr>
* </table>
*
* <h4>Example:</h4>
* <pre><Node id="SORT_CUSTOMER" type="SORT" sortKey="Name:Address" sortOrder="A"/></pre>
*
* @author dpavlis
* @since April 4, 2002
* @revision $Revision$
*/
public class Sort extends Node {
/** Description of the Field */
public final static String COMPONENT_TYPE = "SORT";
private final static int WRITE_TO_PORT = 0;
private final static int READ_FROM_PORT = 0;
private SortDataRecordInternal sorter;
private boolean sortOrderAscending;
private String[] sortKeys;
private ByteBuffer recordBuffer;
/**
*Constructor for the Sort object
*
* @param id Description of the Parameter
* @param sortKeys Description of the Parameter
* @param sortOrder Description of the Parameter
*/
public Sort(String id, String[] sortKeys, boolean sortOrder) {
super(id);
this.sortOrderAscending = sortOrder;
this.sortKeys = sortKeys;
}
/**
*Constructor for the Sort object
*
* @param id Description of the Parameter
* @param sortKeys Description of the Parameter
*/
public Sort(String id, String[] sortKeys) {
super(id);
this.sortOrderAscending = true;// default ascending
this.sortKeys = sortKeys;
}
/**
* Gets the Type attribute of the SimpleCopy object
*
* @return The Type value
* @since April 4, 2002
*/
public String getType() {
return COMPONENT_TYPE;
}
/**
* Main processing method for the SimpleCopy object
*
* @since April 4, 2002
*/
public void run() {
InputPort inPort = getInputPort(READ_FROM_PORT);
DataRecord inRecord = new DataRecord(inPort.getMetadata());
inRecord.init();
while (inRecord != null && runIt) {
try {
inRecord = inPort.readRecord(inRecord);// readRecord(READ_FROM_PORT,inRecord);
if (inRecord != null) {
sorter.put(inRecord);
}
} catch (BufferOverflowException ex) {
resultMsg = "Buffer Overflow";
resultCode = Node.RESULT_ERROR;
closeAllOutputPorts();
return;
} catch (IOException ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_ERROR;
closeAllOutputPorts();
return;
} catch (Exception ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_FATAL_ERROR;
//closeAllOutputPorts();
return;
}
}
// sort the records now
try {
sorter.sort();
} catch (Exception ex) {
resultMsg = "Error when sorting: " + ex.getMessage();
resultCode = Node.RESULT_FATAL_ERROR;
//closeAllOutputPorts();
return;
}
// we read directly into buffer so we don't waste time with deserialization of record
// it will happen if needed on the other side
recordBuffer.clear();
while (sorter.getNext(recordBuffer) && runIt) {
try {
writeRecordBroadcastDirect(recordBuffer);
recordBuffer.clear();
} catch (IOException ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_ERROR;
closeAllOutputPorts();
return;
} catch (Exception ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_FATAL_ERROR;
//closeAllOutputPorts();
return;
}
}
broadcastEOF();
if (runIt) {
resultMsg = "OK";
} else {
resultMsg = "STOPPED";
}
resultCode = Node.RESULT_OK;
}
/**
* Sets the sortOrderAscending attribute of the Sort object
*
* @param ascending The new sortOrderAscending value
*/
public void setSortOrderAscending(boolean ascending) {
sortOrderAscending = ascending;
}
/**
* Description of the Method
*
* @exception ComponentNotReadyException Description of the Exception
* @since April 4, 2002
*/
public void init() throws ComponentNotReadyException {
// test that we have at least one input port and one output
if (inPorts.size() < 1) {
throw new ComponentNotReadyException("At least one input port has to be defined!");
} else if (outPorts.size() < 1) {
throw new ComponentNotReadyException("At least one output port has to be defined!");
}
recordBuffer = ByteBuffer.allocateDirect(Defaults.Record.MAX_RECORD_SIZE);
if (recordBuffer == null) {
throw new ComponentNotReadyException("Can NOT allocate internal record buffer ! Required size:" +
Defaults.Record.MAX_RECORD_SIZE);
}
sorter = new SortDataRecordInternal(getInputPort(READ_FROM_PORT).getMetadata(), sortKeys, sortOrderAscending);
}
/**
* Description of the Method
*
* @return Description of the Returned Value
* @since May 21, 2002
*/
public org.w3c.dom.Node toXML() {
// TODO
return null;
}
/**
* Description of the Method
*
* @param nodeXML Description of Parameter
* @return Description of the Returned Value
* @since May 21, 2002
*/
public static Node fromXML(org.w3c.dom.Node nodeXML) {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML);
Sort sort;
try {
sort = new Sort(xattribs.getString("id"),
xattribs.getString("sortKey").split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX));
if (xattribs.exists("sortOrder")) {
sort.setSortOrderAscending(xattribs.getString("sortOrder").matches("^[Aa].*"));
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
return null;
}
return sort;
}
}
|
package org.jetel.plugin;
import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.component.ComponentFactory;
import org.jetel.ctl.TLCompilerFactory;
import org.jetel.data.Defaults;
import org.jetel.data.lookup.LookupTableFactory;
import org.jetel.data.sequence.SequenceFactory;
import org.jetel.database.ConnectionFactory;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.graph.dictionary.DictionaryTypeFactory;
import org.jetel.graph.runtime.AuthorityProxyFactory;
import org.jetel.interpreter.extensions.TLFunctionPluginRepository;
import org.jetel.metadata.MetadataRepository;
import org.jetel.plugin.generalobject.GeneralObjectFactory;
import org.jetel.util.file.FileUtils;
import org.jetel.util.protocols.CustomPathResolverFactory;
/**
* This class contains all static method, which provide access to all loadable plugins.
* Firstly call init() method to load and check all version dependencies.
*
* @author Martin Zatopek
*
*/
public class Plugins {
private static final String PLUGIN_MANIFEST_FILE_NAME = "plugin.xml";
static Log logger = LogFactory.getLog(Plugins.class);
/**
* Collection of PluginDescriptor(s).
*/
private static Map<String, PluginDescriptor> pluginDescriptors;
private static Map<String, PluginDescriptor> activePlugins;
private static Map<String, PluginDescriptor> deactivePlugins;
private static PluginLocation[] pluginLocations;
/**
* Whether the class references are actively loaded by the plugin system.
*/
private static boolean lazyClassLoading = true;
private static boolean simpleClassLoading = false;
public static void init() {
init((String) null);
}
public static synchronized void init(String directory) {
if (directory == null) {
init((PluginRepositoryLocation[]) null);
return;
}
String[] dirs = directory.split(Defaults.DEFAULT_PATH_SEPARATOR_REGEX);
List<PluginRepositoryLocation> repositoryLocations = new ArrayList<PluginRepositoryLocation>();
for (String dir : dirs) {
repositoryLocations.add(new PluginRepositoryLocation(new File(dir)));
}
init(repositoryLocations.toArray(new PluginRepositoryLocation[repositoryLocations.size()]));
}
public static synchronized void init(PluginRepositoryLocation[] repositoryLocations) {
if (repositoryLocations == null) {
repositoryLocations = new PluginRepositoryLocation[] { new PluginRepositoryLocation(new File(Defaults.DEFAULT_PLUGINS_DIRECTORY)) };
}
FilenameFilter pluginManifestFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(PLUGIN_MANIFEST_FILE_NAME);
}
};
List<PluginLocation> pluginLocations = new ArrayList<PluginLocation>();
for (PluginRepositoryLocation repositoryLocation : repositoryLocations) {
File pluginRepositoryPath = repositoryLocation.getLocation();
File[] pluginManifestFiles = pluginRepositoryPath.listFiles(pluginManifestFilter);
if (pluginManifestFiles != null && pluginManifestFiles.length != 0) {
try {
pluginLocations.add(new PluginLocation(pluginRepositoryPath.toURI().toURL(), repositoryLocation.getClassloader()));
} catch (MalformedURLException e) {
logger.error("Plugin at '" + pluginRepositoryPath + "' cannot be loaded.", e);
continue;
}
} else {
File[] pd = pluginRepositoryPath.listFiles();
if (pd == null) {
logger.error("Plugins repository '" + pluginRepositoryPath + "' is not available (skipped).");
continue;
}
for (int i = 0; i < pd.length; i++) {
if (pd[i].isDirectory()) {
try {
pluginLocations.add(new PluginLocation(pd[i].toURI().toURL(), repositoryLocation.getClassloader()));
} catch (MalformedURLException e) {
logger.error("Plugin at '" + pd[i] + "' cannot be loaded.", e);
continue;
}
}
}
}
}
PluginLocation[] pls = pluginLocations.toArray(new PluginLocation[pluginLocations.size()]);
Plugins.init(pls);
}
/**
* @param pluginLocations
*/
public static synchronized void init(PluginLocation[] pluginLocations) {
//remove all previous settings
pluginDescriptors = new HashMap<String, PluginDescriptor>();
activePlugins = new HashMap<String, PluginDescriptor>();
deactivePlugins = new HashMap<String, PluginDescriptor>();
if (pluginLocations == null || pluginLocations.length == 0) {
logger.warn("Engine starts without plugins.");
if (pluginLocations == null) {
pluginLocations = new PluginLocation[0];
}
}
Plugins.pluginLocations = pluginLocations;
//create all plugin descriptor
loadPluginDescription();
//check dependences between plugins
checkDependences();
//non-lazy activated plugins must be activated here
activatePluginsIfNecessary();
//init calls of all factories for components, sequences, lookups and connections
ComponentFactory.init();
SequenceFactory.init();
LookupTableFactory.init();
ConnectionFactory.init();
TLFunctionPluginRepository.init();
org.jetel.ctl.extensions.TLFunctionPluginRepository.init();
DictionaryTypeFactory.init();
TLCompilerFactory.init();
GeneralObjectFactory.init();
CustomPathResolverFactory.init();
AuthorityProxyFactory.init();
MetadataRepository.init();
}
/**
* Activates all plugins which should be activated right on engine startup.
*/
private static void activatePluginsIfNecessary() {
for (String pluginId : pluginDescriptors.keySet()) {
if (!pluginDescriptors.get(pluginId).isLazyActivated()
&& !activePlugins.containsKey(pluginId)
&& !deactivePlugins.containsKey(pluginId)) {
activatePlugin(pluginId);
}
}
}
public static Map<String, PluginDescriptor> getPluginDescriptors(){
return pluginDescriptors;
}
public static List<Extension> getExtensions(String extensionName) {
List<Extension> ret = new ArrayList<Extension>();
for(PluginDescriptor plugin : pluginDescriptors.values()) {
ret.addAll(plugin.getExtensions(extensionName));
}
return ret;
}
private static void loadPluginDescription() {
//iterates over all plugin repositories
for (PluginLocation pluginLocation : pluginLocations) {
URL pluginManifestUrl;
try {
//find a plugin manifest "plugin.xml"
pluginManifestUrl = FileUtils.getFileURL(pluginLocation.getLocation(), PLUGIN_MANIFEST_FILE_NAME);
} catch (MalformedURLException e) {
logger.error("Plugin '" + pluginLocation.getLocation() + "' is not available (skipped).", e);
continue;
}
PluginDescriptor pluginDescriptor = new PluginDescriptor(pluginManifestUrl, pluginLocation.getClassloader());
try {
pluginDescriptor.init();
} catch (ComponentNotReadyException e) {
//manifest is not parsable
logger.warn("Plugin manifest '" + pluginManifestUrl + "' is not parsable (skipped).", e);
continue;
}
//stores prepared plugin descriptor
if (!pluginDescriptors.containsKey(pluginDescriptor.getId())) {
pluginDescriptors.put(pluginDescriptor.getId(), pluginDescriptor);
} else {
logger.warn("Plugin at '" + pluginManifestUrl + "' cannot be loaded. Another plugin is already registered with identical id attribute.");
}
}
//log plugin descriptors
if (logger.isDebugEnabled()) {
for (PluginDescriptor pluginDescriptor : pluginDescriptors.values()) {
logger.debug("Plugin " + pluginDescriptor.getId() + " loaded.\n" + pluginDescriptor.toString());
}
} else if (logger.isInfoEnabled()) {
StringBuilder sb = new StringBuilder("Engine plug-ins loaded: ");
boolean first = true;
for (PluginDescriptor pluginDescriptor : pluginDescriptors.values()) {
if (!first) {
sb.append(", ");
} else {
first = false;
}
sb.append(pluginDescriptor.getId());
}
logger.info(sb.toString());
}
}
public static List<ClassLoader> getClassLoaders(ClassLoader exclude) {
List<ClassLoader> ret = new ArrayList<ClassLoader>();
for(PluginDescriptor plugin : pluginDescriptors.values()) {
ClassLoader cl = plugin.getClassLoader();
if(cl != exclude) {
ret.add(cl);
}
}
return ret;
}
private static void checkDependences() {
for(PluginDescriptor plugin : pluginDescriptors.values()) {
plugin.checkDependences();
}
}
public static PluginLocation[] getPluginLocations() {
return pluginLocations;
}
public static PluginDescriptor getPluginDescriptor(String pluginId) {
return pluginDescriptors.get(pluginId);
}
/**
* Activate all not yet activated plugins. All already deactivated plugins are skipped.
* @param lazyClassLoading whether the class references are actively loaded by the plugin system
*/
public static synchronized void activateAllPlugins() {
for(String pluginId : pluginDescriptors.keySet()) {
if(!activePlugins.containsKey(pluginId) && !deactivePlugins.containsKey(pluginId)) {
activatePlugin(pluginId);
}
}
}
public static synchronized void activatePlugin(String pluginID) {
//some validation tests
if(!pluginDescriptors.containsKey(pluginID)) {
logger.error("Attempt activate unknown plugin: " + pluginID);
return;
}
if(activePlugins.containsKey(pluginID)) {
logger.error("Attempt activate already actived plugin: " + pluginID);
return;
}
if(deactivePlugins.containsKey(pluginID)) {
logger.error("Attempt activate already deactived plugin: " + pluginID);
return;
}
//activation
PluginDescriptor pluginDescriptor = pluginDescriptors.get(pluginID);
activePlugins.put(pluginID, pluginDescriptor);
pluginDescriptor.activate();
}
public static synchronized void deactivatePlugin(String pluginID) {
//some validation tests
if(!pluginDescriptors.containsKey(pluginID)) {
logger.error("Attempt deactivate unknown plugin: " + pluginID);
return;
}
if(!activePlugins.containsKey(pluginID)) {
logger.error("Attempt deactivate inactive plugin: " + pluginID);
return;
}
if(deactivePlugins.containsKey(pluginID)) {
logger.error("Attempt deactivate already deactive plugin: " + pluginID);
return;
}
//deactivation
PluginDescriptor pluginDescriptor = pluginDescriptors.get(pluginID);
activePlugins.remove(pluginID);
deactivePlugins.put(pluginID, pluginDescriptor);
pluginDescriptor.deactivate();
}
/**
* Checks whether plugin with given pluginId is active.
* @param pluginId
* @return
*/
public static boolean isActive(String pluginId) {
PluginDescriptor pluginDescriptor = getPluginDescriptor(pluginId);
if (pluginDescriptor != null) {
return pluginDescriptor.isActive();
} else {
throw new IllegalArgumentException("unknown pluginId '" + pluginId + "'");
}
}
/**
* @return whether the class references are actively loaded by the plugin system.
*/
public static boolean isLazyClassLoading() {
return lazyClassLoading;
}
/**
* @param lazyClassLoading whether the class references are actively loaded by the plugin system
* @note has to be invoked before Plugins initialization
*/
public static void setLazyClassLoading(boolean lazyClassLoading) {
Plugins.lazyClassLoading = lazyClassLoading;
}
public static boolean isSimpleClassLoading() {
return simpleClassLoading;
}
public static void setSimpleClassLoading(boolean simpleClassLoading) {
Plugins.simpleClassLoading = simpleClassLoading;
}
}
|
package convwatch;
public interface PropertyName
{
final public static String DOC_COMPARATOR_INPUT_PATH = "DOC_COMPARATOR_INPUT_PATH";
final public static String DOC_COMPARATOR_OUTPUT_PATH = "DOC_COMPARATOR_OUTPUT_PATH";
final public static String DOC_COMPARATOR_DIFF_PATH = "DOC_COMPARATOR_DIFF_PATH";
final public static String DOC_COMPARATOR_REFERENCE_PATH = "DOC_COMPARATOR_REFERENCE_PATH";
final public static String DOC_COMPARATOR_REFERENCE_INPUT_PATH = "DOC_COMPARATOR_REFERENCE_INPUT_PATH";
final public static String DOC_COMPARATOR_REFERENCE_TYPE = "DOC_COMPARATOR_REFERENCE_CREATOR_TYPE";
final public static String DOC_COMPARATOR_PRINTER_NAME = "DOC_COMPARATOR_PRINTER_NAME";
final public static String DOC_COMPARATOR_DEFAULT_XML_FORMAT_APP = "DOC_COMPARATOR_DEFAULT_XML_FORMAT_APP";
final public static String DOC_COMPARATOR_INCLUDE_SUBDIRS = "DOC_COMPARATOR_INCLUDE_SUBDIRS";
final public static String DOC_COMPARATOR_PRINT_MAX_PAGE = "DOC_COMPARATOR_PRINT_MAX_PAGE";
final public static String DOC_COMPARATOR_PRINT_ONLY_PAGE = "DOC_COMPARATOR_PRINT_ONLY_PAGE";
final public static String DOC_COMPARATOR_GFX_OUTPUT_DPI_RESOLUTION = "DOC_COMPARATOR_GFX_OUTPUT_DPI_RESOLUTION";
final public static String DOC_COMPARATOR_OVERWRITE_REFERENCE = "DOC_COMPARATOR_OVERWRITE_REFERENCE";
final public static String DOC_COMPARATOR_HTML_OUTPUT_PREFIX = "DOC_COMPARATOR_HTML_OUTPUT_PREFIX";
final public static String DOC_COMPARATOR_GFXCMP_WITH_BORDERMOVE = "DOC_COMPARATOR_GFXCMP_WITH_BORDERMOVE";
final public static String DOC_CONVERTER_IMPORT_FILTER_NAME = "DOC_CONVERTER_IMPORT_FILTER_NAME";
final public static String DOC_CONVERTER_EXPORT_FILTER_NAME = "DOC_CONVERTER_EXPORT_FILTER_NAME";
final public static String DOC_CONVERTER_OFFICE_PROGRAM = "DOC_CONVERTER_OFFICE_PROGRAM";
final public static String DOC_CONVERTER_REUSE_OFFICE = "DOC_CONVERTER_REUSE_OFFICE";
final public static String DOC_COMPARATOR_LEAVE_OUT_FILES = "DOC_COMPARATOR_LEAVE_OUT_FILES";
final public static String DOC_COMPARATOR_DB_INFO_STRING = "DOC_COMPARATOR_DB_INFO_STRING";
}
|
package com.exedio.cope;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import bak.pcj.list.IntArrayList;
import bak.pcj.list.IntList;
import com.exedio.dsmf.Driver;
import com.exedio.dsmf.SQLRuntimeException;
import com.exedio.dsmf.Schema;
abstract class Database
{
protected static final int TWOPOW8 = 1<<8;
protected static final int TWOPOW16 = 1<<16;
protected static final int TWOPOW24 = 1<<24;
private static final String NO_SUCH_ROW = "no such row";
private final ArrayList<Table> tables = new ArrayList<Table>();
private final HashMap<String, UniqueConstraint> uniqueConstraintsByID = new HashMap<String, UniqueConstraint>();
private boolean buildStage = true;
final Driver driver;
private final boolean migrationSupported;
final boolean prepare;
private final boolean log;
private final boolean logStatementInfo;
private final boolean butterflyPkSource;
private final boolean fulltextIndex;
final ConnectionPool connectionPool;
private final java.util.Properties forcedNames;
final java.util.Properties tableOptions;
final LimitSupport limitSupport;
final long blobLengthFactor;
// probed on the initial connection
final boolean supportsReadCommitted;
final String databaseProductName;
final String databaseProductVersion;
final int databaseMajorVersion;
final int databaseMinorVersion;
final String driverName;
final String driverVersion;
final int driverMajorVersion;
final int driverMinorVersion;
final boolean oracle; // TODO remove
protected Database(final Driver driver, final Properties properties, final boolean migrationSupported)
{
this.driver = driver;
this.migrationSupported = migrationSupported;
this.prepare = !properties.getDatabaseDontSupportPreparedStatements();
this.log = properties.getDatabaseLog();
this.logStatementInfo = properties.getDatabaseLogStatementInfo();
this.butterflyPkSource = properties.getPkSourceButterfly();
this.fulltextIndex = properties.getFulltextIndex();
this.connectionPool = new ConnectionPool(new CopeConnectionFactory(properties), properties.getConnectionPoolIdleLimit(), properties.getConnectionPoolIdleInitial());
this.forcedNames = properties.getDatabaseForcedNames();
this.tableOptions = properties.getDatabaseTableOptions();
this.limitSupport = properties.getDatabaseDontSupportLimit() ? LimitSupport.NONE : getLimitSupport();
this.blobLengthFactor = getBlobLengthFactor();
this.oracle = getClass().getName().equals("com.exedio.cope.OracleDatabase");
//System.out.println("using database "+getClass());
assert limitSupport!=null;
Connection probeConnection = null;
try
{
probeConnection = connectionPool.getConnection(true);
final DatabaseMetaData dmd = probeConnection.getMetaData();
supportsReadCommitted =
!fakesSupportReadCommitted() &&
dmd.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED);
databaseProductName = dmd.getDatabaseProductName();
databaseProductVersion = dmd.getDatabaseProductVersion();
databaseMajorVersion = dmd.getDatabaseMajorVersion();
databaseMinorVersion = dmd.getDatabaseMinorVersion();
driverName = dmd.getDriverName();
driverVersion = dmd.getDriverVersion();
driverMajorVersion = dmd.getDriverMajorVersion();
driverMinorVersion = dmd.getDriverMinorVersion();
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, "getMetaData");
}
finally
{
if(probeConnection!=null)
{
try
{
connectionPool.putConnection(probeConnection);
probeConnection = null;
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, "putConnection");
}
}
}
}
final Driver getDriver()
{
return driver;
}
final java.util.Properties getTableOptions()
{
return tableOptions;
}
final ConnectionPool getConnectionPool()
{
return connectionPool;
}
final void addTable(final Table table)
{
if(!buildStage)
throw new RuntimeException();
tables.add(table);
}
final void addUniqueConstraint(final String constraintID, final UniqueConstraint constraint)
{
if(!buildStage)
throw new RuntimeException();
final Object collision = uniqueConstraintsByID.put(constraintID, constraint);
if(collision!=null)
throw new RuntimeException("ambiguous unique constraint "+constraint+" trimmed to >"+constraintID+"< colliding with "+collision);
}
protected final Statement createStatement()
{
return createStatement(true);
}
protected final Statement createStatement(final boolean qualifyTable)
{
return new Statement(this, qualifyTable);
}
protected final Statement createStatement(final Query<? extends Object> query)
{
return new Statement(this, query);
}
final void createDatabase(final int migrationVersion)
{
buildStage = false;
makeSchema().create();
if(migrationSupported)
{
final ConnectionPool connectionPool = this.connectionPool;
Connection con = null;
try
{
con = connectionPool.getConnection(true);
notifyMigration(con, migrationVersion, new Date(), "created schema", false);
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, "migrate");
}
finally
{
if(con!=null)
{
try
{
connectionPool.putConnection(con);
con = null;
}
catch(SQLException ex)
{
throw new SQLRuntimeException(ex, "close");
}
}
}
}
}
final void createDatabaseConstraints(final int mask)
{
buildStage = false;
makeSchema().createConstraints(mask);
}
//private static int checkTableTime = 0;
final void checkDatabase(final Connection connection)
{
buildStage = false;
//final long time = System.currentTimeMillis();
// IMPLEMENTATION NOTE
// MySQL can have at most 63 joined tables in one statement
// and other databases probably have similar constraints as
// well, so we limit the number of joined table here.
final int CHUNK_LENGTH = 60;
final int tablesSize = tables.size();
for(int chunkFromIndex = 0; chunkFromIndex<tablesSize; chunkFromIndex+=CHUNK_LENGTH)
{
final int chunkToIndex = Math.min(chunkFromIndex+CHUNK_LENGTH, tablesSize);
final List<Table> tableChunk = tables.subList(chunkFromIndex, chunkToIndex);
final Statement bf = createStatement(true);
bf.append("select count(*) from ").defineColumnInteger();
boolean first = true;
for(final Table table : tableChunk)
{
if(first)
first = false;
else
bf.append(',');
bf.append(table.protectedID);
}
bf.append(" where ");
first = true;
for(final Table table : tableChunk)
{
if(first)
first = false;
else
bf.append(" and ");
final Column primaryKey = table.primaryKey;
bf.append(primaryKey).
append('=').
appendParameter(Type.NOT_A_PK);
for(final Column column : table.getColumns())
{
bf.append(" and ").
append(column);
if(column instanceof BlobColumn || (oracle && column instanceof StringColumn && ((StringColumn)column).maximumLength>=4000))
{
bf.append("is not null");
}
else
{
bf.append('=').
appendParameter(column, column.getCheckValue());
}
}
}
executeSQLQuery(connection, bf,
new ResultSetHandler()
{
public void handle(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
}
},
false, false
);
}
}
final void dropDatabase()
{
buildStage = false;
makeSchema().drop();
}
final void dropDatabaseConstraints(final int mask)
{
buildStage = false;
makeSchema().dropConstraints(mask);
}
final void tearDownDatabase()
{
buildStage = false;
makeSchema().tearDown();
}
final void tearDownDatabaseConstraints(final int mask)
{
buildStage = false;
makeSchema().tearDownConstraints(mask);
}
final void checkEmptyDatabase(final Connection connection)
{
buildStage = false;
//final long time = System.currentTimeMillis();
for(final Table table : tables)
{
final int count = countTable(connection, table);
if(count>0)
throw new RuntimeException("there are "+count+" items left for table "+table.id);
}
//final long amount = (System.currentTimeMillis()-time);
//checkEmptyTableTime += amount;
//System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime);
}
final ArrayList<Object> search(final Connection connection, final Query<? extends Object> query, final boolean doCountOnly)
{
buildStage = false;
listener.search(connection, query, doCountOnly);
final int limitStart = query.limitStart;
final int limitCount = query.limitCount;
final boolean limitActive = limitStart>0 || limitCount!=Query.UNLIMITED_COUNT;
final boolean distinct = query.distinct;
final ArrayList<Join> queryJoins = query.joins;
final Statement bf = createStatement(query);
if(!doCountOnly && limitActive && limitSupport==LimitSupport.CLAUSES_AROUND)
appendLimitClause(bf, limitStart, limitCount);
bf.append("select");
if(!doCountOnly && limitActive && limitSupport==LimitSupport.CLAUSE_AFTER_SELECT)
appendLimitClause(bf, limitStart, limitCount);
bf.append(' ');
final Selectable[] selects = query.selects;
final Column[] selectColumns = new Column[selects.length];
final Type[] selectTypes = new Type[selects.length];
if(!distinct&&doCountOnly)
{
bf.append("count(*)");
}
else
{
if(doCountOnly)
bf.append("count(");
if(distinct)
bf.append("distinct ");
for(int selectIndex = 0; selectIndex<selects.length; selectIndex++)
{
final Selectable select = selects[selectIndex];
final Column selectColumn;
final Type selectType = select.getType();
final Table selectTable;
final Column selectPrimaryKey;
if(selectIndex>0)
bf.append(',');
if(select instanceof Aggregate)
{
bf.append(select, null).defineColumn(select);
final Function selectSource = ((Aggregate)select).getSource();
if(selectSource instanceof FunctionField)
{
selectColumn = ((FunctionField)selectSource).getColumn();
}
else if(selectSource instanceof Type.This)
{
selectTable = selectType.getTable();
selectPrimaryKey = selectTable.primaryKey;
selectColumn = selectPrimaryKey;
if(selectColumn.primaryKey)
{
final StringColumn selectTypeColumn = selectColumn.getTypeColumn();
if(selectTypeColumn==null)
selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances();
}
else
selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances();
}
else
{
selectColumn = null;
final View view = (View)selectSource;
bf.append(view, (Join)null).defineColumn(view);
}
}
else if(select instanceof FunctionField)
{
selectColumn = ((FunctionField)select).getColumn();
bf.append(select, (Join)null).defineColumn(select);
if(select instanceof ItemField)
{
final StringColumn typeColumn = ((ItemField)select).getTypeColumn();
if(typeColumn!=null)
bf.append(',').append(typeColumn).defineColumn(typeColumn);
}
}
else if(select instanceof Type.This)
{
selectTable = selectType.getTable();
selectPrimaryKey = selectTable.primaryKey;
selectColumn = selectPrimaryKey;
bf.appendPK(selectType, (Join)null).defineColumn(select);
if(selectColumn.primaryKey)
{
final StringColumn selectTypeColumn = selectColumn.getTypeColumn();
if(selectTypeColumn!=null)
{
bf.append(',').
append(selectTypeColumn).defineColumn(selectTypeColumn);
}
else
selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances();
}
else
selectTypes[selectIndex] = selectType.getOnlyPossibleTypeOfInstances();
}
else
{
selectColumn = null;
final View view = (View)select;
bf.append(view, (Join)null).defineColumn(view);
}
selectColumns[selectIndex] = selectColumn;
}
if(doCountOnly)
bf.append(')');
}
bf.append(" from ").
appendTypeDefinition((Join)null, query.type);
if(queryJoins!=null)
{
for(final Join join : queryJoins)
{
final Condition joinCondition = join.condition;
if(joinCondition==null)
{
if(join.kind!=Join.Kind.INNER)
throw new RuntimeException("outer join must have join condition");
bf.append(" cross join ");
}
else
{
bf.append(' ').
append(join.kind.sql);
}
bf.appendTypeDefinition(join, join.type);
if(joinCondition!=null)
{
bf.append(" on ");
joinCondition.append(bf);
}
}
}
if(query.condition!=null)
{
bf.append(" where ");
query.condition.append(bf);
}
if(!doCountOnly)
{
final Function[] orderBy = query.orderBy;
if(orderBy!=null)
{
final boolean[] orderAscending = query.orderAscending;
for(int i = 0; i<orderBy.length; i++)
{
if(i==0)
bf.append(" order by ");
else
bf.append(',');
if(orderBy[i] instanceof ItemField)
{
final ItemField<? extends Item> itemOrderBy = (ItemField<? extends Item>)orderBy[i];
itemOrderBy.getValueType().getPkSource().appendOrderByExpression(bf, itemOrderBy);
}
else if(orderBy[i] instanceof Type.This)
{
final Type.This<? extends Item> itemOrderBy = (Type.This<? extends Item>)orderBy[i];
itemOrderBy.type.getPkSource().appendOrderByExpression(bf, itemOrderBy);
}
else
bf.append(orderBy[i], (Join)null);
if(!orderAscending[i])
bf.append(" desc");
// TODO break here, if already ordered by some unique function
}
}
if(limitActive && limitSupport==LimitSupport.CLAUSE_AFTER_WHERE)
appendLimitClause(bf, limitStart, limitCount);
}
if(!doCountOnly && limitActive && limitSupport==LimitSupport.CLAUSES_AROUND)
appendLimitClause2(bf, limitStart, limitCount);
final Type[] types = selectTypes;
final Model model = query.model;
final ArrayList<Object> result = new ArrayList<Object>();
if(limitStart<0)
throw new RuntimeException();
if(selects.length!=selectColumns.length)
throw new RuntimeException();
if(selects.length!=types.length)
throw new RuntimeException();
//System.out.println(bf.toString());
query.addStatementInfo(executeSQLQuery(connection, bf, new ResultSetHandler()
{
public void handle(final ResultSet resultSet) throws SQLException
{
if(doCountOnly)
{
resultSet.next();
result.add(Integer.valueOf(resultSet.getInt(1)));
if(resultSet.next())
throw new RuntimeException();
return;
}
if(limitStart>0 && limitSupport==LimitSupport.NONE)
{
// TODO: ResultSet.relative
// Would like to use
// resultSet.relative(limitStart+1);
// but this throws a java.sql.SQLException:
// Invalid operation for forward only resultset : relative
for(int i = limitStart; i>0; i
resultSet.next();
}
int i = ((limitCount==Query.UNLIMITED_COUNT||(limitSupport!=LimitSupport.NONE)) ? Integer.MAX_VALUE : limitCount );
if(i<=0)
throw new RuntimeException(String.valueOf(limitCount));
while(resultSet.next() && (--i)>=0)
{
int columnIndex = 1;
final Object[] resultRow = (selects.length > 1) ? new Object[selects.length] : null;
final Row dummyRow = new Row();
for(int selectIndex = 0; selectIndex<selects.length; selectIndex++)
{
final Selectable select;
{
Selectable select0 = selects[selectIndex];
if(select0 instanceof Aggregate)
select0 = ((Aggregate)select0).getSource();
select = select0;
}
final Object resultCell;
if(select instanceof FunctionField)
{
selectColumns[selectIndex].load(resultSet, columnIndex++, dummyRow);
final FunctionField selectField = (FunctionField)select;
if(select instanceof ItemField)
{
final StringColumn typeColumn = ((ItemField)selectField).getTypeColumn();
if(typeColumn!=null)
typeColumn.load(resultSet, columnIndex++, dummyRow);
}
resultCell = selectField.get(dummyRow);
}
else if(select instanceof View)
{
final View selectFunction = (View)select;
resultCell = selectFunction.load(resultSet, columnIndex++);
}
else
{
final Number pk = (Number)resultSet.getObject(columnIndex++);
//System.out.println("pk:"+pk);
if(pk==null)
{
// can happen when using right outer joins
resultCell = null;
}
else
{
final Type type = types[selectIndex];
final Type currentType;
if(type==null)
{
final String typeID = resultSet.getString(columnIndex++);
currentType = model.findTypeByID(typeID);
if(currentType==null)
throw new RuntimeException("no type with type id "+typeID);
}
else
currentType = type;
resultCell = currentType.getItemObject(pk.intValue());
}
}
if(resultRow!=null)
resultRow[selectIndex] = resultCell;
else
result.add(resultCell);
}
if(resultRow!=null)
result.add(Collections.unmodifiableList(Arrays.asList(resultRow)));
}
}
}, query.makeStatementInfo, false));
return result;
}
private void log(final long start, final long end, final Statement statement)
{
final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS");
System.out.println(df.format(new Date(start)) + " " + (end-start) + "ms: " + statement.getText()+" "+statement.parameters);
}
final void load(final Connection connection, final PersistentState state)
{
buildStage = false;
listener.load(connection, state);
final Statement bf = createStatement(state.type.supertype!=null);
bf.append("select ");
boolean first = true;
for(Type type = state.type; type!=null; type = type.supertype)
{
for(final Column column : type.getTable().getColumns())
{
if(!(column instanceof BlobColumn))
{
if(first)
first = false;
else
bf.append(',');
bf.append(column).defineColumn(column);
}
}
}
if(first)
{
// no columns in type
bf.appendPK(state.type, (Join)null);
}
bf.append(" from ");
first = true;
for(Type type = state.type; type!=null; type = type.supertype)
{
if(first)
first = false;
else
bf.append(',');
bf.append(type.getTable().protectedID);
}
bf.append(" where ");
first = true;
for(Type type = state.type; type!=null; type = type.supertype)
{
if(first)
first = false;
else
bf.append(" and ");
bf.appendPK(type, (Join)null).
append('=').
appendParameter(state.pk).
appendTypeCheck(type.getTable(), state.type); // Here this also checks additionally for Model#findByID, that the item has the type given in the ID.
}
//System.out.println(bf.toString());
executeSQLQuery(connection, bf, state, false, false);
}
final void store(
final Connection connection,
final State state,
final boolean present,
final Map<BlobColumn, byte[]> blobs)
{
store(connection, state, present, blobs, state.type);
}
private void store(
final Connection connection,
final State state,
final boolean present,
final Map<BlobColumn, byte[]> blobs,
final Type<?> type)
{
buildStage = false;
final Type supertype = type.supertype;
if(supertype!=null)
store(connection, state, present, blobs, supertype);
final Table table = type.getTable();
final List<Column> columns = table.getColumns();
final Statement bf = createStatement();
final StringColumn typeColumn = table.typeColumn;
if(present)
{
bf.append("update ").
append(table.protectedID).
append(" set ");
boolean first = true;
for(final Column column : columns)
{
if(!(column instanceof BlobColumn) || blobs.containsKey(column))
{
if(first)
first = false;
else
bf.append(',');
bf.append(column.protectedID).
append('=');
if(column instanceof BlobColumn)
bf.appendParameterBlob((BlobColumn)column, blobs.get(column));
else
bf.appendParameter(column, state.store(column));
}
}
if(first) // no columns in table
return;
bf.append(" where ").
append(table.primaryKey.protectedID).
append('=').
appendParameter(state.pk).
appendTypeCheck(table, state.type);
}
else
{
bf.append("insert into ").
append(table.protectedID).
append("(").
append(table.primaryKey.protectedID);
if(typeColumn!=null)
{
bf.append(',').
append(typeColumn.protectedID);
}
for(final Column column : columns)
{
if(!(column instanceof BlobColumn) || blobs.containsKey(column))
{
bf.append(',').
append(column.protectedID);
}
}
bf.append(")values(").
appendParameter(state.pk);
if(typeColumn!=null)
{
bf.append(',').
appendParameter(state.type.id);
}
for(final Column column : columns)
{
if(column instanceof BlobColumn)
{
if(blobs.containsKey(column))
{
bf.append(',').
appendParameterBlob((BlobColumn)column, blobs.get(column));
}
}
else
{
bf.append(',').
appendParameter(column, state.store(column));
}
}
bf.append(')');
}
//System.out.println("storing "+bf.toString());
executeSQLUpdate(connection, bf, 1, type.declaredUniqueConstraints);
}
final void delete(final Connection connection, final Item item)
{
buildStage = false;
final Type type = item.type;
final int pk = item.pk;
for(Type currentType = type; currentType!=null; currentType = currentType.supertype)
{
final Table currentTable = currentType.getTable();
final Statement bf = createStatement();
bf.append("delete from ").
append(currentTable.protectedID).
append(" where ").
append(currentTable.primaryKey.protectedID).
append('=').
appendParameter(pk);
//System.out.println("deleting "+bf.toString());
executeSQLUpdate(connection, bf, 1);
}
}
final byte[] load(final Connection connection, final BlobColumn column, final Item item)
{
// TODO reuse code in load blob methods
buildStage = false;
final Table table = column.table;
final Statement bf = createStatement();
bf.append("select ").
append(column.protectedID).defineColumn(column).
append(" from ").
append(table.protectedID).
append(" where ").
append(table.primaryKey.protectedID).
append('=').
appendParameter(item.pk).
appendTypeCheck(table, item.type);
final LoadBlobResultSetHandler handler = new LoadBlobResultSetHandler(supportsGetBytes());
executeSQLQuery(connection, bf, handler, false, false);
return handler.result;
}
private static class LoadBlobResultSetHandler implements ResultSetHandler
{
final boolean supportsGetBytes;
LoadBlobResultSetHandler(final boolean supportsGetBytes)
{
this.supportsGetBytes = supportsGetBytes;
}
byte[] result;
public void handle(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
result = supportsGetBytes ? resultSet.getBytes(1) : loadBlob(resultSet.getBlob(1));
}
private static final byte[] loadBlob(final Blob blob) throws SQLException
{
if(blob==null)
return null;
return DataField.copy(blob.getBinaryStream(), blob.length());
}
}
final void load(final Connection connection, final BlobColumn column, final Item item, final OutputStream data, final DataField field)
{
buildStage = false;
final Table table = column.table;
final Statement bf = createStatement();
bf.append("select ").
append(column.protectedID).defineColumn(column).
append(" from ").
append(table.protectedID).
append(" where ").
append(table.primaryKey.protectedID).
append('=').
appendParameter(item.pk).
appendTypeCheck(table, item.type);
executeSQLQuery(connection, bf, new ResultSetHandler(){
public void handle(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
if(supportsBlobInResultSet())
{
final Blob blob = resultSet.getBlob(1);
if(blob!=null)
{
InputStream source = null;
try
{
source = blob.getBinaryStream();
field.copy(source, data, blob.length(), item);
}
catch(IOException e)
{
throw new RuntimeException(e);
}
finally
{
if(source!=null)
{
try
{
source.close();
}
catch(IOException e)
{/*IGNORE*/}
}
}
}
}
else
{
InputStream source = null;
try
{
source = resultSet.getBinaryStream(1);
if(source!=null)
field.copy(source, data, item);
}
catch(IOException e)
{
throw new RuntimeException(e);
}
finally
{
if(source!=null)
{
try
{
source.close();
}
catch(IOException e)
{/*IGNORE*/}
}
}
}
}
}, false, false);
}
final long loadLength(final Connection connection, final BlobColumn column, final Item item)
{
buildStage = false;
final Table table = column.table;
final Statement bf = createStatement();
bf.append("select length(").
append(column.protectedID).defineColumnInteger().
append(") from ").
append(table.protectedID).
append(" where ").
append(table.primaryKey.protectedID).
append('=').
appendParameter(item.pk).
appendTypeCheck(table, item.type);
final LoadBlobLengthResultSetHandler handler = new LoadBlobLengthResultSetHandler();
executeSQLQuery(connection, bf, handler, false, false);
return handler.result;
}
private class LoadBlobLengthResultSetHandler implements ResultSetHandler
{
long result;
public void handle(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
final Object o = resultSet.getObject(1);
if(o!=null)
{
long value = ((Number)o).longValue();
final long factor = blobLengthFactor;
if(factor!=1)
{
if(value%factor!=0)
throw new RuntimeException("not dividable "+value+'/'+factor);
value /= factor;
}
result = value;
}
else
result = -1;
}
}
final void store(
final Connection connection, final BlobColumn column, final Item item,
final InputStream data, final DataField field)
throws IOException
{
buildStage = false;
final Table table = column.table;
final Statement bf = createStatement();
bf.append("update ").
append(table.protectedID).
append(" set ").
append(column.protectedID).
append('=');
if(data!=null)
bf.appendParameterBlob(column, data, field, item);
else
bf.append("NULL");
bf.append(" where ").
append(table.primaryKey.protectedID).
append('=').
appendParameter(item.pk).
appendTypeCheck(table, item.type);
//System.out.println("storing "+bf.toString());
executeSQLUpdate(connection, bf, 1);
}
static interface ResultSetHandler
{
public void handle(ResultSet resultSet) throws SQLException;
}
private final static int convertSQLResult(final Object sqlInteger)
{
// IMPLEMENTATION NOTE
// Whether the returned object is an Integer, a Long or a BigDecimal,
// depends on the database used and for oracle on whether
// OracleStatement.defineColumnType is used or not, so we support all
// here.
return ((Number)sqlInteger).intValue();
}
//private static int timeExecuteQuery = 0;
protected final StatementInfo executeSQLQuery(
final Connection connection,
final Statement statement,
final ResultSetHandler resultSetHandler,
final boolean makeStatementInfo,
final boolean explain)
{
java.sql.Statement sqlStatement = null;
ResultSet resultSet = null;
try
{
final boolean log = !explain && (this.log || this.logStatementInfo || makeStatementInfo);
final String sqlText = statement.getText();
final long logStart = log ? System.currentTimeMillis() : 0;
final long logPrepared;
final long logExecuted;
if(!prepare)
{
sqlStatement = connection.createStatement();
defineColumnTypes(statement.columnTypes, sqlStatement);
logPrepared = log ? System.currentTimeMillis() : 0;
resultSet = sqlStatement.executeQuery(sqlText);
logExecuted = log ? System.currentTimeMillis() : 0;
resultSetHandler.handle(resultSet);
}
else
{
final PreparedStatement prepared = connection.prepareStatement(sqlText);
sqlStatement = prepared;
int parameterIndex = 1;
for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++)
setObject(sqlText, prepared, parameterIndex, i.next());
defineColumnTypes(statement.columnTypes, sqlStatement);
logPrepared = log ? System.currentTimeMillis() : 0;
resultSet = prepared.executeQuery();
logExecuted = log ? System.currentTimeMillis() : 0;
resultSetHandler.handle(resultSet);
}
final long logResultRead = log ? System.currentTimeMillis() : 0;
if(resultSet!=null)
{
resultSet.close();
resultSet = null;
}
if(sqlStatement!=null)
{
sqlStatement.close();
sqlStatement = null;
}
final long logEnd = log ? System.currentTimeMillis() : 0;
if(!explain && this.log)
log(logStart, logEnd, statement);
final StatementInfo statementInfo =
(!explain && (this.logStatementInfo || makeStatementInfo))
? makeStatementInfo(statement, connection, logStart, logPrepared, logExecuted, logResultRead, logEnd)
: null;
if(!explain && this.logStatementInfo)
statementInfo.print(System.out);
return makeStatementInfo ? statementInfo : null;
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, statement.toString());
}
finally
{
if(resultSet!=null)
{
try
{
resultSet.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
if(sqlStatement!=null)
{
try
{
sqlStatement.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
}
}
private final void executeSQLUpdate(final Connection connection, final Statement statement, final int expectedRows)
throws UniqueViolationException
{
executeSQLUpdate(connection, statement, expectedRows, null);
}
private final void executeSQLUpdate(
final Connection connection,
final Statement statement, final int expectedRows,
final List<UniqueConstraint> threatenedUniqueConstraints)
throws UniqueViolationException
{
java.sql.Statement sqlStatement = null;
Savepoint savepoint = null;
try
{
final String sqlText = statement.getText();
final long logStart = log ? System.currentTimeMillis() : 0;
final int rows;
if(threatenedUniqueConstraints!=null && threatenedUniqueConstraints.size()>0 && needsSavepoint())
savepoint = connection.setSavepoint();
if(!prepare)
{
sqlStatement = connection.createStatement();
rows = sqlStatement.executeUpdate(sqlText);
}
else
{
final PreparedStatement prepared = connection.prepareStatement(sqlText);
sqlStatement = prepared;
int parameterIndex = 1;
for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++)
setObject(sqlText, prepared, parameterIndex, i.next());
rows = prepared.executeUpdate();
}
final long logEnd = log ? System.currentTimeMillis() : 0;
if(log)
log(logStart, logEnd, statement);
//System.out.println("("+rows+"): "+statement.getText());
if(rows!=expectedRows)
throw new RuntimeException("expected "+expectedRows+" rows, but got "+rows+" on statement "+sqlText);
}
catch(SQLException e)
{
final UniqueViolationException wrappedException = wrapException(e, threatenedUniqueConstraints);
if(wrappedException!=null)
{
if(savepoint!=null)
{
try
{
connection.rollback(savepoint);
savepoint = null;
}
catch(SQLException ex)
{
throw new SQLRuntimeException(e, ex.getMessage() + " on rollback of: " + statement.toString());
}
}
throw wrappedException;
}
else
throw new SQLRuntimeException(e, statement.toString());
}
finally
{
if(sqlStatement!=null)
{
try
{
sqlStatement.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
}
}
private static final void setObject(String s, final PreparedStatement statement, final int parameterIndex, final Object value)
throws SQLException
{
//try{
statement.setObject(parameterIndex, value);
//}catch(SQLException e){ throw new SQLRuntimeException(e, "setObject("+parameterIndex+","+value+")"+s); }
}
protected static final String EXPLAIN_PLAN = "explain plan";
protected StatementInfo makeStatementInfo(
final Statement statement, final Connection connection,
final long start, final long prepared, final long executed, final long resultRead, final long end)
{
final StatementInfo result = new StatementInfo(statement.getText());
result.addChild(new StatementInfo("timing "+(end-start)+'/'+(prepared-start)+'/'+(executed-prepared)+'/'+(resultRead-executed)+'/'+(end-resultRead)+" (total/prepare/execute/readResult/close in ms)"));
final ArrayList<Object> parameters = statement.parameters;
if(parameters!=null)
{
final StatementInfo parametersChild = new StatementInfo("parameters");
result.addChild(parametersChild);
int i = 1;
for(Object p : parameters)
parametersChild.addChild(new StatementInfo(String.valueOf(i++) + ':' + p));
}
return result;
}
protected abstract String extractUniqueConstraintName(SQLException e);
protected final static String ANY_CONSTRAINT = "--ANY
private final UniqueViolationException wrapException(
final SQLException e,
final List<UniqueConstraint> threatenedUniqueConstraints)
{
final String uniqueConstraintID = extractUniqueConstraintName(e);
if(uniqueConstraintID!=null)
{
final UniqueConstraint constraint;
if(ANY_CONSTRAINT.equals(uniqueConstraintID))
constraint = (threatenedUniqueConstraints.size()==1) ? threatenedUniqueConstraints.get(0) : null;
else
{
constraint = uniqueConstraintsByID.get(uniqueConstraintID);
if(constraint==null)
throw new SQLRuntimeException(e, "no unique constraint found for >"+uniqueConstraintID
+"<, has only "+uniqueConstraintsByID.keySet());
}
return new UniqueViolationException(constraint, null, e);
}
return null;
}
/**
* Trims a name to length for being a suitable qualifier for database entities,
* such as tables, columns, indexes, constraints, partitions etc.
*/
protected static final String trimString(final String longString, final int maxLength)
{
if(maxLength<=0)
throw new IllegalArgumentException("maxLength must be greater zero");
if(longString.length()==0)
throw new IllegalArgumentException("longString must not be empty");
if(longString.length()<=maxLength)
return (longString.indexOf('.')<=0) ? longString : longString.replace('.', '_');
int longStringLength = longString.length();
final int[] trimPotential = new int[maxLength];
final ArrayList<String> words = new ArrayList<String>();
{
final StringBuffer buf = new StringBuffer();
for(int i=0; i<longString.length(); i++)
{
char c = longString.charAt(i);
if(c=='.')
c = '_';
if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0)
{
words.add(buf.toString());
int potential = 1;
for(int j = buf.length()-1; j>=0; j--, potential++)
trimPotential[j] += potential;
buf.setLength(0);
}
if(buf.length()<maxLength)
buf.append(c);
else
longStringLength
}
if(buf.length()>0)
{
words.add(buf.toString());
int potential = 1;
for(int j = buf.length()-1; j>=0; j--, potential++)
trimPotential[j] += potential;
buf.setLength(0);
}
}
final int expectedTrimPotential = longStringLength - maxLength;
//System.out.println("expected trim potential = "+expectedTrimPotential);
int wordLength;
int remainder = 0;
for(wordLength = trimPotential.length-1; wordLength>=0; wordLength
{
//System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]);
remainder = trimPotential[wordLength] - expectedTrimPotential;
if(remainder>=0)
break;
}
final StringBuffer result = new StringBuffer(longStringLength);
for(final String word : words)
{
//System.out.println("word "+word+" remainder:"+remainder);
if((word.length()>wordLength) && remainder>0)
{
result.append(word.substring(0, wordLength+1));
remainder
}
else if(word.length()>wordLength)
result.append(word.substring(0, wordLength));
else
result.append(word);
}
if(result.length()!=maxLength)
throw new RuntimeException(result.toString()+maxLength);
return result.toString();
}
final String makeName(final String longName)
{
return makeName(null, longName);
}
final String makeName(final String prefix, final String longName)
{
final String query = prefix==null ? longName : prefix+'.'+longName;
final String forcedName = forcedNames.getProperty(query);
if(forcedName!=null)
return forcedName;
return trimString(longName, 25);
}
boolean supportsGetBytes()
{
return true;
}
boolean supportsBlobInResultSet()
{
return true;
}
boolean supportsEmptyStrings()
{
return true;
}
boolean fakesSupportReadCommitted()
{
return false;
}
/**
* Specifies the factor,
* the length function of blob columns is wrong.
*/
int getBlobLengthFactor()
{
return 1;
}
/**
* By overriding this method subclasses can enable the use of save points.
* Some databases cannot recover from constraint violations in
* the same transaction without a little help,
* they need a save point set before the modification, that can be
* recovered manually.
*/
boolean needsSavepoint()
{
return false;
}
abstract String getIntegerType(long minimum, long maximum);
abstract String getDoubleType();
abstract String getStringType(int maxLength);
abstract String getDayType();
/**
* Returns a column type suitable for storing timestamps
* with milliseconds resolution.
* This method may return null,
* if the database does not support such a column type.
* The framework will then fall back to store the number of milliseconds.
*/
abstract String getDateTimestampType();
abstract String getBlobType(long maximumLength);
abstract LimitSupport getLimitSupport();
static enum LimitSupport
{
NONE,
CLAUSE_AFTER_SELECT,
CLAUSE_AFTER_WHERE,
CLAUSES_AROUND;
}
/**
* Appends a clause to the statement causing the database limiting the query result.
* This method is never called for <tt>start==0 && count=={@link Query#UNLIMITED_COUNT}</tt>.
* NOTE: Don't forget the space before the keyword 'limit'!
* @param start the number of rows to be skipped
* or zero, if no rows to be skipped.
* Is never negative.
* @param count the number of rows to be returned
* or {@link Query#UNLIMITED_COUNT} if all rows to be returned.
* Is always positive (greater zero).
*/
abstract void appendLimitClause(Statement bf, int start, int count);
/**
* Same as {@link #appendLimitClause(Statement, int, int)}.
* Is used for {@link LimitSupport#CLAUSES_AROUND} only,
* for the postfix.
*/
abstract void appendLimitClause2(Statement bf, int start, int count);
abstract void appendMatchClauseFullTextIndex(Statement bf, StringFunction function, String value);
/**
* Search full text.
*/
final void appendMatchClause(final Statement bf, final StringFunction function, final String value)
{
if(fulltextIndex)
appendMatchClauseFullTextIndex(bf, function, value);
else
appendMatchClauseByLike(bf, function, value);
}
protected final void appendMatchClauseByLike(final Statement bf, final StringFunction function, final String value)
{
bf.append(function, (Join)null).
append(" like ").
appendParameter(function, LikeCondition.WILDCARD + value + LikeCondition.WILDCARD);
}
private int countTable(final Connection connection, final Table table)
{
final Statement bf = createStatement();
bf.append("select count(*) from ").defineColumnInteger().
append(table.protectedID);
final CountResultSetHandler handler = new CountResultSetHandler();
executeSQLQuery(connection, bf, handler, false, false);
return handler.result;
}
private static class CountResultSetHandler implements ResultSetHandler
{
int result;
public void handle(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
result = convertSQLResult(resultSet.getObject(1));
}
}
final PkSource makePkSource(final Table table)
{
return butterflyPkSource ? (PkSource)new ButterflyPkSource(table) : new SequentialPkSource(table);
}
final int[] getMinMaxPK(final Connection connection, final Table table)
{
buildStage = false;
final Statement bf = createStatement();
final String primaryKeyProtectedID = table.primaryKey.protectedID;
bf.append("select min(").
append(primaryKeyProtectedID).defineColumnInteger().
append("),max(").
append(primaryKeyProtectedID).defineColumnInteger().
append(") from ").
append(table.protectedID);
final NextPKResultSetHandler handler = new NextPKResultSetHandler();
executeSQLQuery(connection, bf, handler, false, false);
return handler.result;
}
private static class NextPKResultSetHandler implements ResultSetHandler
{
int[] result;
public void handle(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new SQLException(NO_SUCH_ROW);
final Object oLo = resultSet.getObject(1);
if(oLo!=null)
{
result = new int[2];
result[0] = convertSQLResult(oLo);
final Object oHi = resultSet.getObject(2);
result[1] = convertSQLResult(oHi);
}
}
}
final int checkTypeColumn(final Connection connection, final Type type)
{
buildStage = false;
final Table table = type.getTable();
final Table superTable = type.getSupertype().getTable();
final Statement bf = createStatement(true);
bf.append("select count(*) from ").
append(table).append(',').append(superTable).
append(" where ").
append(table.primaryKey).append('=').append(superTable.primaryKey).
append(" and ");
if(table.typeColumn!=null)
bf.append(table.typeColumn);
else
bf.appendParameter(type.id);
bf.append("<>").append(superTable.typeColumn);
//System.out.println("CHECKT:"+bf.toString());
final CheckTypeColumnResultSetHandler handler = new CheckTypeColumnResultSetHandler();
executeSQLQuery(connection, bf, handler, false, false);
return handler.result;
}
final int checkTypeColumn(final Connection connection, final ItemField field)
{
buildStage = false;
final Table table = field.getType().getTable();
final Table valueTable = field.getValueType().getTable();
final String alias1 = driver.protectName(Table.SQL_ALIAS_1);
final String alias2 = driver.protectName(Table.SQL_ALIAS_2);
final Statement bf = createStatement(false);
bf.append("select count(*) from ").
append(table).append(' ').append(alias1).
append(',').
append(valueTable).append(' ').append(alias2).
append(" where ").
append(alias1).append('.').append(field.getColumn()).
append('=').
append(alias2).append('.').append(valueTable.primaryKey).
append(" and ").
append(alias1).append('.').append(field.getTypeColumn()).
append("<>").
append(alias2).append('.').append(valueTable.typeColumn);
//System.out.println("CHECKA:"+bf.toString());
final CheckTypeColumnResultSetHandler handler = new CheckTypeColumnResultSetHandler();
executeSQLQuery(connection, bf, handler, false, false);
return handler.result;
}
private static class CheckTypeColumnResultSetHandler implements ResultSetHandler
{
int result = Integer.MIN_VALUE;
public void handle(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException();
result = resultSet.getInt(1);
}
}
private static final String MIGRATION_COLUMN_VERSION_NAME = "v";
private static final String MIGRATION_COLUMN_COMMENT_NAME = "c";
final Schema makeSchema()
{
final Schema result = new Schema(driver, connectionPool);
for(final Table t : tables)
t.makeSchema(result);
if(migrationSupported)
{
final com.exedio.dsmf.Table table = new com.exedio.dsmf.Table(result, Table.MIGRATION_TABLE_NAME);
new com.exedio.dsmf.Column(table, MIGRATION_COLUMN_VERSION_NAME, getIntegerType(0, Integer.MAX_VALUE));
new com.exedio.dsmf.Column(table, MIGRATION_COLUMN_COMMENT_NAME, getStringType(100));
new com.exedio.dsmf.UniqueConstraint(table, Table.MIGRATION_UNIQUE_CONSTRAINT_NAME, '(' + driver.protectName(MIGRATION_COLUMN_VERSION_NAME) + ')');
}
completeSchema(result);
return result;
}
protected void completeSchema(final Schema schema)
{
// empty default implementation
}
final Schema makeVerifiedSchema()
{
final Schema result = makeSchema();
result.verify();
return result;
}
final int getActualMigrationVersion(final Connection connection)
{
buildStage = false;
final Statement bf = createStatement();
bf.append("select max(").
append(driver.protectName(MIGRATION_COLUMN_VERSION_NAME)).defineColumnInteger().
append(") from ").
append(driver.protectName(Table.MIGRATION_TABLE_NAME));
final ActualMigrationVersionResultSetHandler handler = new ActualMigrationVersionResultSetHandler();
executeSQLQuery(connection, bf, handler, false, false);
return handler.result;
}
private static class ActualMigrationVersionResultSetHandler implements ResultSetHandler
{
int result = -1;
public void handle(final ResultSet resultSet) throws SQLException
{
resultSet.next();
result = resultSet.getInt(1);
}
}
final Map<Integer, String> getMigrationLogs()
{
final ConnectionPool connectionPool = this.connectionPool;
Connection con = null;
try
{
con = connectionPool.getConnection(true);
return getMigrationLogs(con);
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, "getMigrationLogs");
}
finally
{
if(con!=null)
{
try
{
connectionPool.putConnection(con);
con = null;
}
catch(SQLException ex)
{
throw new SQLRuntimeException(ex, "close");
}
}
}
}
private final Map<Integer, String> getMigrationLogs(final Connection connection)
{
buildStage = false;
final Statement bf = createStatement();
bf.append("select ").
append(driver.protectName(MIGRATION_COLUMN_VERSION_NAME)).defineColumnInteger().
append(',').
append(driver.protectName(MIGRATION_COLUMN_COMMENT_NAME)).defineColumnString().
append(" from ").
append(driver.protectName(Table.MIGRATION_TABLE_NAME));
final MigrationLogsResultSetHandler handler = new MigrationLogsResultSetHandler();
executeSQLQuery(connection, bf, handler, false, false);
return Collections.unmodifiableMap(handler.result);
}
private static class MigrationLogsResultSetHandler implements ResultSetHandler
{
final HashMap<Integer, String> result = new HashMap<Integer, String>();
public void handle(final ResultSet resultSet) throws SQLException
{
while(resultSet.next())
{
final int version = resultSet.getInt(1);
final String comment = resultSet.getString(2);
final String previous = result.put(version, comment);
if(previous!=null)
throw new RuntimeException("duplicate version " + version + ':' + previous + "/" + comment);
}
}
}
private final void notifyMigration(final Connection connection, final int version, final Date date, final String comment, final boolean logToConsole)
{
assert migrationSupported;
final String fullComment = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(date) + ':' + comment;
if(logToConsole)
System.out.println("Migrated to version " + version + ':' + fullComment);
final Statement bf = createStatement();
bf.append("insert into ").
append(driver.protectName(Table.MIGRATION_TABLE_NAME)).
append('(').
append(driver.protectName(MIGRATION_COLUMN_VERSION_NAME)).
append(',').
append(driver.protectName(MIGRATION_COLUMN_COMMENT_NAME)).
append(")values(").
appendParameter(version).
append(',').
appendParameter(fullComment).
append(')');
executeSQLUpdate(connection, bf, 1);
}
final void migrate(final int expectedVersion, final Migration[] migrations)
{
assert expectedVersion>=0 : expectedVersion;
assert migrationSupported;
final ConnectionPool connectionPool = this.connectionPool;
Connection con = null;
java.sql.Statement stmt = null;
try
{
con = connectionPool.getConnection(true);
final int actualVersion = getActualMigrationVersion(con);
if(actualVersion>expectedVersion)
{
throw new IllegalArgumentException("cannot migrate backwards, expected " + expectedVersion + ", but was " + actualVersion);
}
else if(actualVersion<expectedVersion)
{
final Migration[] relevant = new Migration[expectedVersion-actualVersion];
for(final Migration migration : migrations)
{
final int version = migration.version;
if(version<=actualVersion || version>expectedVersion)
continue; // irrelevant
final int relevantIndex = version - actualVersion - 1;
assert relevant[relevantIndex]==null : "there is more than one migration for version " + version + ": " + relevant[relevantIndex].comment + " and " + migration.comment;
relevant[relevantIndex] = migration;
}
IntArrayList missing = null;
for(int i = 0; i<relevant.length; i++)
{
if(relevant[i]==null)
{
if(missing==null)
missing = new IntArrayList();
missing.add(i + actualVersion + 1);
}
}
if(missing!=null)
throw new IllegalArgumentException(
"no migration for versions " + missing.toString() +
" on migration from " + actualVersion + " to " + expectedVersion);
final Date date = new Date();
stmt = con.createStatement();
for(final Migration migration : relevant)
{
final String[] body = migration.body;
final IntArrayList rowCounts = new IntArrayList(body.length);
for(final String sql : body)
{
try
{
rowCounts.add(stmt.executeUpdate(sql));
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, sql);
}
}
notifyMigration(con, migration.version, date, migration.comment + ' ' + rowCounts, true);
}
stmt.close();
stmt = null;
}
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, "migrate");
}
finally
{
if(stmt!=null)
{
try
{
stmt.close();
stmt = null;
}
catch(SQLException ex)
{
throw new SQLRuntimeException(ex, "close");
}
}
if(con!=null)
{
try
{
connectionPool.putConnection(con);
con = null;
}
catch(SQLException ex)
{
throw new SQLRuntimeException(ex, "close");
}
}
}
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
@Deprecated
protected static final void printMeta(final ResultSet resultSet) throws SQLException
{
final ResultSetMetaData metaData = resultSet.getMetaData();;
final int columnCount = metaData.getColumnCount();
for(int i = 1; i<=columnCount; i++)
System.out.println("
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
@Deprecated
protected static final void printRow(final ResultSet resultSet) throws SQLException
{
final ResultSetMetaData metaData = resultSet.getMetaData();;
final int columnCount = metaData.getColumnCount();
for(int i = 1; i<=columnCount; i++)
System.out.println("
}
/**
* @deprecated for debugging only, should never be used in committed code
*/
@Deprecated
static final ResultSetHandler logHandler = new ResultSetHandler()
{
public void handle(final ResultSet resultSet) throws SQLException
{
final int columnCount = resultSet.getMetaData().getColumnCount();
System.out.println("columnCount:"+columnCount);
final ResultSetMetaData meta = resultSet.getMetaData();
for(int i = 1; i<=columnCount; i++)
{
System.out.println(meta.getColumnName(i)+"|");
}
while(resultSet.next())
{
for(int i = 1; i<=columnCount; i++)
{
System.out.println(resultSet.getObject(i)+"|");
}
}
}
};
boolean isDefiningColumnTypes()
{
return false;
}
void defineColumnTypes(IntList columnTypes, java.sql.Statement statement)
throws SQLException
{
// default implementation does nothing, may be overwritten by subclasses
}
protected void close()
{
getConnectionPool().flush();
}
private static final DatabaseListener noopListener = new DatabaseListener()
{
public void load(Connection connection, PersistentState state)
{/* DOES NOTHING */}
public void search(Connection connection, Query query, boolean doCountOnly)
{/* DOES NOTHING */}
};
private DatabaseListener listener = noopListener;
private final Object listenerLock = new Object();
final DatabaseListener setListener(DatabaseListener listener)
{
if(listener==null)
listener = noopListener;
DatabaseListener result;
synchronized(listenerLock)
{
result = this.listener;
this.listener = listener;
}
if(result==noopListener)
result = null;
return result;
}
}
|
package com.knox.tree;
import com.knox.Asserts;
import com.knox.tree.printer.BinaryTreeInfo;
import com.knox.tree.printer.BinaryTrees;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
public class BinarySearchTree<T> implements BinaryTreeInfo {
public static abstract class Visitor<T> {
boolean stop;
// @return true,
abstract boolean visit(T element);
}
private TreeNode<T> root;
private int size;
private Comparator<T> comparator;
public BinarySearchTree(Comparator<T> comparator) {
this.comparator = comparator;
}
public BinarySearchTree() {
this(null);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void add(T element) {
elementNotNullCheck(element);
if (root == null) {
root = new TreeNode<T>(element, null);
size++;
return;
}
TreeNode<T> cur = root;
TreeNode<T> parent = root;
int cmp = 0;
while (cur != null) {
parent = cur;
cmp = compare(element, cur.value);
if (cmp < 0) {
cur = cur.left;
} else if (cmp > 0) {
cur = cur.right;
} else {
cur.value = element;
return;
}
}
TreeNode<T> newNode = new TreeNode(element, parent);
if (cmp < 0) {
parent.left = newNode;
} else {
parent.right = newNode;
}
size++;
}
public void remove(T element) {
}
public boolean contains(T element) {
return false;
}
public void clear() {
}
public int height() {
// return height_v1(root);
return height_v2();
}
/*
*
*
* :
* , height1
* 1. levelSize
* 2. , , 1
* 3. , levelSize1,
* 4. levelSize == 0, , queue.size(), height1
*
* */
private int height_v2() {
if (root == null) return 0;
Queue<TreeNode<T>> queue = new LinkedList<>();
queue.offer(root);
int levelSize = 1;
int height = 0;
while (!queue.isEmpty()) {
TreeNode<T> node = queue.poll();
levelSize
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
if (levelSize == 0) {
levelSize = queue.size();
height++;
}
}
return height;
}
/*
*
*
* 1.
* 2.
* 3. +1
* */
private int height_v1(TreeNode<T> node) {
if (node == null) return 0;
int leftHeight = height_v1(node.left);
int rightHeight = height_v1(node.right);
return Math.max(leftHeight, rightHeight) + 1;
}
public boolean isComplete() {
if (root == null) return true;
Queue<TreeNode<T>> queue = new LinkedList<>();
queue.offer(root);
boolean leaf = false;
while (!queue.isEmpty()) {
TreeNode<T> node = queue.poll();
if (leaf && !node.isLeaf()) return false;
if (node.left != null) {
queue.offer(node.left);
} else if (node.right != null) { // node.left == null && node.right != null
return false;
}
if (node.right != null) {
queue.offer(node.right);
} else {
// node.right == null ,
leaf = true;
}
}
return true;
}
private void elementNotNullCheck(T element) {
if (element == null) {
throw new NullPointerException("element should not be null");
}
}
private int compare(T lhs, T rhs) {
if (comparator != null) {
return comparator.compare(lhs, rhs);
} else {
return ((Comparable<T>)lhs).compareTo(rhs);
}
}
public void preorder(Visitor<T> visitor) {
if (visitor == null) return;
preorder(root, visitor);
}
private void preorder(TreeNode<T> root, Visitor<T> visitor) {
if (root == null || visitor.stop) return;
visitor.stop = visitor.visit(root.value);
preorder(root.left, visitor);
preorder(root.right, visitor);
}
public void inorder(Visitor<T> visitor) {
if (visitor == null) return;
inorder(root, visitor);
}
private void inorder(TreeNode<T> root, Visitor<T> visitor) {
if (root == null || visitor.stop) return;
inorder(root.left, visitor);
if (visitor.stop) return;
visitor.stop = visitor.visit(root.value);
inorder(root.right, visitor);
}
public void postorder(Visitor<T> visitor) {
if (visitor == null) return;
postorder(root, visitor);
}
private void postorder(TreeNode<T> root, Visitor<T> visitor) {
if (root == null || visitor.stop) return;
postorder(root.left, visitor);
postorder(root.right, visitor);
if (visitor.stop) return;
visitor.stop = visitor.visit(root.value);
}
public void levelOrder(Visitor<T> visitor) {
if (root == null || visitor == null) return;
Queue<TreeNode<T>> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode<T> node = queue.poll();
if (visitor.visit(node.value)) return;
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
@Override
public Object root() {
return root;
}
@Override
public Object left(Object node) {
return ((TreeNode<T>)node).left;
}
@Override
public Object right(Object node) {
return ((TreeNode<T>)node).right;
}
@Override
public Object string(Object node) {
TreeNode<T> treeNode = ((TreeNode<T>)node);
String parentStr = treeNode.parent == null ? "null" : treeNode.parent.value.toString();
return treeNode.value.toString() + "(" + parentStr + ")";
}
public static void main(String[] args) {
// BinarySearchTree<Integer> bst = createTree();
// BinaryTrees.print(bst);
// test_preoder(bst);
// test_inoder(bst);
// test_postoder(bst);
// test_isComplete();
test_height();;
// test_levelOrder();
}
private static void test_height() {
BinarySearchTree<Integer> bst = randomCreateTree(10);
BinaryTrees.print(bst);
System.out.println("height = " + bst.height());
}
private static void test_isComplete() {
{
Integer[] arr = new Integer[] {
7, 4, 9
};
BinarySearchTree<Integer> bst = createTree(arr);
Asserts.testTrue(bst.isComplete());
}
{
Integer[] arr = new Integer[] {
7, 4, 9, 2
};
BinarySearchTree<Integer> bst = createTree(arr);
Asserts.testTrue(bst.isComplete());
}
{
Integer[] arr = new Integer[] {
7, 4, 9, 8
};
BinarySearchTree<Integer> bst = createTree(arr);
Asserts.testFalse(bst.isComplete());
}
}
private static void test_preoder(BinarySearchTree<Integer> bst) {
LinkedList<Integer> ret = new LinkedList<>();
bst.preorder(new Visitor<Integer>() {
@Override
public boolean visit(Integer element) {
ret.add(element);
return element == 4;
}
});
System.out.println("preorder : " + ret.toString());
}
private static void test_inoder(BinarySearchTree<Integer> bst) {
LinkedList<Integer> ret = new LinkedList<>();
bst.inorder(new Visitor<Integer>() {
@Override
public boolean visit(Integer element) {
ret.add(element);
return false;
}
});
System.out.println("inorder : " + ret.toString());
}
private static void test_postoder(BinarySearchTree<Integer> bst) {
LinkedList<Integer> ret = new LinkedList<>();
bst.postorder(new Visitor<Integer>() {
@Override
public boolean visit(Integer element) {
ret.add(element);
return element == 4;
}
});
System.out.println("postorder : " + ret.toString());
}
private static void test_levelOrder() {
BinarySearchTree<Integer> bst = createTree();
BinaryTrees.print(bst);
LinkedList<Integer> ret = new LinkedList<>();
bst.levelOrder(new Visitor<Integer>() {
@Override
public boolean visit(Integer element) {
ret.add(element);
return element == 5;
}
});
System.out.println("levelOrder : " + ret.toString());
}
private static void test1() {
BinarySearchTree<Integer> bst = new BinarySearchTree<>(new Comparator<Integer>() {
// , javaComparator,
@Override
public int compare(Integer o1, Integer o2) {
return o1.intValue() - o2.intValue();
}
});
for (int i = 0; i < 10; i++) {
int value = (int)(Math.random() * 100);
bst.add(value);
}
BinaryTrees.print(bst);
}
private static BinarySearchTree<Integer> createTree() {
BinarySearchTree<Integer> bst = new BinarySearchTree<>();
int[] arr = new int[] {
7, 4, 9, 2, 5, 8, 11, 1, 3, 10, 12
};
for (int i = 0; i < arr.length; i++) {
bst.add(arr[i]);
}
return bst;
}
private static BinarySearchTree<Integer> createTree(Integer[] arr) {
BinarySearchTree<Integer> bst = new BinarySearchTree<>();
for (int i = 0; i < arr.length; i++) {
bst.add(arr[i]);
}
return bst;
}
private static BinarySearchTree<Integer> randomCreateTree(int size) {
Integer[] arr = new Integer[size];
for (int i = 0; i < size; i++) {
arr[i] = (int)(Math.random() * 100);
}
return createTree(arr);
}
}
|
package nl.nn.adapterframework.util;
import java.io.File;
import java.io.FilenameFilter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.lang.StringUtils;
/**
* @author John Dekker
* @version Id
*/
public class FileUtils {
public static final String version = "$RCSfile: FileUtils.java,v $ $Revision: 1.6 $ $Date: 2005-10-11 12:52:57 $";
public static String getFilename(String originalFilename, String filenamePattern, boolean uidParam) {
// no pattern defined, outputname = inputname
if (StringUtils.isEmpty(filenamePattern)) {
return originalFilename;
}
// obtain filename
int ndx = originalFilename.lastIndexOf('.');
String name = originalFilename;
String extension = "";
if (ndx > 0) {
name = originalFilename.substring(0, ndx);
extension = originalFilename.substring(ndx + 1);
}
Object[] params;
if (uidParam) {
params = new Object[] { name, extension, new Date(), Misc.createSimpleUUID()};
}
else {
params = new Object[] { name, extension, new Date()};
}
return MessageFormat.format(filenamePattern, params).toString();
}
public static String getFilename(File originalFile, String filenamePattern, boolean uidParam) {
return getFilename(originalFile.getName(), filenamePattern, uidParam);
}
public static String moveFile(File orgFile, File rename2File, int nrRetries, long waitTime) throws InterruptedException {
int errCount = 0;
while (errCount++ < nrRetries) {
// Move file to new directory
boolean success = orgFile.renameTo(rename2File);
if (! success) {
Thread.sleep(waitTime);
}
else {
return rename2File.getAbsolutePath();
}
}
return null;
}
public static File[] getFiles(String directory, String wildcard) {
WildCardFilter filter = new WildCardFilter(wildcard);
File dir = new File(directory);
File[] files = dir.listFiles(filter);
ArrayList result = new ArrayList();
int count = (files == null ? 0 : files.length);
for (int i = 0; i < count; i++) {
File file = files[i];
if (file.isDirectory()) {
continue;
}
result.add(file);
}
return (File[])result.toArray(new File[0]);
}
public static File getFirstMatchingFile(String directory, String wildcard) {
File[] files = getFiles(directory, wildcard);
if (files.length > 0)
return files[0];
return null;
}
public static File[] getFiles(String directory, final String[] names) {
File dir = new File(directory);
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
for (int i = 0; i < names.length; i++) {
if (name.equals(names[i]))
return true;
}
return false;
}
});
ArrayList result = new ArrayList();
int count = (files == null ? 0 : files.length);
for (int i = 0; i < count; i++) {
File file = files[i];
if (file.isDirectory()) {
continue;
}
result.add(file);
}
return (File[])result.toArray(new File[0]);
}
public static File getFirstMatchingFile(String directory, String[] names) {
File[] files = getFiles(directory, names);
if (files.length > 0)
return files[0];
return null;
}
public static List getListFromNames(String names, char seperator) {
StringTokenizer st = new StringTokenizer(names, "" + seperator);
LinkedList list = new LinkedList();
while (st.hasMoreTokens()) {
list.add(st.nextToken());
}
return list;
}
public static List getListFromNames(String[] names) {
if (names == null)
return null;
return Arrays.asList(names);
}
public static String getNamesFromArray(String[] names, char seperator) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < names.length; i++) {
String name = names[i];
if (result.length() > 0)
result.append(seperator);
result.append(name);
}
return result.toString();
}
public static String getNamesFromList(List filenames, char seperator) {
if (filenames == null)
return "";
StringBuffer result = new StringBuffer();
for (Iterator nameIterator = filenames.iterator(); nameIterator.hasNext();) {
String name = (String)nameIterator.next();
if (result.length() > 0)
result.append(seperator);
result.append(name);
}
return result.toString();
}
/*
* methods to create a fixed length string from a value
*/
public static String align(String val, int length, boolean leftAlign, char fillchar) {
StringBuffer result = new StringBuffer();
align(result, val, length, leftAlign, fillchar);
return result.toString();
}
public static void align(StringBuffer result, String val, int length, boolean leftAlign, char fillchar) {
if (val.length() > length) {
result.append(val.substring(0, length));
}
else if (val.length() == length) {
result.append(val);
}
else {
char[] fill = getFilledArray(length - val.length(), fillchar);
if (leftAlign) {
result.append(val).append(fill);
}
else {
result.append(fill).append(val);
}
}
}
/*
* create a filled array
*/
public static char[] getFilledArray(int length, char fillchar) {
char[] fill = new char[length];
Arrays.fill(fill, fillchar);
return fill;
}
}
|
package net.minecraftforge.liquids;
import static cpw.mods.fml.relauncher.Side.CLIENT;
import com.google.common.base.Objects;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFluid;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Icon;
/**
* ItemStack substitute for liquids
* Things of note: they are equal if their items are equal. Amount does NOT matter for java equals() testing
* <br/>
* The canonical liquidstack is probably the only one that has a lot of the rendering data on it. Use {@link #canonical()}
* to get it.
*
* @author SirSengir
*/
public class LiquidStack
{
public final int itemID;
public int amount;
public final int itemMeta;
public LiquidStack(int itemID, int amount) { this(itemID, amount, 0); }
public LiquidStack(Item item, int amount) { this(item.itemID, amount, 0); }
public LiquidStack(Block block, int amount) { this(block.blockID, amount, 0); }
public LiquidStack(int itemID, int amount, int itemDamage)
{
this.itemID = itemID;
this.amount = amount;
this.itemMeta = itemDamage;
}
public NBTTagCompound writeToNBT(NBTTagCompound nbt)
{
nbt.setInteger("Amount", amount);
nbt.setShort("Id", (short)itemID);
nbt.setShort("Meta", (short)itemMeta);
nbt.setString("LiquidName", LiquidDictionary.findLiquidName(this));
return nbt;
}
/**
* NO-OP now. Use {@link #loadLiquidStackFromNBT(NBTTagCompound)} to get a new instance
*
* @param nbt
*/
@Deprecated
public void readFromNBT(NBTTagCompound nbt)
{
}
/**
* @return A copy of this LiquidStack
*/
public LiquidStack copy()
{
return new LiquidStack(itemID, amount, itemMeta);
}
/**
* @param other
* @return true if this LiquidStack contains the same liquid as the one passed in.
*/
public boolean isLiquidEqual(LiquidStack other)
{
return other != null && itemID == other.itemID && itemMeta == other.itemMeta;
}
/**
* @param other
* @return true if this LiquidStack contains the other liquid (liquids are equal and amount >= other.amount).
*/
public boolean containsLiquid(LiquidStack other)
{
return isLiquidEqual(other) && amount >= other.amount;
}
/**
* @param other ItemStack containing liquids.
* @return true if this LiquidStack contains the same liquid as the one passed in.
*/
public boolean isLiquidEqual(ItemStack other)
{
if (other == null)
{
return false;
}
if (itemID == other.itemID && itemMeta == other.getItemDamage())
{
return true;
}
return isLiquidEqual(LiquidContainerRegistry.getLiquidForFilledItem(other));
}
/**
* @return ItemStack representation of this LiquidStack
*/
public ItemStack asItemStack()
{
return new ItemStack(itemID, 1, itemMeta);
}
/**
* Reads a liquid stack from the passed nbttagcompound and returns it.
*
* @param nbt
* @return the liquid stack
*/
public static LiquidStack loadLiquidStackFromNBT(NBTTagCompound nbt)
{
if (nbt == null)
{
return null;
}
String liquidName = nbt.getString("LiquidName");
int itemID = nbt.getShort("Id");
int itemMeta = nbt.getShort("Meta");
LiquidStack liquid = LiquidDictionary.getCanonicalLiquid(liquidName);
if(liquid != null) {
itemID = liquid.itemID;
itemMeta = liquid.itemMeta;
}
// if the item is not existent, and no liquid dictionary is found, null returns
else if (Item.itemsList[itemID] == null)
{
return null;
}
int amount = nbt.getInteger("Amount");
LiquidStack liquidstack = new LiquidStack(itemID, amount, itemMeta);
return liquidstack.itemID == 0 ? null : liquidstack;
}
private String textureSheet = "/terrain.png";
/**
* Return the textureSheet used for this liquid stack's texture Icon
* Defaults to '/terrain.png'
*
* See {@link #getRenderingIcon()} for the actual icon
*
* @return The texture sheet
*/
public String getTextureSheet()
{
return textureSheet;
}
/**
* Set the texture sheet for this icon (usually /terrain.png or /gui/items.png)
*
* See also the {@link #setRenderingIcon(Icon)} for the icon itself
*
* @param textureSheet
* @return the liquid stack
*/
public LiquidStack setTextureSheet(String textureSheet)
{
this.textureSheet = textureSheet;
return this;
}
@SideOnly(CLIENT)
private Icon renderingIcon;
/**
* Get the rendering icon for this liquid stack, for presentation in the world or in GUIs.
* Defaults to handling water and lava, and returns the set rendering icon otherwise.
*
* See {@link #getTextureSheet()} to get the texture sheet this icon is associated with
*
* @return The icon for rendering this liquid
*/
@SideOnly(CLIENT)
public Icon getRenderingIcon()
{
if (itemID == Block.waterStill.blockID)
{
return BlockFluid.func_94424_b("water");
}
else if (itemID == Block.lavaStill.blockID)
{
return BlockFluid.func_94424_b("lava");
}
return renderingIcon;
}
/**
* Set the icon for rendering this liquid
* It should be refreshed whenever textures are refreshed.
*
* See also {@link #setTextureSheet(String)} for setting the sheet this icon is associated with
*
* @param icon The icon to render
* @return The liquid stack
*/
@SideOnly(CLIENT)
public LiquidStack setRenderingIcon(Icon icon)
{
this.renderingIcon = icon;
return this;
}
@Override
public final int hashCode()
{
return 31 * itemMeta + itemID;
}
@Override
public final boolean equals(Object ob)
{
if (ob instanceof LiquidStack)
{
LiquidStack ls = (LiquidStack)ob;
return ls.itemID == itemID && ls.itemMeta == itemMeta;
}
return false;
}
/**
* Get the canonical version of this liquid stack (will contain things like icons and texturesheets)
* @return The canonical liquidstack
*/
public LiquidStack canonical()
{
return LiquidDictionary.getCanonicalLiquid(this);
}
}
|
package org.usfirst.frc.team340.robot.subsystems;
import org.usfirst.frc.team340.robot.RobotMap;
import edu.wpi.first.wpilibj.AnalogPotentiometer;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.TalonSRX;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*Dummy subsystem for a simple Arm with a claw at the end. Includes motors, solenoids, and digital sensors.
*@version 1.0
*/
public class ExampleClawArm extends Subsystem {
// Put methods for controlling this subsystem
// here. Call these from Commands.
private TalonSRX armMotor;
private TalonSRX clawMotor;
private Solenoid leftPiston;
private Solenoid rightPiston;
private AnalogPotentiometer armAngleSensor;
private DigitalInput bottomSwitch;
private DigitalInput topSwitch;
public ExampleClawArm() {
armMotor = new TalonSRX(RobotMap.ClawArmMotor);
clawMotor = new TalonSRX(RobotMap.ClawTopMotor);
leftPiston = new Solenoid(RobotMap.ClawLeftPiston);
rightPiston = new Solenoid(RobotMap.ClawRightPiston);
armAngleSensor = new AnalogPotentiometer(RobotMap.ClawArmAngleSensor);
bottomSwitch = new DigitalInput(RobotMap.ClawBottomSwitch);
topSwitch = new DigitalInput(RobotMap.ClawTopSwitch);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
public void openClaw() {
leftPiston.set(true);
rightPiston.set(true);
}
public void closeClaw() {
leftPiston.set(false);
rightPiston.set(false);
}
public void armDown(double speed) {
armMotor.set(-speed);
}
public void armUp(double speed) {
armMotor.set(speed);
}
public void armStop() {
armMotor.set(0);
}
public boolean armAtBottom() {
return ((armAngleSensor.get() < 1) || bottomSwitch.get());
}
public boolean armAtTop() {
return ((armAngleSensor.get() > 179) || topSwitch.get());
}
public double armPosition() {
return armAngleSensor.get();
}
}
|
package test;
public class Test {
public static void main(String[] args) {
System.out.println("Test");
}
}
|
package org.azavea.otm.fields;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.azavea.helpers.JSONHelper;
import org.azavea.otm.App;
import org.azavea.otm.R;
import org.azavea.otm.data.Plot;
import org.azavea.otm.data.UDFCollectionDefinition;
import org.azavea.otm.ui.TreeEditDisplay;
import org.azavea.otm.ui.UDFCollectionCreateActivity;
import org.azavea.otm.ui.UDFCollectionEditActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.collect.Collections2.filter;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.partition;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Collections2.transform;
/**
* UDF Collections are odd and don't really fit into the ecosystem of other fields.
* <p>
* A UDF collection has one or more keys, and each entry on a Model has a list of zero or more
* entries per UDF collection field
* <p>
* Each UDFCollectionFieldGroup can have multiple UDF collection fields that are shown in that group
* All collection entries are merged together by a sort key, which *must* exist on every collection
* UDF in the group.
* <p>
* It isn't known until we pull the values from the Plot and Tree models how many rows we
* will need to display.
* As such, it doesn't make it's Field(s) until it is rendered, and the number of Fields may change
*/
public class UDFCollectionFieldGroup extends FieldGroup {
private static final int NUM_FIELDS_PER_CLICK = 3;
private final String title;
private final String sortKey;
private final LinkedHashMap<String, UDFCollectionDefinition> udfDefinitions = new LinkedHashMap<>();
private final LinkedHashMap<String, UDFCollectionDefinition> editableUdfDefinitions = new LinkedHashMap<>();
private final List<String> fieldKeys;
private ViewGroup fieldContainer;
private List<UDFCollectionValueField> fields;
public UDFCollectionFieldGroup(JSONObject groupDefinition,
Map<String, JSONObject> fieldDefinitions) throws JSONException {
title = groupDefinition.optString("header");
sortKey = groupDefinition.optString("sort_key");
fieldKeys = JSONHelper.jsonStringArrayToList(groupDefinition.getJSONArray("collection_udf_keys"));
for (String key : fieldKeys) {
if (fieldDefinitions.containsKey(key)) {
final UDFCollectionDefinition udfDef = new UDFCollectionDefinition(fieldDefinitions.get(key));
udfDefinitions.put(key, udfDef);
if (udfDef.isWritable()) {
editableUdfDefinitions.put(key, udfDef);
}
}
}
}
/**
* Render a field group and its child fields for viewing
*/
@Override
public View renderForDisplay(LayoutInflater inflater, Plot plot, Activity activity, ViewGroup parent) {
return render(inflater, plot, activity, parent, DisplayMode.VIEW);
}
/**
* Render a field group and its child fields for editing
*/
@Override
public View renderForEdit(LayoutInflater inflater, Plot plot, Activity activity, ViewGroup parent) {
return render(inflater, plot, activity, parent, DisplayMode.EDIT);
}
@Override
public void receiveActivityResult(int resultCode, Intent data, Activity activity) {
for (String key : editableUdfDefinitions.keySet()) {
if (data.getExtras().containsKey(key)) {
final String json = data.getStringExtra(key);
final UDFCollectionDefinition udfDef = editableUdfDefinitions.get(key);
final JSONObject value;
try {
value = new JSONObject(json);
} catch (JSONException e) {
Log.e(App.LOG_TAG, "Error parsing JSON passed as activity result", e);
continue;
}
final UDFCollectionValueField field = new UDFCollectionValueField(udfDef, sortKey, value);
if (data.getExtras().containsKey(UDFCollectionEditActivity.TAG)) {
final int tag = data.getIntExtra(UDFCollectionEditActivity.TAG, -1);
if (tag == -1 || fields.isEmpty()) {
Log.w(App.LOG_TAG, "Invalid tag for UDF, ignoring it");
} else {
// If we received a modified field, remove the old field and add it back with new data
fields = newArrayList(concat(filter(fields, f -> f.getTag() != tag), newArrayList(field)));
}
} else {
fields.add(field);
}
}
}
replaceEditFields(activity);
}
@Override
public void update(Plot plot) {
Map<String, JSONArray> collectionUdfArrays = new HashMap<>(fieldKeys.size());
for (String collectionKey : fieldKeys) {
collectionUdfArrays.put(collectionKey, new JSONArray());
}
for (Field field : fields) {
String collectionKey = field.key;
if (collectionUdfArrays.containsKey(collectionKey)) {
JSONArray udfData = collectionUdfArrays.get(collectionKey);
udfData.put(field.getEditedValue());
} else {
Log.w(App.LOG_TAG, "Impossible state - UDFCollectionGroup has a field not in it's fieldKeys");
}
}
for (Map.Entry<String, JSONArray> entry : collectionUdfArrays.entrySet()) {
try {
plot.setValueForKey(entry.getKey(), entry.getValue());
} catch (Exception e) {
// TODO: Extract String
Toast.makeText(App.getAppInstance(), "Error saving Stewardship fields", Toast.LENGTH_SHORT).show();
}
}
}
/**
* Handles the common functionality between rendering collection UDFs for edit and for display
* Dispatches to helpers for those parts which are different based on DisplayMode
*/
private View render(LayoutInflater inflater, Plot plot, Activity activity, ViewGroup parent, DisplayMode mode) {
if (getCurrentUdfDefinitions(mode).isEmpty()) {
// If there are no udfDefinitions, we shouldn't show the group at all
return null;
}
final View groupContainer = inflater.inflate(R.layout.collection_udf_field_group, parent, false);
final TextView groupLabel = (TextView) groupContainer.findViewById(R.id.group_name);
groupLabel.setText(title);
final View buttonContainer = groupContainer.findViewById(R.id.udf_button_container);
final Button button = (Button) groupContainer.findViewById(R.id.udf_button);
fields = getFields(plot, mode);
fieldContainer = (LinearLayout) groupContainer.findViewById(R.id.fields);
final Collection<View> fieldViews = getViewsForFields(inflater, activity, mode);
if (mode == DisplayMode.VIEW) {
setupFieldsForDisplay(inflater, buttonContainer, button, fieldViews);
} else {
setupFieldsForEdit(button, fieldViews, activity);
}
return groupContainer;
}
private void setupFieldsForDisplay(LayoutInflater inflater, View buttonContainer, Button button,
Collection<View> fieldViews) {
button.setText(R.string.load_more_collection_udf);
if (fieldViews.isEmpty()) {
inflater.inflate(R.layout.collection_udf_empty, fieldContainer);
buttonContainer.setVisibility(View.GONE);
} else {
// We only want to show so many fields at a time, and add more when a "Show More" button is clicked
final List<List<View>> fieldViewGroups = newArrayList(partition(fieldViews, NUM_FIELDS_PER_CLICK));
addFieldsToGroup(fieldViewGroups.remove(0), fieldContainer);
if (fieldViewGroups.isEmpty()) {
buttonContainer.setVisibility(View.GONE);
} else {
button.setOnClickListener(v -> {
addFieldsToGroup(fieldViewGroups.remove(0), fieldContainer);
if (fieldViewGroups.isEmpty()) {
buttonContainer.setVisibility(View.GONE);
}
});
}
}
}
private void setupFieldsForEdit(Button button, Collection<View> fieldViews, Activity activity) {
// TODO: String extraction
button.setText("Add New");
for (View view : fieldViews) {
fieldContainer.addView(view);
}
button.setOnClickListener(v -> {
Intent udfCreator = new Intent(App.getAppInstance(), UDFCollectionCreateActivity.class);
udfCreator.putParcelableArrayListExtra(UDFCollectionCreateActivity.UDF_DEFINITIONS,
newArrayList(editableUdfDefinitions.values()));
activity.startActivityForResult(udfCreator, TreeEditDisplay.FIELD_ACTIVITY_REQUEST_CODE);
});
}
private void replaceEditFields(Activity activity) {
fieldContainer.removeAllViews();
Collections.sort(fields);
LayoutInflater inflater = activity.getLayoutInflater();
Collection<View> fieldViews = getViewsForFields(inflater, activity, DisplayMode.EDIT);
for (View view : fieldViews) {
fieldContainer.addView(view);
}
}
private List<UDFCollectionValueField> getFields(Plot plot, DisplayMode mode) {
final List<UDFCollectionValueField> fieldsList = newArrayList();
for (UDFCollectionDefinition udfDef : getCurrentUdfDefinitions(mode).values()) {
JSONArray collectionValues = (JSONArray) plot.getValueForKey(udfDef.getCollectionKey());
if (!JSONObject.NULL.equals(collectionValues)) {
for (int i = 0; i < collectionValues.length(); i++) {
JSONObject value = collectionValues.optJSONObject(i);
fieldsList.add(new UDFCollectionValueField(udfDef, sortKey, value));
}
}
}
return fieldsList;
}
private Map<String, UDFCollectionDefinition> getCurrentUdfDefinitions(DisplayMode mode) {
return (mode == DisplayMode.VIEW) ? udfDefinitions : editableUdfDefinitions;
}
private Collection<View> getViewsForFields(LayoutInflater inflater, Activity activity, DisplayMode mode) {
Collections.sort(fields);
return filter(transform(fields, field -> {
try {
if (mode == DisplayMode.VIEW) {
return field.renderForDisplay(inflater, activity, fieldContainer);
} else {
return field.renderForEdit(inflater, activity, fieldContainer);
}
} catch (JSONException e) {
return null;
}
}), view -> view != null);
}
private void addFieldsToGroup(List<View> fieldGroup, ViewGroup parent) {
for (View fieldView : fieldGroup) {
parent.addView(fieldView);
}
}
}
|
package com.hubspot.singularity;
import static com.hubspot.singularity.JsonHelpers.copyOfList;
import static com.hubspot.singularity.JsonHelpers.copyOfSet;
import static com.hubspot.singularity.JsonHelpers.copyOfMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.hubspot.deploy.ExecutorData;
import com.hubspot.mesos.Resources;
import com.hubspot.mesos.SingularityContainerInfo;
import com.hubspot.mesos.SingularityMesosTaskLabel;
import com.wordnik.swagger.annotations.ApiModelProperty;
public class SingularityDeploy {
private final String requestId;
private final String id;
private final Optional<String> version;
private final Optional<Long> timestamp;
private final Optional<Map<String, String>> metadata;
private final Optional<SingularityContainerInfo> containerInfo;
private final Optional<String> customExecutorCmd;
private final Optional<String> customExecutorId;
private final Optional<String> customExecutorSource;
private final Optional<Resources> customExecutorResources;
private final Optional<Resources> resources;
private final Optional<String> command;
private final Optional<List<String>> arguments;
private final Optional<Map<String, String>> env;
private final Optional<List<String>> uris;
private final Optional<ExecutorData> executorData;
private final Optional<Map<String, String>> labels;
private final Optional<List<SingularityMesosTaskLabel>> mesosLabels;
private final Optional<Map<Integer, Map<String, String>>> taskLabels;
private final Optional<Map<Integer, List<SingularityMesosTaskLabel>>> mesosTaskLabels;
private final Optional<Map<Integer, Map<String, String>>> taskEnv;
private final Optional<String> healthcheckUri;
private final Optional<Long> healthcheckIntervalSeconds;
private final Optional<Long> healthcheckTimeoutSeconds;
private final Optional<Integer> healthcheckPortIndex;
private final Optional<Boolean> skipHealthchecksOnDeploy;
private final Optional<HealthcheckProtocol> healthcheckProtocol;
private final Optional<Integer> healthcheckMaxRetries;
private final Optional<Long> healthcheckMaxTotalTimeoutSeconds;
private final Optional<Long> deployHealthTimeoutSeconds;
private final Optional<Long> considerHealthyAfterRunningForSeconds;
private final Optional<String> serviceBasePath;
private final Optional<Set<String>> loadBalancerGroups;
private final Optional<Integer> loadBalancerPortIndex;
private final Optional<Map<String, Object>> loadBalancerOptions;
private final Optional<Set<String>> loadBalancerDomains;
private final Optional<List<String>> loadBalancerAdditionalRoutes;
private final Optional<String> loadBalancerTemplate;
private final Optional<String> loadBalancerServiceIdOverride;
private final Optional<String> loadBalancerUpstreamGroup;
private final Optional<Integer> deployInstanceCountPerStep;
private final Optional<Integer> deployStepWaitTimeMs;
private final Optional<Boolean> autoAdvanceDeploySteps;
private final Optional<Integer> maxTaskRetries;
private final Optional<Boolean> shell;
private final Optional<String> user;
public static SingularityDeployBuilder newBuilder(String requestId, String id) {
return new SingularityDeployBuilder(requestId, id);
}
@JsonCreator
public SingularityDeploy(@JsonProperty("requestId") String requestId,
@JsonProperty("id") String id,
@JsonProperty("command") Optional<String> command,
@JsonProperty("arguments") Optional<List<String>> arguments,
@JsonProperty("containerInfo") Optional<SingularityContainerInfo> containerInfo,
@JsonProperty("customExecutorCmd") Optional<String> customExecutorCmd,
@JsonProperty("customExecutorId") Optional<String> customExecutorId,
@JsonProperty("customExecutorSource") Optional<String> customExecutorSource,
@JsonProperty("customExecutorResources") Optional<Resources> customExecutorResources,
@JsonProperty("resources") Optional<Resources> resources,
@JsonProperty("env") Optional<Map<String, String>> env,
@JsonProperty("taskEnv") Optional<Map<Integer, Map<String, String>>> taskEnv,
@JsonProperty("uris") Optional<List<String>> uris,
@JsonProperty("metadata") Optional<Map<String, String>> metadata,
@JsonProperty("executorData") Optional<ExecutorData> executorData,
@JsonProperty("version") Optional<String> version,
@JsonProperty("timestamp") Optional<Long> timestamp,
@JsonProperty("labels") Optional<Map<String, String>> labels,
@JsonProperty("mesosLabels") Optional<List<SingularityMesosTaskLabel>> mesosLabels,
@JsonProperty("taskLabels") Optional<Map<Integer, Map<String, String>>> taskLabels,
@JsonProperty("mesosTaskLabels") Optional<Map<Integer, List<SingularityMesosTaskLabel>>> mesosTaskLabels,
@JsonProperty("deployHealthTimeoutSeconds") Optional<Long> deployHealthTimeoutSeconds,
@JsonProperty("healthcheckUri") Optional<String> healthcheckUri,
@JsonProperty("healthcheckIntervalSeconds") Optional<Long> healthcheckIntervalSeconds,
@JsonProperty("healthcheckTimeoutSeconds") Optional<Long> healthcheckTimeoutSeconds,
@JsonProperty("healthcheckPortIndex") Optional<Integer> healthcheckPortIndex,
@JsonProperty("healthcheckMaxRetries") Optional<Integer> healthcheckMaxRetries,
@JsonProperty("healthcheckMaxTotalTimeoutSeconds") Optional<Long> healthcheckMaxTotalTimeoutSeconds,
@JsonProperty("serviceBasePath") Optional<String> serviceBasePath,
@JsonProperty("loadBalancerGroups") Optional<Set<String>> loadBalancerGroups,
@JsonProperty("loadBalancerPortIndex") Optional<Integer> loadBalancerPortIndex,
@JsonProperty("considerHealthyAfterRunningForSeconds") Optional<Long> considerHealthyAfterRunningForSeconds,
@JsonProperty("loadBalancerOptions") Optional<Map<String, Object>> loadBalancerOptions,
@JsonProperty("loadBalancerDomains") Optional<Set<String>> loadBalancerDomains,
@JsonProperty("loadBalancerAdditionalRoutes") Optional<List<String>> loadBalancerAdditionalRoutes,
@JsonProperty("loadBalancerTemplate") Optional<String> loadBalancerTemplate,
@JsonProperty("loadBalancerServiceIdOverride") Optional<String> loadBalancerServiceIdOverride,
@JsonProperty("loadBalancerUpstreamGroup") Optional<String> loadBalancerUpstreamGroup,
@JsonProperty("skipHealthchecksOnDeploy") Optional<Boolean> skipHealthchecksOnDeploy,
@JsonProperty("healthCheckProtocol") Optional<HealthcheckProtocol> healthcheckProtocol,
@JsonProperty("deployInstanceCountPerStep") Optional<Integer> deployInstanceCountPerStep,
@JsonProperty("deployStepWaitTimeMs") Optional<Integer> deployStepWaitTimeMs,
@JsonProperty("autoAdvanceDeploySteps") Optional<Boolean> autoAdvanceDeploySteps,
@JsonProperty("maxTaskRetries") Optional<Integer> maxTaskRetries,
@JsonProperty("shell") Optional<Boolean> shell,
@JsonProperty("user") Optional<String> user) {
this.requestId = requestId;
this.command = command;
this.arguments = arguments;
this.resources = resources;
this.containerInfo = containerInfo;
this.customExecutorCmd = customExecutorCmd;
this.customExecutorId = customExecutorId;
this.customExecutorSource = customExecutorSource;
this.customExecutorResources = customExecutorResources;
this.metadata = metadata;
this.version = version;
this.id = id;
this.timestamp = timestamp;
this.env = env;
this.taskEnv = taskEnv;
this.uris = uris;
this.executorData = executorData;
this.labels = labels;
this.mesosLabels = mesosLabels.or(labels.isPresent() ? Optional.of(SingularityMesosTaskLabel.labelsFromMap(labels.get())) : Optional.<List<SingularityMesosTaskLabel>>absent());
this.taskLabels = taskLabels;
this.mesosTaskLabels = mesosTaskLabels.or(taskLabels.isPresent() ? Optional.of(parseMesosTaskLabelsFromMap(taskLabels.get())) : Optional.<Map<Integer,List<SingularityMesosTaskLabel>>>absent());
this.healthcheckUri = healthcheckUri;
this.healthcheckIntervalSeconds = healthcheckIntervalSeconds;
this.healthcheckTimeoutSeconds = healthcheckTimeoutSeconds;
this.healthcheckPortIndex = healthcheckPortIndex;
this.skipHealthchecksOnDeploy = skipHealthchecksOnDeploy;
this.healthcheckProtocol = healthcheckProtocol;
this.healthcheckMaxRetries = healthcheckMaxRetries;
this.healthcheckMaxTotalTimeoutSeconds = healthcheckMaxTotalTimeoutSeconds;
this.considerHealthyAfterRunningForSeconds = considerHealthyAfterRunningForSeconds;
this.deployHealthTimeoutSeconds = deployHealthTimeoutSeconds;
this.serviceBasePath = serviceBasePath;
this.loadBalancerGroups = loadBalancerGroups;
this.loadBalancerPortIndex = loadBalancerPortIndex;
this.loadBalancerOptions = loadBalancerOptions;
this.loadBalancerDomains = loadBalancerDomains;
this.loadBalancerAdditionalRoutes = loadBalancerAdditionalRoutes;
this.loadBalancerTemplate = loadBalancerTemplate;
this.loadBalancerServiceIdOverride = loadBalancerServiceIdOverride;
this.loadBalancerUpstreamGroup = loadBalancerUpstreamGroup;
this.deployInstanceCountPerStep = deployInstanceCountPerStep;
this.deployStepWaitTimeMs = deployStepWaitTimeMs;
this.autoAdvanceDeploySteps = autoAdvanceDeploySteps;
this.maxTaskRetries = maxTaskRetries;
this.shell = shell;
this.user = user;
}
private static Map<Integer, List<SingularityMesosTaskLabel>> parseMesosTaskLabelsFromMap(Map<Integer, Map<String, String>> taskLabels) {
Map<Integer, List<SingularityMesosTaskLabel>> mesosTaskLabels = new HashMap<>();
for (Map.Entry<Integer, Map<String, String>> entry : taskLabels.entrySet()) {
mesosTaskLabels.put(entry.getKey(), SingularityMesosTaskLabel.labelsFromMap(entry.getValue()));
}
return mesosTaskLabels;
}
public SingularityDeployBuilder toBuilder() {
return new SingularityDeployBuilder(requestId, id)
.setCommand(command)
.setArguments(copyOfList(arguments))
.setResources(resources)
.setContainerInfo(containerInfo)
.setCustomExecutorCmd(customExecutorCmd)
.setCustomExecutorId(customExecutorId)
.setCustomExecutorSource(customExecutorSource)
.setCustomExecutorResources(customExecutorResources)
.setHealthcheckUri(healthcheckUri)
.setHealthcheckIntervalSeconds(healthcheckIntervalSeconds)
.setHealthcheckTimeoutSeconds(healthcheckTimeoutSeconds)
.setHealthcheckPortIndex(healthcheckPortIndex)
.setSkipHealthchecksOnDeploy(skipHealthchecksOnDeploy)
.setHealthcheckProtocol(healthcheckProtocol)
.setHealthcheckMaxRetries(healthcheckMaxRetries)
.setHealthcheckMaxTotalTimeoutSeconds(healthcheckMaxTotalTimeoutSeconds)
.setConsiderHealthyAfterRunningForSeconds(considerHealthyAfterRunningForSeconds)
.setDeployHealthTimeoutSeconds(deployHealthTimeoutSeconds)
.setServiceBasePath(serviceBasePath)
.setLoadBalancerGroups(copyOfSet(loadBalancerGroups))
.setLoadBalancerPortIndex(loadBalancerPortIndex)
.setLoadBalancerOptions(copyOfMap(loadBalancerOptions))
.setLoadBalancerDomains(copyOfSet(loadBalancerDomains))
.setLoadBalancerAdditionalRoutes(copyOfList(loadBalancerAdditionalRoutes))
.setLoadBalancerTemplate(loadBalancerTemplate)
.setLoadBalancerUpstreamGroup(loadBalancerUpstreamGroup)
.setLoadBalancerServiceIdOverride(loadBalancerServiceIdOverride)
.setMetadata(copyOfMap(metadata))
.setVersion(version)
.setTimestamp(timestamp)
.setEnv(copyOfMap(env))
.setTaskEnv(taskEnv)
.setUris(copyOfList(uris))
.setExecutorData(executorData)
.setLabels(labels)
.setMesosLabels(mesosLabels)
.setTaskLabels(taskLabels)
.setMesosTaskLabels(mesosTaskLabels)
.setDeployInstanceCountPerStep(deployInstanceCountPerStep)
.setDeployStepWaitTimeMs(deployStepWaitTimeMs)
.setAutoAdvanceDeploySteps(autoAdvanceDeploySteps)
.setMaxTaskRetries(maxTaskRetries)
.setShell(shell)
.setUser(user);
}
@ApiModelProperty(required=false, value="Number of seconds that Singularity waits for this service to become healthy (for it to download artifacts, start running, and optionally pass healthchecks.)")
public Optional<Long> getDeployHealthTimeoutSeconds() {
return deployHealthTimeoutSeconds;
}
@ApiModelProperty(required=true, value="Singularity Request Id which is associated with this deploy.")
public String getRequestId() {
return requestId;
}
@ApiModelProperty(required=true, value="Singularity deploy id.")
public String getId() {
return id;
}
@ApiModelProperty(required=false, value="Deploy version")
public Optional<String> getVersion() {
return version;
}
@ApiModelProperty(required=false, value="Deploy timestamp.")
public Optional<Long> getTimestamp() {
return timestamp;
}
@ApiModelProperty(required=false, value="Map of metadata key/value pairs associated with the deployment.")
public Optional<Map<String, String>> getMetadata() {
return metadata;
}
@ApiModelProperty(required=false, value="Container information for deployment into a container.", dataType="SingularityContainerInfo")
public Optional<SingularityContainerInfo> getContainerInfo() {
return containerInfo;
}
@ApiModelProperty(required=false, value="Custom Mesos executor", dataType="string")
public Optional<String> getCustomExecutorCmd() {
return customExecutorCmd;
}
@ApiModelProperty(required=false, value="Custom Mesos executor id.", dataType="string")
public Optional<String> getCustomExecutorId() {
return customExecutorId;
}
@ApiModelProperty(required=false, value="Custom Mesos executor source.", dataType="string")
public Optional<String> getCustomExecutorSource() { return customExecutorSource; }
@ApiModelProperty(required=false, value="Resources to allocate for custom mesos executor", dataType="com.hubspot.mesos.Resources")
public Optional<Resources> getCustomExecutorResources() {
return customExecutorResources;
}
@ApiModelProperty(required=false, value="Resources required for this deploy.", dataType="com.hubspot.mesos.Resources")
public Optional<Resources> getResources() {
return resources;
}
@ApiModelProperty(required=false, value="Command to execute for this deployment.")
public Optional<String> getCommand() {
return command;
}
@ApiModelProperty(required=false, value="Command arguments.")
public Optional<List<String>> getArguments() {
return arguments;
}
@ApiModelProperty(required=false, value="Map of environment variable definitions.")
public Optional<Map<String, String>> getEnv() {
return env;
}
@ApiModelProperty(required=false, value="Map of environment variable overrides for specific task instances.")
public Optional<Map<Integer, Map<String, String>>> getTaskEnv() {
return taskEnv;
}
@ApiModelProperty(required=false, value="List of URIs to download before executing the deploy command.")
public Optional<List<String>> getUris() {
return uris;
}
@ApiModelProperty(required=false, value="Executor specific information")
public Optional<ExecutorData> getExecutorData() {
return executorData;
}
@ApiModelProperty(required=false, value="Deployment Healthcheck URI, if specified will be called after TASK_RUNNING.")
public Optional<String> getHealthcheckUri() {
return healthcheckUri;
}
@ApiModelProperty(required=false, value="Healthcheck protocol - HTTP or HTTPS", dataType="com.hubspot.singularity.HealthcheckProtocol")
public Optional<HealthcheckProtocol> getHealthcheckProtocol() {
return healthcheckProtocol;
}
@ApiModelProperty(required=false, value="Time to wait after a failed healthcheck to try again in seconds.")
public Optional<Long> getHealthcheckIntervalSeconds() {
return healthcheckIntervalSeconds;
}
@ApiModelProperty(required=false, value="Single healthcheck HTTP timeout in seconds.")
public Optional<Long> getHealthcheckTimeoutSeconds() {
return healthcheckTimeoutSeconds;
}
@ApiModelProperty(required=false, value="Perform healthcheck on this dynamically allocated port (e.g. 0 for first port), defaults to first port")
public Optional<Integer> getHealthcheckPortIndex() {
return healthcheckPortIndex;
}
@ApiModelProperty(required=false, value="The base path for the API exposed by the deploy. Used in conjunction with the Load balancer API.")
public Optional<String> getServiceBasePath() {
return serviceBasePath;
}
@ApiModelProperty(required=false, value="Number of seconds that a service must be healthy to consider the deployment to be successful.")
public Optional<Long> getConsiderHealthyAfterRunningForSeconds() {
return considerHealthyAfterRunningForSeconds;
}
@ApiModelProperty(required=false, value="List of load balancer groups associated with this deployment.")
public Optional<Set<String>> getLoadBalancerGroups() {
return loadBalancerGroups;
}
@ApiModelProperty(required=false, value="Send this port to the load balancer api (e.g. 0 for first port), defaults to first port")
public Optional<Integer> getLoadBalancerPortIndex() {
return loadBalancerPortIndex;
}
@ApiModelProperty(required=false, value="Map (Key/Value) of options for the load balancer.")
public Optional<Map<String, Object>> getLoadBalancerOptions() {
return loadBalancerOptions;
}
@ApiModelProperty(required=false, value="List of domains to host this service on, for use with the load balancer api")
public Optional<Set<String>> getLoadBalancerDomains() {
return loadBalancerDomains;
}
@ApiModelProperty(required=false, value="Additional routes besides serviceBasePath used by this service")
public Optional<List<String>> getLoadBalancerAdditionalRoutes() {
return loadBalancerAdditionalRoutes;
}
@ApiModelProperty(required=false, value="Name of load balancer template to use if not using the default template")
public Optional<String> getLoadBalancerTemplate() {
return loadBalancerTemplate;
}
@ApiModelProperty(required=false, value="Name of load balancer Service ID to use instead of the Request ID")
public Optional<String> getLoadBalancerServiceIdOverride() {
return loadBalancerServiceIdOverride;
}
@ApiModelProperty(required=false, value="Group name to tag all upstreams with in load balancer")
public Optional<String> getLoadBalancerUpstreamGroup() {
return loadBalancerUpstreamGroup;
}
@Deprecated
@ApiModelProperty(required=false, value="Labels for all tasks associated with this deploy")
public Optional<Map<String, String>> getLabels() {
return labels;
}
@ApiModelProperty(required=false, value="Labels for all tasks associated with this deploy")
public Optional<List<SingularityMesosTaskLabel>> getMesosLabels() {
return mesosLabels;
}
@ApiModelProperty(required=false, value="(Deprecated) Labels for specific tasks associated with this deploy, indexed by instance number")
public Optional<Map<Integer, Map<String, String>>> getTaskLabels() {
return taskLabels;
}
@ApiModelProperty(required=false, value="Labels for specific tasks associated with this deploy, indexed by instance number")
public Optional<Map<Integer, List<SingularityMesosTaskLabel>>> getMesosTaskLabels() {
return mesosTaskLabels;
}
@ApiModelProperty(required=false, value="Allows skipping of health checks when deploying.")
public Optional<Boolean> getSkipHealthchecksOnDeploy() {
return skipHealthchecksOnDeploy;
}
@ApiModelProperty(required=false, value="Maximum number of times to retry an individual healthcheck before failing the deploy.")
public Optional<Integer> getHealthcheckMaxRetries() {
return healthcheckMaxRetries;
}
@ApiModelProperty(required=false, value="Maximum amount of time to wait before failing a deploy for healthchecks to pass.")
public Optional<Long> getHealthcheckMaxTotalTimeoutSeconds() {
return healthcheckMaxTotalTimeoutSeconds;
}
@ApiModelProperty(required=false, value="deploy this many instances at a time")
public Optional<Integer> getDeployInstanceCountPerStep() {
return deployInstanceCountPerStep;
}
@ApiModelProperty(required=false, value="wait this long between deploy steps")
public Optional<Integer> getDeployStepWaitTimeMs() {
return deployStepWaitTimeMs;
}
@ApiModelProperty(required=false, value="automatically advance to the next target instance count after `deployStepWaitTimeMs` seconds")
public Optional<Boolean> getAutoAdvanceDeploySteps() {
return autoAdvanceDeploySteps;
}
@ApiModelProperty(required=false, value="allowed at most this many failed tasks to be retried before failing the deploy")
public Optional<Integer> getMaxTaskRetries() {
return maxTaskRetries;
}
@ApiModelProperty(required=false, value="Override the shell property on the mesos task")
public Optional<Boolean> getShell() {
return shell;
}
@ApiModelProperty(required=false, value="Run tasks as this user")
public Optional<String> getUser() {
return user;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("requestId", requestId)
.add("id", id)
.add("version", version)
.add("timestamp", timestamp)
.add("metadata", metadata)
.add("containerInfo", containerInfo)
.add("customExecutorCmd", customExecutorCmd)
.add("customExecutorId", customExecutorId)
.add("customExecutorSource", customExecutorSource)
.add("customExecutorResources", customExecutorResources)
.add("resources", resources)
.add("command", command)
.add("arguments", arguments)
.add("env", env)
.add("uris", uris)
.add("executorData", executorData)
.add("labels", labels)
.add("mesosLabels", mesosLabels)
.add("taskLabels", taskLabels)
.add("mesosTaskLabels", mesosTaskLabels)
.add("taskEnv", taskEnv)
.add("healthcheckUri", healthcheckUri)
.add("healthcheckIntervalSeconds", healthcheckIntervalSeconds)
.add("healthcheckTimeoutSeconds", healthcheckTimeoutSeconds)
.add("healthcheckPortIndex", healthcheckPortIndex)
.add("skipHealthchecksOnDeploy", skipHealthchecksOnDeploy)
.add("healthcheckProtocol", healthcheckProtocol)
.add("healthcheckMaxRetries", healthcheckMaxRetries)
.add("healthcheckMaxTotalTimeoutSeconds", healthcheckMaxTotalTimeoutSeconds)
.add("deployHealthTimeoutSeconds", deployHealthTimeoutSeconds)
.add("considerHealthyAfterRunningForSeconds", considerHealthyAfterRunningForSeconds)
.add("serviceBasePath", serviceBasePath)
.add("loadBalancerGroups", loadBalancerGroups)
.add("loadBalancerPortIndex", loadBalancerPortIndex)
.add("loadBalancerOptions", loadBalancerOptions)
.add("loadBalancerDomains", loadBalancerDomains)
.add("loadBalancerAdditionalRoutes", loadBalancerAdditionalRoutes)
.add("loadBalancerTemplate", loadBalancerTemplate)
.add("loadBalancerServiceIdOverride", loadBalancerServiceIdOverride)
.add("loadBalancerUpstreamGroup", loadBalancerUpstreamGroup)
.add("deployInstanceCountPerStep", deployInstanceCountPerStep)
.add("deployStepWaitTimeMs", deployStepWaitTimeMs)
.add("autoAdvanceDeploySteps", autoAdvanceDeploySteps)
.add("maxTaskRetries", maxTaskRetries)
.add("shell", shell)
.add("user", user)
.toString();
}
}
|
package com.salvadordalvik.something;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannedString;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.salvadordalvik.fastlibrary.FastFragment;
import com.salvadordalvik.fastlibrary.alert.FastAlert;
import com.salvadordalvik.fastlibrary.request.FastVolley;
import com.salvadordalvik.fastlibrary.util.FastUtils;
import com.salvadordalvik.something.request.BookmarkRequest;
import com.salvadordalvik.something.request.MarkLastReadRequest;
import com.salvadordalvik.something.request.ThreadPageRequest;
import com.salvadordalvik.something.util.Constants;
import com.salvadordalvik.something.util.SomePreferences;
import com.salvadordalvik.something.widget.PageSelectDialogFragment;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.DefaultHeaderTransformer;
import uk.co.senab.actionbarpulltorefresh.library.Options;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnPullFromBottomListener;
public class ThreadViewFragment extends FastFragment implements PageSelectDialogFragment.PageSelectable, View.OnClickListener, OnPullFromBottomListener {
private WebView threadView;
private int threadId, page, maxPage;
private CharSequence threadTitle;
private String pageHtml, rawThreadTitle;
private boolean bookmarked;
private ImageView navPrev, navNext;
private TextView navPageBar;
private boolean disableNavLoading = false;
private DefaultHeaderTransformer headerTransformer;
public ThreadViewFragment() {
super(R.layout.thread_pageview, R.menu.thread_view);
}
@Override
public void viewCreated(View frag, Bundle savedInstanceState) {
navPrev = (ImageView) frag.findViewById(R.id.threadview_prev);
navNext = (ImageView) frag.findViewById(R.id.threadview_next);
navPageBar = (TextView) frag.findViewById(R.id.threadview_page);
navPageBar.setOnClickListener(this);
navNext.setOnClickListener(this);
navPrev.setOnClickListener(this);
threadView = (WebView) frag.findViewById(R.id.ptr_webview);
initWebview();
if(savedInstanceState != null && savedInstanceState.containsKey("thread_html")){
threadId = savedInstanceState.getInt("thread_id");
pageHtml = savedInstanceState.getString("thread_html");
page = savedInstanceState.getInt("thread_page", 1);
maxPage = savedInstanceState.getInt("thread_maxpage", 1);
rawThreadTitle = savedInstanceState.getString("thread_title");
if(!TextUtils.isEmpty(rawThreadTitle)){
threadTitle = Html.fromHtml(rawThreadTitle);
setTitle(threadTitle);
}
threadView.loadDataWithBaseURL(Constants.BASE_URL, pageHtml, "text/html", "utf-8", null);
}
updateNavbar();
loadSessionCookie();
}
@Override
protected void setupPullToRefresh(PullToRefreshLayout ptr) {
ActionBarPullToRefresh.from(getActivity()).allChildrenArePullable().options(generatePullToRefreshOptions()).addPullFromBottomListener(this).listener(this).setup(ptr);
}
private void initWebview() {
threadView.getSettings().setJavaScriptEnabled(true);
threadView.setWebChromeClient(chromeClient);
threadView.setWebViewClient(webClient);
threadView.addJavascriptInterface(new SomeJavascriptInterface(), "listener");
TypedValue val = new TypedValue();
if(getActivity().getTheme().resolveAttribute(R.attr.webviewBackgroundColor, val, true)){
threadView.setBackgroundColor(val.data);
}
registerForContextMenu(threadView);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
WebView.HitTestResult result = threadView.getHitTestResult();
final String targetUrl = result.getExtra();
switch (result.getType()){
case WebView.HitTestResult.IMAGE_TYPE:
case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
menu.add(R.string.menu_save_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getActivity(), "Image Saving not implemented yet!", Toast.LENGTH_LONG).show();
//TODO save image link
FastUtils.startUrlIntent(getActivity(), targetUrl);
return true;
}
});
case WebView.HitTestResult.SRC_ANCHOR_TYPE:
menu.setHeaderTitle(result.getExtra());
menu.add(R.string.menu_open_link).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
FastUtils.startUrlIntent(getActivity(), targetUrl);
return true;
}
});
menu.add(R.string.menu_copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
FastAlert.custom(getActivity(), getView(), getString(R.string.url_copied), null, R.drawable.ic_menu_link);
ClipboardManager clipman = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
clipman.setPrimaryClip(ClipData.newPlainText(threadTitle.toString(), targetUrl));
return true;
}
});
menu.add(R.string.menu_share_link).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
FastUtils.showSimpleShareChooser(getActivity(), threadTitle.toString(), targetUrl, getString(R.string.menu_share_link));
return true;
}
});
break;
}
}
@Override
public void onResume() {
super.onResume();
if(((MainActivity)getActivity()).isFragmentFocused(this)){
threadView.onResume();
threadView.resumeTimers();
}
}
public void onPaneObscured() {
if(isResumed()){
threadView.pauseTimers();
threadView.onPause();
}
}
public void onPaneRevealed() {
if(isResumed()){
threadView.onResume();
threadView.resumeTimers();
}
}
@Override
public void onPause() {
super.onPause();
threadView.pauseTimers();
threadView.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(pageHtml != null){
outState.putString("thread_html", pageHtml);
outState.putInt("thread_id", threadId);
outState.putInt("thread_page", page);
outState.putInt("thread_maxpage", maxPage);
outState.putString("thread_title", rawThreadTitle);
}
}
private void updateNavbar() {
navPrev.setEnabled(page > 1 && !disableNavLoading);
navPageBar.setText("Page "+page+"/"+maxPage);
navNext.setImageResource(page < maxPage ? R.drawable.arrowright : R.drawable.ic_menu_load);
navNext.setEnabled(!disableNavLoading || page == maxPage);
updateHeader();
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem bookmark = menu.findItem(R.id.menu_thread_bookmark);
if(bookmark != null){
bookmark.setIcon(bookmarked ? R.drawable.star : R.drawable.star_empty);
bookmark.setTitle(bookmarked ? R.string.menu_thread_unbookmark : R.string.menu_thread_bookmark);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_thread_bookmark:
FastAlert.process(getActivity(), getView(), getString(bookmarked ? R.string.bookmarking_thread_started_removing : R.string.bookmarking_thread_started));
queueRequest(new BookmarkRequest(threadId, !bookmarked, new Response.Listener<Boolean>() {
@Override
public void onResponse(Boolean response) {
bookmarked = response;
invalidateOptionsMenu();
FastAlert.notice(getActivity(), getView(), getString(response ? R.string.bookmarking_thread_success_add : R.string.bookmarking_thread_success_remove));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
FastAlert.error(getActivity(), getView(), getString(R.string.bookmarking_thread_failure));
}
}));
return true;
}
return super.onOptionsItemSelected(item);
}
//Must be a common string, volley uses direct equality when comparing tags.
private static final String THREAD_REQUEST_TAG = "thread_page_request";
@Override
public void refreshData(boolean pullToRefresh, boolean staleRefresh) {
threadView.stopLoading();
disableNavLoading = true;
updateNavbar();
FastVolley.cancelRequestByTag(THREAD_REQUEST_TAG);
queueRequest(new ThreadPageRequest(threadId, page, pageListener, errorListener), THREAD_REQUEST_TAG);
getHandler().postDelayed(enableNavigation, 1000);
}
private Runnable enableNavigation = new Runnable() {
@Override
public void run() {
if(disableNavLoading){
disableNavLoading = false;
updateNavbar();
}
}
};
private Response.Listener<ThreadPageRequest.ThreadPage> pageListener = new Response.Listener<ThreadPageRequest.ThreadPage>() {
@Override
public void onResponse(ThreadPageRequest.ThreadPage response) {
loadSessionCookie();
disableNavLoading = false;
page = response.pageNum;
maxPage = response.maxPageNum;
if (!TextUtils.isEmpty(response.threadTitle)) {
threadTitle = Html.fromHtml(response.threadTitle);
}
threadView.loadDataWithBaseURL(Constants.BASE_URL, response.pageHtml, "text/html", "utf-8", null);
pageHtml = response.pageHtml;
rawThreadTitle = response.threadTitle;
bookmarked = response.bookmarked;
Activity act = getActivity();
if (act instanceof MainActivity) {
MainActivity main = (MainActivity) act;
main.onThreadPageLoaded(response.threadId);
}
setTitle(threadTitle);
updateNavbar();
invalidateOptionsMenu();
}
};
private Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
disableNavLoading = false;
updateNavbar();
}
};
public void loadThread(int threadId, int page){
this.threadId = threadId;
this.page = page;
this.maxPage = 0;
this.bookmarked = false;
this.threadTitle = new SpannedString(getString(R.string.thread_view_loading));
setTitle(threadTitle);
invalidateOptionsMenu();
updateNavbar();
startRefresh();
threadView.loadUrl("about:blank");
}
private void loadSessionCookie(){
CookieManager cookieMstr = CookieManager.getInstance();
Matcher cookieCutter = Pattern.compile("(\\w+)=(\\w+)").matcher(SomePreferences.cookieString);
while(cookieCutter.find()){
String name = cookieCutter.group(1);
String value = cookieCutter.group(2);
cookieMstr.setCookie("forums.somethingawful.com", name+"="+value+"; domain=forums.somethingawful.com");
}
CookieSyncManager.getInstance().sync();
}
public void goToPage(int pageNum){
if(pageNum <= maxPage && pageNum > 0){
page = pageNum;
updateNavbar();
startRefresh();
}
}
public boolean hasThreadLoaded() {
return pageHtml != null;
}
public CharSequence getTitle() {
return threadTitle;
}
private WebChromeClient chromeClient = new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
Log.d("WebView", "Progress: "+newProgress);
setProgress(newProgress);
}
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.e("WebChromeClient", consoleMessage.lineNumber()+" - "+consoleMessage.messageLevel()+" - "+consoleMessage.message());
return true;
}
};
private WebViewClient webClient = new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d("WebView", "onPageStarted: " + url);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d("WebView", "onPageFinished: " + url);
setProgress(100);
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
Log.d("WebView", "onLoadResource: " + url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("WebView", "shouldOverrideUrlLoading: "+url);
if(url != null && url.startsWith("something")){
if(url.contains("something://something-next")){
goToPage(page+1);
return true;
}else if(url.contains("something://something-prev")){
goToPage(page-1);
return true;
}else if(url.contains("something://something-pageselect")){
displayPageSelect();
return true;
}
}
FastUtils.startUrlIntent(getActivity(), url);
return true;
}
};
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.threadview_prev:
goToPage(page-1);
break;
case R.id.threadview_page:
displayPageSelect();
break;
case R.id.threadview_next:
if(page < maxPage){
goToPage(page+1);
}else{
startRefresh();
}
break;
}
}
private void displayPageSelect(){
PageSelectDialogFragment.newInstance(page, maxPage, ThreadViewFragment.this).show(getFragmentManager(), "page_select");
}
@Override
protected Options generatePullToRefreshOptions() {
headerTransformer = new DefaultHeaderTransformer();
return Options.create().headerTransformer(headerTransformer).scrollDistance(getScrollDistance()).build();
}
private float getScrollDistance(){
return Math.max(Math.min(FastUtils.calculateScrollDistance(getActivity(), 2.5f), 0.666f), 0.333f);
}
private void updateHeader(){
if(headerTransformer != null){
headerTransformer.setPullFromBottomText(getString(page < maxPage ? R.string.pull_bottom_nextpage : R.string.pull_to_refresh_pull_label));
headerTransformer.setPullFromBottomReleaseText(getString(page < maxPage ? R.string.pull_bottom_release_nexpage : R.string.pull_to_refresh_release_label));
}
}
@Override
public void onPullFromBottom(View view) {
if(page < maxPage){
goToPage(page+1);
}else{
startRefresh();
}
}
public class SomeJavascriptInterface {
@JavascriptInterface
public void onQuoteClick(String postId){
}
@JavascriptInterface
public void onEditClick(String postId){
}
@JavascriptInterface
public void onMoreClick(String postId, String username, String userid){
}
@JavascriptInterface
public void onLastReadClick(String postIndex){
final int index = FastUtils.safeParseInt(postIndex, 0);
if(index > 0){
runOnUiThread(new Runnable() {
@Override
public void run() {
FastAlert.process(getActivity(), getView(), getString(R.string.mark_last_read_started));
queueRequest(new MarkLastReadRequest(threadId, index, new Response.Listener<ThreadPageRequest.ThreadPage>() {
@Override
public void onResponse(ThreadPageRequest.ThreadPage response) {
FastAlert.notice(getActivity(), getView(), getString(R.string.mark_last_read_success));
pageListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
FastAlert.error(getActivity(), getView(), getString(R.string.mark_last_read_failure));
}
}
));
}
});
}else{
throw new RuntimeException("Invalid postIndex in onLastReadClick: "+postIndex);
}
}
}
@Override
protected void setTitle(CharSequence title) {
Activity act = getActivity();
if(act instanceof MainActivity){
((MainActivity)act).setTitle(title, this);
}
}
}
|
package edu.purdue.cs307.team16.test;
import static org.junit.Assert.assertArrayEquals;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.junit.Test;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import edu.purdue.cs307.team16.AWSInterface;
import edu.purdue.cs307.team16.RadarFilePicker;
import junit.framework.TestCase;
public class AWSInterfaceTest extends TestCase {
@Test
public void testListBucket() {
final String dataBucket = "noaa-nexrad-level2";
String[] key = {"2010/01/01", "2010/07/14"};
String jobID = null;
AWSInterface awsInterface = new AWSInterface(jobID);
List<S3ObjectSummary> summaries;
int[] output = new int[2];
for(int i = 0 ; i < 2; i++) {
summaries = awsInterface.ListBucket(dataBucket, key[i]);
output[i] = summaries.size();
summaries.clear();
}
int[] answer = {14104, 33468};
assertArrayEquals(answer, output);
System.out.println("ListBucket() is ok");
}
@Test
public void testFindOrCreateWeatherPipeJobBucket() {
String jobID = null;
String bucketName = "fdgfhfdx";
AWSInterface awsInterface = new AWSInterface(jobID);
jobID = "job1";
awsInterface = new AWSInterface(jobID, bucketName);
String output;
output = awsInterface.FindOrCreateWeatherPipeJobBucket();
String answer = "s3n://fdgfhfdx/";
assertEquals(answer, output);
AWSCredentials credentials = new ProfileCredentialsProvider("default").getCredentials();
Region region = Region.getRegion(Regions.US_EAST_1);
AmazonS3Client s3client = new AmazonS3Client(credentials);
s3client.setRegion(region);
s3client.deleteBucket(bucketName);
System.out.println("FindOrCreateWeatherPipeJobBucket() is ok");
}
@Test
public void testUploadInputFileList() {
//ArrayList<String> fileList = new ArrayList<String>();
ArrayList<ArrayList<String>> fileList1 = new ArrayList<ArrayList<String>>();
//DateTime startTimes = new DateTime(2010, 01, 01, 07, 39, 28);
//DateTime endTimes = new DateTime(2010, 01, 01, 15, 58, 47);
DateTime[] startTimes = {new DateTime(2010, 01, 01, 07, 39, 28), new DateTime(2010, 01, 01, 07, 39, 28)};
DateTime[] endTimes = {new DateTime(2010, 01, 01, 15, 58, 47), new DateTime(2010, 01, 01, 07, 39, 30)};
String key = "2010/01/01";
String station = "KBBX";
final String dataBucket = "noaa-nexrad-level2";
String[] jobID = {"job1", "job2"};
//jobID = "job1";
String[] bucketName = {"fdafda", "adfeth"};
AWSInterface[] awsInterface = {new AWSInterface(jobID[0], bucketName[0]), new AWSInterface(jobID[1], bucketName[1])};
//awsInterface.FindOrCreateWeatherPipeJobBucket();
//AWSInterface awsInterface = new AWSInterface(jobID);
String[] ret = new String[2];
for(int i = 0; i < 2; i++) {
awsInterface[i].FindOrCreateWeatherPipeJobBucket();
fileList1.add(RadarFilePicker.getRadarFilesFromTimeRange(startTimes[i], endTimes[i], station, awsInterface[i], dataBucket));
ret[i] = awsInterface[i].UploadInputFileList(fileList1.get(i), dataBucket);
}
String[] answer = {"s3n://fdafda/job1_input", "s3n://adfeth/job2_input"};
assertArrayEquals(answer, ret);
System.out.println("UploadInputFileList() is ok");
}
}
|
package hska.iwi.eShopMaster.controller;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import hska.iwi.eShopMaster.model.businessLogic.manager.UserManager;
import hska.iwi.eShopMaster.model.businessLogic.manager.entity.User;
import hska.iwi.eShopMaster.model.businessLogic.manager.impl.UserManagerImpl;
import java.util.Map;
public class LogoutAction extends ActionSupport {
private static final long serialVersionUID = -530488065543708898L;
public String execute() throws Exception {
// Clear session:
Map<String, Object> session = ActionContext.getContext().getSession();
UserManager userManager = new UserManagerImpl();
User currentUser = (User) session.get("webshop_user");
userManager.logoutUser(currentUser.getUsername(), currentUser.getPassword());
session.clear();
return "success";
}
}
|
package uk.ac.cam.gpe21.droidssl.analysis;
import soot.*;
import soot.options.Options;
import uk.ac.cam.gpe21.droidssl.analysis.trans.*;
import java.util.Arrays;
public final class StaticAnalyser {
public static void main(String[] args) {
/*
* Set path to input APK.
*/
Options.v().set_src_prec(Options.src_prec_apk);
Options.v().set_process_dir(Arrays.asList("test-hv/build/apk/test-hv-release-unsigned.apk"));
/*
* Prevent Soot from outputting *.jimple files.
*/
Options.v().set_output_format(Options.output_format_none);
/*
* Set the path to the Android SDK.
*/
Options.v().set_android_jars("/opt/android/platforms");
/*
* Allow phantom references as there are some Google-specific APIs not
* included in the Android SDK directory as listed above.
*/
Options.v().set_allow_phantom_refs(true);
/*
* Enable the SPARK points-to analysis.
*/
Options.v().set_whole_program(true);
PhaseOptions.v().processPhaseOptions("cg.spark", "enabled:true");
/*
* Add transforms to the Whole Jimple Pre-processing Pack.
*/
Pack wjpp = PackManager.v().getPack("wjpp");
wjpp.add(new Transform("wjpp.activity_entry_transformer", new ActivityEntryTransformer()));
wjpp.add(new Transform("wjpp.known_vulnerable_class_tagger", new KnownVulnerableClassTagger()));
/*
* Add transforms to the Jimple Transformation Pack.
*/
Pack jtp = PackManager.v().getPack("jtp");
jtp.add(new Transform("jtp.jsse_hostname_verifier", new JsseHostnameVerifierTransformer()));
jtp.add(new Transform("jtp.httpclient_hostname_verifier", new HttpClientHostnameVerifierTransformer()));
jtp.add(new Transform("jtp.default_jsse_hostname_verifier", new DefaultJsseHostnameVerifierTransformer()));
/*
* Perform the analysis.
*/
Scene.v().loadNecessaryClasses();
PackManager.v().runPacks();
}
}
|
package torrent.download.tracker;
import java.io.IOException;
import java.util.LinkedList;
import org.johnnei.utils.ThreadUtils;
import torrent.download.Torrent;
import torrent.download.peer.Peer;
import torrent.download.peer.PeerConnectInfo;
import torrent.encoding.SHA1;
import torrent.network.BitTorrentSocket;
import torrent.protocol.BitTorrentHandshake;
import torrent.protocol.BitTorrentUtil;
public class PeerConnector implements Runnable {
private final Object LOCK_PEER_LIST = new Object();
/**
* The object on which the thread will start sleeping once it is out of work
*/
public final Object PEER_JOB_NOTIFY = new Object();
/**
* List of peer that are currently being connected
*/
private LinkedList<PeerConnectInfo> peers;
private TrackerManager manager;
private final int maxPeers;
public PeerConnector(TrackerManager manager, int maxConnecting) {
this.manager = manager;
this.maxPeers = maxConnecting;
peers = new LinkedList<>();
}
/**
* Adds a pending connection peer to the connection cycle
*
* @param peerInfo The peer to connect
*/
public void addPeer(PeerConnectInfo peerInfo) {
if (peers.size() >= maxPeers) {
throw new IllegalStateException(String.format("Connector is full"));
}
synchronized (LOCK_PEER_LIST) {
peers.add(peerInfo);
}
}
public void run() {
while (true) {
if (peers.isEmpty()) {
ThreadUtils.wait(PEER_JOB_NOTIFY);
}
PeerConnectInfo peerInfo = null;
BitTorrentSocket peerSocket = null;
synchronized (LOCK_PEER_LIST) {
peerInfo = peers.remove();
}
if (peerInfo == null) {
continue;
}
try {
peerSocket = new BitTorrentSocket();
peerSocket.connect(peerInfo.getAddress());
peerSocket.sendHandshake(manager.getPeerId(), peerInfo.getTorrent().getHashArray());
long timeWaited = 0;
while (!peerSocket.canReadMessage() && timeWaited < 10_000) {
final int INTERVAL = 100;
ThreadUtils.sleep(INTERVAL);
timeWaited += INTERVAL;
}
if (!peerSocket.canReadMessage()) {
throw new IOException("Handshake timeout");
}
BitTorrentHandshake handshake = checkHandshake(peerSocket, peerInfo.getTorrent().getHashArray());
Peer peer = new Peer(peerSocket, peerInfo.getTorrent());
peer.getExtensions().register(handshake.getPeerExtensionBytes());
BitTorrentUtil.onPostHandshake(peer);
} catch (IOException e) {
System.err.println(String.format("[PeerConnector] Failed to connect peer: %s", e.getMessage()));
if (peerSocket != null) {
peerSocket.close();
}
}
}
}
private BitTorrentHandshake checkHandshake(BitTorrentSocket peerSocket, byte[] torrentHash) throws IOException {
BitTorrentHandshake handshake = peerSocket.readHandshake();
if (SHA1.match(torrentHash, handshake.getTorrentHash())) {
throw new IOException("Peer does not download the same torrent");
}
return handshake;
}
public int getFreeCapacity() {
return maxPeers - peers.size();
}
public int getConnectingCount() {
return peers.size();
}
public int getMaxCapacity() {
return maxPeers;
}
public int getConnectingCountFor(Torrent torrent) {
LinkedList<PeerConnectInfo> peerList = null;
synchronized (LOCK_PEER_LIST) {
peerList = new LinkedList<>(peers);
}
return (int) peerList.stream().
filter(p -> p.getTorrent().equals(torrent)).
count();
}
}
|
package org.sagebionetworks.bridge.play.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.sagebionetworks.bridge.models.GuidHolder;
import org.sagebionetworks.bridge.models.accounts.UserSession;
import org.sagebionetworks.bridge.models.notifications.NotificationRegistration;
import org.sagebionetworks.bridge.services.NotificationsService;
import play.mvc.Result;
@Controller
public class NotificationsController extends BaseController {
private NotificationsService notificationsService;
@Autowired
final void setNotificationService(NotificationsService notificationsService) {
this.notificationsService = notificationsService;
}
public Result getAllRegistrations() {
UserSession session = getAuthenticatedAndConsentedSession();
List<NotificationRegistration> registrations = notificationsService.listRegistrations(session.getHealthCode());
return okResult(registrations);
}
public Result createRegistration() throws Exception {
UserSession session = getAuthenticatedAndConsentedSession();
NotificationRegistration registration = parseJson(request(), NotificationRegistration.class);
registration.setHealthCode(session.getHealthCode());
NotificationRegistration result = notificationsService.createRegistration(session.getStudyIdentifier(),
registration);
return createdResult(new GuidHolder(result.getGuid()));
}
public Result updateRegistration(String guid) {
UserSession session = getAuthenticatedAndConsentedSession();
NotificationRegistration registration = parseJson(request(), NotificationRegistration.class);
registration.setHealthCode(session.getHealthCode());
registration.setGuid(guid);
NotificationRegistration result = notificationsService.updateRegistration(session.getStudyIdentifier(),
registration);
return okResult(new GuidHolder(result.getGuid()));
}
public Result getRegistration(String guid) {
UserSession session = getAuthenticatedAndConsentedSession();
NotificationRegistration result = notificationsService.getRegistration(session.getHealthCode(), guid);
return okResult(result);
}
public Result deleteRegistration(String guid) {
UserSession session = getAuthenticatedAndConsentedSession();
notificationsService.deleteRegistration(session.getHealthCode(), guid);
return okResult("Push notification registration deleted.");
}
}
|
package cl.monsoon.s1next.view.fragment;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import cl.monsoon.s1next.R;
import cl.monsoon.s1next.databinding.FragmentViewPagerBinding;
import cl.monsoon.s1next.util.ResourceUtil;
import cl.monsoon.s1next.util.StringUtil;
import cl.monsoon.s1next.view.dialog.PageTurningDialogFragment;
import cl.monsoon.s1next.view.internal.PagerCallback;
import cl.monsoon.s1next.viewmodel.ViewPagerViewModel;
import cl.monsoon.s1next.widget.FragmentStatePagerAdapter;
/**
* A base Fragment wraps {@link ViewPager} and provides related methods.
*/
public abstract class BaseViewPagerFragment extends Fragment
implements PageTurningDialogFragment.OnPageTurnedListener,
PagerCallback {
/**
* The serialization (saved instance state) Bundle key representing
* the total pages.
*/
private static final String STATE_TOTAL_PAGES = "total_pages";
private FragmentViewPagerBinding mFragmentViewPagerBinding;
private ViewPager mViewPager;
private MenuItem mMenuPageTurning;
@Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mFragmentViewPagerBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_view_pager,
container, false);
mViewPager = mFragmentViewPagerBinding.viewPager;
return mFragmentViewPagerBinding.getRoot();
}
@Override
@CallSuper
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewPagerViewModel viewModel = new ViewPagerViewModel();
if (savedInstanceState != null) {
viewModel.totalPage.set(savedInstanceState.getInt(STATE_TOTAL_PAGES));
} else {
viewModel.totalPage.set(1);
}
mFragmentViewPagerBinding.setViewPagerViewModel(viewModel);
// don't use getChildFragmentManager()
// because we can't retain Fragments (DataRetainedFragment)
// that are nested in other fragments
mViewPager.setAdapter(getPagerAdapter(getFragmentManager()));
}
@Override
@CallSuper
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
@CallSuper
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_view_pager, menu);
mMenuPageTurning = menu.findItem(R.id.menu_page_turning);
preparePageTurningMenu();
}
@Override
@CallSuper
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_page_turning:
new PageTurningDialogFragment(getTotalPages(), getCurrentPage()).show(
getChildFragmentManager(), PageTurningDialogFragment.TAG);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
@CallSuper
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_TOTAL_PAGES, getTotalPages());
}
ViewPager getViewPager() {
return mViewPager;
}
abstract BaseFragmentStatePagerAdapter getPagerAdapter(FragmentManager fragmentManager);
int getTotalPages() {
return mFragmentViewPagerBinding.getViewPagerViewModel().totalPage.get();
}
public final void setTotalPage(int page) {
mFragmentViewPagerBinding.getViewPagerViewModel().totalPage.set(page);
preparePageTurningMenu();
}
final int getCurrentPage() {
return mViewPager.getCurrentItem();
}
@Override
@CallSuper
public void onPageTurned(int position) {
mViewPager.setCurrentItem(position);
}
/**
* Disables the page turning menu if only has one page.
*/
private void preparePageTurningMenu() {
if (mMenuPageTurning == null) {
return;
}
if (getTotalPages() == 1) {
mMenuPageTurning.setEnabled(false);
} else {
mMenuPageTurning.setEnabled(true);
}
}
private void setTitleWithPosition(int position) {
CharSequence titleWithoutPosition = getTitleWithoutPosition();
if (titleWithoutPosition == null) {
getActivity().setTitle(null);
return;
}
String titleWithPosition;
if (ResourceUtil.isRTL(getResources())) {
titleWithPosition = StringUtil.concatWithTwoSpaces(position + 1, titleWithoutPosition);
} else {
titleWithPosition = StringUtil.concatWithTwoSpaces(titleWithoutPosition, position + 1);
}
getActivity().setTitle(titleWithPosition);
}
abstract CharSequence getTitleWithoutPosition();
/**
* A base {@link FragmentStatePagerAdapter} wraps some implement.
*/
abstract class BaseFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
public BaseFragmentStatePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public final int getCount() {
return getTotalPages();
}
@Override
@CallSuper
public void setPrimaryItem(ViewGroup container, int position, Object object) {
setTitleWithPosition(position);
super.setPrimaryItem(container, position, object);
}
@Override
@CallSuper
public void destroyItem(ViewGroup container, int position, Object object) {
if (object instanceof BaseFragment) {
// We don't reuse Fragment in ViewPager and its retained Fragment
// because it is not cost-effective nowadays.
((BaseFragment) object).destroyRetainedFragment();
}
super.destroyItem(container, position, object);
}
}
}
|
package com.infoeducatie.app.recyclerviews.talks;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.infoeducatie.app.R;
import com.infoeducatie.app.client.entities.Talk;
import com.infoeducatie.app.client.entities.User;
import com.infoeducatie.app.helpers.DateHelper;
import java.util.List;
public class TalksAdapter extends RecyclerView.Adapter<TalksViewHolder> {
private Talk[] talks = new Talk[0];
/* getters and setters for the news */
public void setTalks(Talk[] talks) {
this.talks = talks;
notifyDataSetChanged();
}
public Talk[] getNews() {
return talks;
}
@Override
public TalksViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
/* create the view holder */
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_talk, null);
TalksViewHolder viewHolder = new TalksViewHolder(view);
return viewHolder;
}
/* converts a list of users to string, ex: Nume Prenume, Job
Nume2 Prenume2 Job
*/
public String usersToString(List<User> users) {
if (users == null) return null;
String result = "";
for (User user : users) {
result += user.getFirst_name() + " " + user.getLast_name();
if (user.getJob() != null && user.getJob().trim().length() > 0) {
result += ", " + user.getJob();
}
result += "\n";
}
return result;
}
@Override
public void onBindViewHolder(final TalksViewHolder holder, final int position) {
/* bind the viewholder item */
Talk talk = talks[position];
holder.title.setText(talk.getTitle());
holder.body.setText(talk.getDescription());
holder.location.setText(talk.getLocation());
if (talk.getDate() != null) {
holder.date.setText(DateHelper.ISOFormatToString(talk.getDate()));
} else {
holder.date.setText(null);
}
holder.person.setText(usersToString(talk.getUsers()));
}
@Override
public int getItemCount() {
return talks.length;
}
}
|
package com.michaldabski.panoramio.main_activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.michaldabski.panoramio.R;
import com.michaldabski.panoramio.models.PanoramioResponse;
import com.michaldabski.panoramio.models.Photo;
import com.michaldabski.panoramio.photo_activity.PhotoActivity;
import com.michaldabski.panoramio.requests.NearbyPhotosRequest;
import com.michaldabski.panoramio.requests.PanoramioRequest;
import com.michaldabski.panoramio.utils.VolleySingleton;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
public class MainActivity extends Activity implements Response.ErrorListener, AdapterView.OnItemClickListener, AbsListView.OnScrollListener
{
private static final String
STATE_RESPONSE = "response",
STATE_LAT = "latitude",
STATE_LONG = "longitude";
private ArrayList<Photo> photos = new ArrayList<Photo>();
PanoramioResponse panoramioResponse;
PanoramioRequest panoramioRequest = null;
float latitude=Float.NaN,
longitude=Float.NaN;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
if (savedInstanceState != null)
{
panoramioResponse = savedInstanceState.getParcelable(STATE_RESPONSE);
latitude = savedInstanceState.getFloat(STATE_LAT);
longitude = savedInstanceState.getFloat(STATE_LONG);
}
GridView gridView = (GridView) findViewById(R.id.gridView);
gridView.setOnItemClickListener(this);
gridView.setAdapter(new PhotoGridAdapter(this, photos));
gridView.setOnScrollListener(this);
if (panoramioResponse == null)
acquireLocation();
else
{
addPhotos(panoramioResponse.getPhotos());
panoramioResponse.setPhotos(this.photos);
}
}
void addPhotos(Collection<Photo> photoCollection)
{
photos.addAll(photoCollection);
GridView gridView = (GridView) findViewById(R.id.gridView);
PhotoGridAdapter adapter = (PhotoGridAdapter) gridView.getAdapter();
adapter.notifyDataSetChanged();
}
void onPanoramioResponse(PanoramioResponse response)
{
this.panoramioResponse = response;
addPhotos(panoramioResponse.getPhotos());
panoramioResponse.setPhotos(this.photos);
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putParcelable(STATE_RESPONSE, panoramioResponse);
outState.putFloat(STATE_LAT, latitude);
outState.putFloat(STATE_LONG, longitude);
}
void acquireLocation()
{
final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
setProgressBarIndeterminateVisibility(true);
LocationListener locationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
latitude = (float) location.getLatitude();
longitude = (float) location.getLongitude();
requestPhotos(latitude, longitude);
locationManager.removeUpdates(this);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle)
{
}
@Override
public void onProviderEnabled(String s)
{
}
@Override
public void onProviderDisabled(String s)
{
}
};
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String bestProvider = locationManager.getBestProvider(criteria, true);
if (bestProvider != null && locationManager.isProviderEnabled(bestProvider))
{
locationManager.requestLocationUpdates(bestProvider, 0, 0, locationListener);
}
else
{
Random random = new Random(System.currentTimeMillis());
Location location = new Location(LocationManager.NETWORK_PROVIDER);
location.setAccuracy(1f);
location.setLatitude((random.nextDouble() * 180d) - 90d);
location.setLongitude((random.nextDouble() * 360d) - 180d);
locationListener.onLocationChanged(location);
Toast.makeText(this, "No location provider. Using random location.", Toast.LENGTH_SHORT).show();
}
}
void requestPhotos(float lat, float lng)
{
requestPhotos(lat, lng, 0);
}
void requestPhotos(float lat, float lng, int from)
{
setProgressBarIndeterminateVisibility(true);
panoramioRequest = new NearbyPhotosRequest(this, lat, lng, from, 0.1f)
{
@Override
protected void deliverResponse(PanoramioResponse response)
{
super.deliverResponse(response);
onPanoramioResponse(response);
panoramioRequest = null;
setProgressBarIndeterminateVisibility(false);
}
};
panoramioRequest.setTag(this);
VolleySingleton.getInstance(this).getRequestQueue().add(panoramioRequest);
}
@Override
public void onErrorResponse(VolleyError error)
{
panoramioRequest = null;
setProgressBarIndeterminateVisibility(false);
error.printStackTrace();
new AlertDialog.Builder(this)
.setTitle(R.string.error)
.setMessage(error.getMessage())
.setPositiveButton(android.R.string.ok, null)
.show();
}
boolean isRequestPending()
{
return panoramioRequest != null;
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l)
{
Intent intent = new Intent(this, PhotoActivity.class);
intent.putExtra(PhotoActivity.ARG_PHOTOS_ARRAY, panoramioResponse.getPhotos().toArray(new Photo[panoramioResponse.getPhotos().size()]));
intent.putExtra(PhotoActivity.ARG_SELECTED_INDEX, position);
startActivity(intent);
}
@Override
public void onScrollStateChanged(AbsListView absListView, int scrollState)
{
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
if (firstVisibleItem != 0 && totalItemCount <= firstVisibleItem+visibleItemCount && !isRequestPending() && Float.isNaN(latitude) == false && totalItemCount < panoramioResponse.getCount())
{
requestPhotos(latitude, longitude, photos.size());
}
}
}
|
package com.test.myapplication.model.validator;
import android.support.annotation.NonNull;
import java.lang.reflect.Field;
public class ModelValidator {
private Object model;
public ModelValidator(@NonNull Object model) {
this.model = model;
}
public void validate() throws IllegalArgumentException {
if (model == null) {
throw new IllegalArgumentException("Model cannot be null");
}
final Field[] modelFields = model.getClass().getFields();
for (Field modelField : modelFields) {
validateIsDefinedField(modelField);
}
}
private void validateIsDefinedField(Field field) {
if (field.isAnnotationPresent(IsDefined.class)) {
Object modelAttribute = null;
try {
modelAttribute = field.get(model);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (modelAttribute == null) {
throw new IllegalArgumentException(field + " is required");
}
}
}
}
|
package de.bitshares_munich.smartcoinswallet;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.bitshares_munich.models.AccountDetails;
import de.bitshares_munich.models.TransactionDetails;
import de.bitshares_munich.utils.Application;
import de.bitshares_munich.utils.BinHelper;
import de.bitshares_munich.utils.Crypt;
import de.bitshares_munich.utils.Helper;
import de.bitshares_munich.utils.IWebService;
import de.bitshares_munich.utils.ServiceGenerator;
import de.bitshares_munich.utils.TinyDB;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class BrainkeyActivity extends BaseActivity {
@Bind(R.id.etPin)
EditText etPin;
@Bind(R.id.etPinConfirmation)
EditText etPinConfirmation;
@Bind(R.id.etBrainKey)
EditText etBrainKey;
@Bind(R.id.tvBlockNumberHead_brain_key_activity)
TextView tvBlockNumberHead;
@Bind(R.id.tvAppVersion_brain_key_activity)
TextView tvAppVersion;
@Bind(R.id.ivSocketConnected_brain_key_activity)
ImageView ivSocketConnected;
ProgressDialog progressDialog;
TinyDB tinyDB;
Boolean settingScreen = false;
@Bind(R.id.tvPin)
TextView tvPin;
@Bind(R.id.tvPinConfirmation)
TextView tvPinConfirmation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brainkey);
ButterKnife.bind(this);
setBackButton(true);
setTitle(getResources().getString(R.string.app_name));
progressDialog = new ProgressDialog(this);
tinyDB = new TinyDB(getApplicationContext());
tvAppVersion.setText("v" + BuildConfig.VERSION_NAME + getString(R.string.beta));
updateBlockNumberHead();
etBrainKey.addTextChangedListener(brainKeyWatcher);
}
private final TextWatcher brainKeyWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
// String s = editable.toString();
// if (!s.equals(s.toLowerCase())) {
// s = s.toLowerCase();
// etBrainKey.setText(s);
// etBrainKey.setSelection(etBrainKey.getText().toString().length());
}
};
@OnClick(R.id.btnCancel)
public void cancel(Button button) {
this.finish();
}
@OnClick(R.id.btnWallet)
public void wallet(Button button) {
if (etBrainKey.getText().length() == 0) {
Toast.makeText(getApplicationContext(), R.string.please_enter_brainkey, Toast.LENGTH_SHORT).show();
} else {
String trimmedBrainKey = etBrainKey.getText().toString().trim();
etBrainKey.setText(trimmedBrainKey);
if (etPin.getText().length() < 5) {
Toast.makeText(getApplicationContext(), R.string.please_enter_6_digit_pin, Toast.LENGTH_SHORT).show();
} else if (etPinConfirmation.getText().length() < 5) {
Toast.makeText(getApplicationContext(), R.string.please_enter_6_digit_pin_confirm, Toast.LENGTH_SHORT).show();
} else if (!etPinConfirmation.getText().toString().equals(etPin.getText().toString())) {
Toast.makeText(getApplicationContext(), R.string.mismatch_pin, Toast.LENGTH_SHORT).show();
} else {
load(etPin.getText().toString());
}
}
}
void load(String pinCode) {
String temp = etBrainKey.getText().toString();
if (temp.contains(" ")) {
String arr[] = temp.split(" ");
if (arr.length == 16) {
if (checkBrainKeyExist(temp)) {
Toast.makeText(getApplicationContext(), R.string.account_already_exist, Toast.LENGTH_SHORT).show();
} else {
showDialog("", getString(R.string.importing_your_wallet));
get_account_from_brainkey(this, temp, pinCode);
}
} else {
Toast.makeText(getApplicationContext(), R.string.please_enter_correct_brainkey, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), R.string.please_enter_correct_brainkey, Toast.LENGTH_SHORT).show();
}
}
private boolean checkBrainKeyExist(String brainKey) {
boolean isBrainKey = false;
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
for (int i = 0; i < accountDetails.size(); i++) {
try {
if (brainKey.equals(accountDetails.get(i).brain_key)) {
isBrainKey = true;
break;
}
} catch (Exception e) {
}
}
return isBrainKey;
}
public void get_account_from_brainkey(final Activity activity, final String brainKey, final String pinCode) {
ServiceGenerator sg = new ServiceGenerator(getString(R.string.account_from_brainkey_url));
IWebService service = sg.getService(IWebService.class);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("method", "get_account_from_brainkey");
hashMap.put("brainkey", brainKey);
final Call<AccountDetails> postingService = service.getAccount(hashMap);
postingService.enqueue(new Callback<AccountDetails>() {
@Override
public void onResponse(Response<AccountDetails> response) {
if (response.isSuccess()) {
hideDialog();
AccountDetails accountDetails = response.body();
if (accountDetails.status.equals("failure")) {
Toast.makeText(activity, accountDetails.msg, Toast.LENGTH_SHORT).show();
} else {
addWallet(accountDetails, brainKey, pinCode);
}
} else {
hideDialog();
Toast.makeText(activity, activity.getString(R.string.unable_to_create_account_from_brainkey), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Throwable t) {
hideDialog();
Toast.makeText(activity, activity.getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show();
}
});
}
private void showDialog(String title, String msg) {
if (progressDialog != null) {
if (!progressDialog.isShowing()) {
progressDialog.setTitle(title);
progressDialog.setMessage(msg);
progressDialog.show();
}
}
}
private void hideDialog() {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.cancel();
}
}
}
private void updateBlockNumberHead() {
final Handler handler = new Handler();
final Activity myActivity = this;
final Runnable updateTask = new Runnable() {
@Override
public void run() {
if (Application.isConnected()) {
ivSocketConnected.setImageResource(R.drawable.icon_connecting);
tvBlockNumberHead.setText(Application.blockHead);
ivSocketConnected.clearAnimation();
} else {
ivSocketConnected.setImageResource(R.drawable.icon_disconnecting);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(myActivity.getApplicationContext(), R.anim.flash);
ivSocketConnected.startAnimation(myFadeInAnimation);
}
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(updateTask, 1000);
}
void addWallet(AccountDetails accountDetail, String brainKey, String pinCode) {
AccountDetails accountDetails = new AccountDetails();
accountDetails.wif_key = accountDetail.wif_key;
accountDetails.pinCode = pinCode;
accountDetails.account_name = accountDetail.account_name;
accountDetails.pub_key = accountDetail.pub_key;
accountDetails.brain_key = brainKey;
accountDetails.isSelected = true;
accountDetails.status = "success";
accountDetails.account_id = accountDetail.account_id;
BinHelper myBinHelper = new BinHelper();
myBinHelper.addWallet(accountDetails,brainKey,pinCode,getApplicationContext(),this);
Intent intent;
if ( myBinHelper.numberOfWalletAccounts(getApplicationContext()) <= 1 )
{
intent = new Intent(getApplicationContext(), BackupBrainkeyActivity.class);
}
else
{
intent = new Intent(getApplicationContext(), TabActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
|
package de.bitshares_munich.smartcoinswallet;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import de.bitshares_munich.utils.Helper;
import de.bitshares_munich.utils.SupportMethods;
import de.bitshares_munich.utils.TinyDB;
public class ListViewActivity extends BaseAdapter {
ArrayList<ListviewContactItem> listContact;
HashMap<String,Bitmap> images = new HashMap<String,Bitmap>();
HashMap<String,Boolean> notEmail = new HashMap<String,Boolean>();
ImageLoader imageLoader = ImageLoader.getInstance();
int pos = 0;
Context context;
private LayoutInflater mInflater;
TinyDB tinyDB;
public ListViewActivity(Context _context) {
context = _context;
tinyDB = new TinyDB(context);
mInflater = LayoutInflater.from(context);
listContact = GetlistContact();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return listContact.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return listContact.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
// public View getView(final int position, View convertView, final ViewGroup parent) {
// if (convertView == null)
// convertView = mInflater.inflate(R.layout.listview_contacts, null);
// if (imageLoader == null) {
// imageLoader = ImageLoader.getInstance();
// imageLoader.init(ImageLoaderConfiguration.createDefault(context));
// TextView username = (TextView) convertView.findViewById(R.id.username);
// TextView txtaccount = (TextView) convertView.findViewById(R.id.accountname);
// ImageButton delete = (ImageButton) convertView.findViewById(R.id.deleteitem);
// TextView txtnote = (TextView) convertView.findViewById(R.id.note_txt);
// ImageButton ibEdit = (ImageButton) convertView.findViewById(R.id.editcontact);
// String accountnm = listContact.get(position).GetAccount();
// txtaccount.setText(accountnm);
// String name = listContact.get(position).GetName();
// username.setText(name);
// txtnote.setText(listContact.get(position).GetNote());
// final WebView webView = (WebView) convertView.findViewById(R.id.webViewContacts);
// loadWebView(webView , 40, Helper.hash(accountnm, Helper.SHA256));
// final ImageView ivEmail = (ImageView) convertView.findViewById(R.id.imageEmail);
// ivEmail.setImageBitmap(null);
// imageLoader.loadImage(emailGravatarUrl, new SimpleImageLoadingListener() {
// @Override
// public void onLoadingStarted(String imageUri, View view) {
// if (!listContact.get(position).GetEmail().isEmpty()) {
// webView.setVisibility(View.GONE);
// @Override
// public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Bitmap corner = getRoundedCornerBitmap(loadedImage);
// ivEmail.setImageBitmap(corner);
// ivEmail.setVisibility(View.VISIBLE);
// delete.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
// showDialog(position);
// ibEdit.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
// int index = position;
// Intent intent = new Intent(context, AddEditContacts.class);
// intent.putExtra("id", index);
// intent.putExtra("name", listContact.get(index).GetName());
// intent.putExtra("account", listContact.get(index).GetAccount());
// intent.putExtra("note", listContact.get(index).GetNote());
// intent.putExtra("email", listContact.get(index).GetEmail());
// context.startActivity(intent);
// return convertView;
public View getView(final int position, View convertView, final ViewGroup parent) {
// if (convertView == null) {
if(listContact.get(position).isImage) {
convertView = mInflater.inflate(R.layout.list_view_contacts_imageview, null);
}else {
convertView = mInflater.inflate(R.layout.list_view_contacts_webview, null);
}
// if (imageLoader == null) {
// imageLoader = ImageLoader.getInstance();
// imageLoader.init(ImageLoaderConfiguration.createDefault(context));
TextView username = (TextView) convertView.findViewById(R.id.username);
TextView txtaccount = (TextView) convertView.findViewById(R.id.accountname);
ImageButton delete = (ImageButton) convertView.findViewById(R.id.deleteitem);
TextView txtnote = (TextView) convertView.findViewById(R.id.note_txt);
String accountnm = listContact.get(position).GetAccount();
txtaccount.setText(accountnm);
String name = listContact.get(position).GetName();
username.setText(name);
txtnote.setText(listContact.get(position).GetNote());
delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(position);
}
});
ImageButton ibEdit = (ImageButton) convertView.findViewById(R.id.editcontact);
ibEdit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int index = position;
Intent intent = new Intent(context, AddEditContacts.class);
intent.putExtra("id", index);
intent.putExtra("name", listContact.get(index).GetName());
intent.putExtra("account", listContact.get(index).GetAccount());
intent.putExtra("note", listContact.get(index).GetNote());
intent.putExtra("email", listContact.get(index).GetEmail());
context.startActivity(intent);
}
});
if(listContact.get(position).isImage) {
final ImageView ivEmail = (ImageView) convertView.findViewById(R.id.imageEmail);
setGravator(listContact.get(position).GetEmail(),ivEmail);
// imageLoader.loadImage(emailGravatarUrl, new SimpleImageLoadingListener() {
// @Override
// public void onLoadingStarted(String imageUri, View view) {
// @Override
// public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Bitmap corner = getRoundedCornerBitmap(loadedImage);
// ivEmail.setImageBitmap(corner);
}else {
final WebView webView = (WebView) convertView.findViewById(R.id.webViewContacts);
loadWebView(webView, 40, Helper.hash(accountnm, Helper.SHA256));
}
return convertView;
}
private ArrayList<ListviewContactItem> GetlistContact(){
ArrayList<ListviewContactItem> contactlist = new ArrayList<ListviewContactItem>();
ListviewContactItem contact = new ListviewContactItem();
ArrayList<ListviewContactItem> contacts = tinyDB.getContactObject("Contacts", ListviewContactItem.class);
for (int i = 0; i < contacts.size(); i++) {
contact = new ListviewContactItem();
contact.SetName(contacts.get(i).name);
contact.SetAccount(contacts.get(i).account);
contact.SaveNote(contacts.get(i).note);
if(!contacts.get(i).email.isEmpty()) {
contact.isImage = true;
contact.SaveEmail(contacts.get(i).email);
}
contactlist.add(contact);
}
Collections.sort(contactlist, new ContactNameComparator());
return contactlist;
}
public static class ListviewContactItem{
String name;
String email;
String account;
String note;
public Boolean isImage = false;
void SetName(String n){
name = n;
}
void SetAccount(String n){
account = n;
}
void SaveNote(String n){
note = n;
}
void SaveEmail(String n){
email = n;
}
String GetName(){
return name;
}
String GetAccount(){
return account;
}
String GetNote(){
return note;
}
String GetEmail(){
return email;
}
}
private void loadWebView(WebView webView , int size, String encryptText) {
String htmlShareAccountName = "<html><head><style>body,html { margin:0; padding:0; text-align:center;}</style><meta name=viewport content=width=" + size + ",user-scalable=no/></head><body><canvas width=" + size + " height=" + size + " data-jdenticon-hash=" + encryptText + "></canvas><script src=https://cdn.jsdelivr.net/jdenticon/1.3.2/jdenticon.min.js async></script></body></html>";
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadData(htmlShareAccountName, "text/html", "UTF-8");
}
void removeFromlist(int id){
ArrayList<ListViewActivity.ListviewContactItem> contacts = tinyDB.getContactObject("Contacts", ListViewActivity.ListviewContactItem.class);
contacts.remove(id);
tinyDB.putContactsObject("Contacts", contacts);
}
public void loadmore(){
pos=0;
listContact.clear();
}
public void showDialog(final int position){
final Dialog dialog = new Dialog(context);
//dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
// dialog.setTitle(R.string.pin_verification);
dialog.setContentView(R.layout.alert_delete_dialog);
Button btnDone = (Button) dialog.findViewById(R.id.btnDone);
Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
TextView textView = (TextView) dialog.findViewById(R.id.alertMsg);
String alertMsg = context.getString(R.string.delete);
String accountName = listContact.get(position).GetAccount();
alertMsg = alertMsg + " \"" + accountName + "\" ?";
textView.setText(alertMsg);
btnDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listContact.remove(position);
removeFromlist(position);
notifyDataSetChanged();
dialog.cancel();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel();
}
});
// dialog.setCancelable(false);
dialog.show();
}
public static class ContactNameComparator implements Comparator<ListViewActivity.ListviewContactItem>
{
public int compare(ListViewActivity.ListviewContactItem left, ListViewActivity.ListviewContactItem right) {
return left.name.toLowerCase().compareTo(right.name.toLowerCase());
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView _bmImage) {
bmImage = _bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
SupportMethods.testing("alpha",e.getMessage(),"error");
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if(result==null) {
Bitmap corner = BitmapFactory.decodeResource(context.getResources(), R.drawable.gravtr);
bmImage.setImageBitmap(getRoundedCornerBitmap(corner));
}
else {
Bitmap corner = getRoundedCornerBitmap(result);
bmImage.setImageBitmap(corner);
}
}
}
void setGravator(String email,ImageView imageView){
String emailGravatarUrl = "https:
new DownloadImageTask(imageView)
.execute(emailGravatarUrl);
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 90;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
}
|
package eu.kanade.mangafeed.ui.manga.chapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import eu.kanade.mangafeed.R;
import eu.kanade.mangafeed.data.database.models.Chapter;
import eu.kanade.mangafeed.data.download.DownloadService;
import eu.kanade.mangafeed.ui.base.activity.BaseActivity;
import eu.kanade.mangafeed.ui.base.fragment.BaseRxFragment;
import eu.kanade.mangafeed.ui.decoration.DividerItemDecoration;
import eu.kanade.mangafeed.ui.manga.MangaActivity;
import eu.kanade.mangafeed.ui.reader.ReaderActivity;
import nucleus.factory.RequiresPresenter;
import rx.Observable;
@RequiresPresenter(ChaptersPresenter.class)
public class ChaptersFragment extends BaseRxFragment<ChaptersPresenter> implements
ActionMode.Callback, ChaptersAdapter.OnItemClickListener {
@Bind(R.id.chapter_list) RecyclerView chapters;
@Bind(R.id.swipe_refresh) SwipeRefreshLayout swipeRefresh;
@Bind(R.id.toolbar_bottom) Toolbar toolbarBottom;
@Bind(R.id.action_sort) ImageView sortBtn;
@Bind(R.id.action_next_unread) ImageView nextUnreadBtn;
@Bind(R.id.action_show_unread) CheckBox readCb;
@Bind(R.id.action_show_downloaded) CheckBox downloadedCb;
private ChaptersAdapter adapter;
private ActionMode actionMode;
public static ChaptersFragment newInstance() {
return new ChaptersFragment();
}
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_manga_chapters, container, false);
ButterKnife.bind(this, view);
chapters.setLayoutManager(new LinearLayoutManager(getActivity()));
chapters.addItemDecoration(new DividerItemDecoration(ContextCompat.getDrawable(this.getContext(), R.drawable.line_divider)));
createAdapter();
setSwipeRefreshListener();
readCb.setOnCheckedChangeListener((arg, isCheked) -> getPresenter().setReadFilter(isCheked));
sortBtn.setOnClickListener(v -> getPresenter().revertSortOrder());
nextUnreadBtn.setOnClickListener(v -> {
Chapter chapter = getPresenter().getNextUnreadChapter();
if (chapter != null) {
openChapter(chapter);
} else {
Toast.makeText(getContext(), R.string.no_next_chapter, Toast.LENGTH_SHORT).show();
}
});
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.chapters, menu);
super.onCreateOptionsMenu(menu, inflater);
getPresenter().initSortIcon();
getPresenter().initReadCb();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
getPresenter().refreshChapters();
break;
}
return super.onOptionsItemSelected(item);
}
private void createAdapter() {
adapter = new ChaptersAdapter(this);
chapters.setAdapter(adapter);
}
private void setSwipeRefreshListener() {
swipeRefresh.setOnRefreshListener(() -> getPresenter().refreshChapters());
}
public void onNextChapters(List<Chapter> chapters) {
adapter.setItems(chapters);
closeActionMode();
}
public void onNextOnlineChapters() {
swipeRefresh.setRefreshing(false);
}
public void setSwipeRefreshing() {
swipeRefresh.setRefreshing(true);
}
public boolean isOnlineManga() {
return ((MangaActivity) getActivity()).isOnlineManga();
}
protected void openChapter(Chapter chapter) {
getPresenter().onChapterClicked(chapter);
Intent intent = ReaderActivity.newIntent(getActivity());
startActivity(intent);
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.chapter_selection, menu);
adapter.setMode(ChaptersAdapter.MODE_MULTI);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_select_all:
return onSelectAll();
case R.id.action_mark_as_read:
return onMarkAsRead(getSelectedChapters());
case R.id.action_mark_as_unread:
return onMarkAsUnread(getSelectedChapters());
case R.id.action_download:
return onDownload(getSelectedChapters());
case R.id.action_delete:
return onDelete(getSelectedChapters());
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
adapter.setMode(ChaptersAdapter.MODE_SINGLE);
adapter.clearSelection();
actionMode = null;
}
private Observable<Chapter> getSelectedChapters() {
return Observable.from(adapter.getSelectedItems())
.map(adapter::getItem);
}
public void closeActionMode() {
if (actionMode != null)
actionMode.finish();
}
protected boolean onSelectAll() {
adapter.selectAll();
setContextTitle(adapter.getSelectedItemCount());
actionMode.invalidate();
return true;
}
protected boolean onMarkAsRead(Observable<Chapter> chapters) {
getPresenter().markChaptersRead(chapters, true);
return true;
}
protected boolean onMarkAsUnread(Observable<Chapter> chapters) {
getPresenter().markChaptersRead(chapters, false);
return true;
}
protected boolean onDownload(Observable<Chapter> chapters) {
DownloadService.start(getActivity());
getPresenter().downloadChapters(chapters);
closeActionMode();
return true;
}
protected boolean onDelete(Observable<Chapter> chapters) {
getPresenter().deleteChapters(chapters);
closeActionMode();
return true;
}
@Override
public boolean onListItemClick(int position) {
if (actionMode != null && adapter.getMode() == ChaptersAdapter.MODE_MULTI) {
toggleSelection(position);
return true;
} else {
openChapter(adapter.getItem(position));
return false;
}
}
@Override
public void onListItemLongClick(int position) {
if (actionMode == null)
actionMode = ((BaseActivity) getActivity()).startSupportActionMode(this);
toggleSelection(position);
}
private void toggleSelection(int position) {
adapter.toggleSelection(position, false);
int count = adapter.getSelectedItemCount();
if (count == 0) {
actionMode.finish();
} else {
setContextTitle(count);
actionMode.invalidate();
}
}
private void setContextTitle(int count) {
actionMode.setTitle(getString(R.string.selected_chapters_title, count));
}
public void setSortIcon(boolean aToZ) {
if (sortBtn != null) {
sortBtn.setImageResource(!aToZ ? R.drawable.ic_expand_less_white_36dp : R.drawable.ic_expand_more_white_36dp);
}
}
public void setReadFilter(boolean onlyUnread) {
if (readCb != null) readCb.setChecked(onlyUnread);
}
}
|
package nerd.tuxmobil.fahrplan.congress.changes;
import android.app.Activity;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import nerd.tuxmobil.fahrplan.congress.R;
import nerd.tuxmobil.fahrplan.congress.contract.BundleKeys;
import nerd.tuxmobil.fahrplan.congress.schedule.MainActivity;
public class ChangesDialog extends DialogFragment {
public static final String FRAGMENT_TAG = "changesDialog";
private int changed;
private int added;
private int cancelled;
private int markedAffected;
private String version;
public static ChangesDialog newInstance(String version, int changed, int added,
int cancelled, int marked) {
ChangesDialog dialog = new ChangesDialog();
Bundle args = new Bundle();
args.putInt(BundleKeys.CHANGES_DLG_NUM_CHANGED, changed);
args.putInt(BundleKeys.CHANGES_DLG_NUM_NEW, added);
args.putInt(BundleKeys.CHANGES_DLG_NUM_CANCELLED, cancelled);
args.putInt(BundleKeys.CHANGES_DLG_NUM_MARKED, marked);
args.putString(BundleKeys.CHANGES_DLG_VERSION, version);
dialog.setArguments(args);
dialog.setCancelable(false);
return dialog;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
changed = args.getInt(BundleKeys.CHANGES_DLG_NUM_CHANGED);
added = args.getInt(BundleKeys.CHANGES_DLG_NUM_NEW);
cancelled = args.getInt(BundleKeys.CHANGES_DLG_NUM_CANCELLED);
markedAffected = args.getInt(BundleKeys.CHANGES_DLG_NUM_MARKED);
version = args.getString(BundleKeys.CHANGES_DLG_VERSION);
}
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Activity activity = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(activity)
.setTitle(getString(R.string.schedule_update))
.setPositiveButton(R.string.btn_dlg_browse, (dialog, which) -> onBrowse())
.setNegativeButton(R.string.btn_dlg_later, (dialog, which) -> onLater());
LayoutInflater inflater = activity.getLayoutInflater();
View msgView = inflater.inflate(R.layout.changes_dialog, null);
TextView changes1 = msgView.findViewById(R.id.changes_dlg_text);
SpannableStringBuilder span = new SpannableStringBuilder();
span.append(getString(R.string.changes_dlg_text1));
span.append(" ");
int spanStart = span.length();
span.append(version);
Resources resources = getResources();
int spanColor = ContextCompat.getColor(activity, R.color.colorAccent);
span.setSpan(new ForegroundColorSpan(spanColor),
spanStart, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span.append(getString(R.string.changes_dlg_text2, version,
resources.getQuantityString(R.plurals.numberOfLectures, changed, changed),
resources.getQuantityString(R.plurals.being, added, added),
resources.getQuantityString(R.plurals.being, cancelled, cancelled)));
changes1.setText(span);
TextView changes2 = msgView.findViewById(R.id.changes_dlg_text2);
changes2.setText(getString(R.string.changes_dlg_text3, markedAffected));
builder.setView(msgView);
return builder.create();
}
private void onBrowse() {
flagChangesAsSeen();
FragmentActivity activity = getActivity();
if (activity instanceof MainActivity) {
((MainActivity) activity).openLectureChanges();
}
}
private void onLater() {
flagChangesAsSeen();
}
private void flagChangesAsSeen() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(BundleKeys.PREFS_CHANGES_SEEN, true);
edit.commit();
}
}
|
package nerd.tuxmobil.fahrplan.congress.schedule;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import org.ligi.snackengage.SnackEngage;
import org.ligi.snackengage.SnackEngageBuilder;
import org.ligi.snackengage.conditions.AfterNumberOfOpportunities;
import org.ligi.snackengage.conditions.NeverAgainWhenClickedOnce;
import org.ligi.snackengage.snacks.BaseSnack;
import org.ligi.snackengage.snacks.DefaultRateSnack;
import org.ligi.snackengage.snacks.OpenURLSnack;
import java.util.List;
import nerd.tuxmobil.fahrplan.congress.BuildConfig;
import nerd.tuxmobil.fahrplan.congress.MyApp;
import nerd.tuxmobil.fahrplan.congress.MyApp.TASKS;
import nerd.tuxmobil.fahrplan.congress.R;
import nerd.tuxmobil.fahrplan.congress.about.AboutDialog;
import nerd.tuxmobil.fahrplan.congress.alarms.AlarmList;
import nerd.tuxmobil.fahrplan.congress.base.AbstractListFragment;
import nerd.tuxmobil.fahrplan.congress.base.BaseActivity;
import nerd.tuxmobil.fahrplan.congress.changes.ChangeListActivity;
import nerd.tuxmobil.fahrplan.congress.changes.ChangeListFragment;
import nerd.tuxmobil.fahrplan.congress.changes.ChangesDialog;
import nerd.tuxmobil.fahrplan.congress.contract.BundleKeys;
import nerd.tuxmobil.fahrplan.congress.details.EventDetail;
import nerd.tuxmobil.fahrplan.congress.details.EventDetailFragment;
import nerd.tuxmobil.fahrplan.congress.favorites.StarredListActivity;
import nerd.tuxmobil.fahrplan.congress.favorites.StarredListFragment;
import nerd.tuxmobil.fahrplan.congress.models.Lecture;
import nerd.tuxmobil.fahrplan.congress.navigation.C3navSnack;
import nerd.tuxmobil.fahrplan.congress.net.CertificateDialogFragment;
import nerd.tuxmobil.fahrplan.congress.net.CustomHttpClient;
import nerd.tuxmobil.fahrplan.congress.net.FetchScheduleResult;
import nerd.tuxmobil.fahrplan.congress.net.HttpStatus;
import nerd.tuxmobil.fahrplan.congress.reporting.TraceDroidEmailSender;
import nerd.tuxmobil.fahrplan.congress.repositories.AppRepository;
import nerd.tuxmobil.fahrplan.congress.settings.SettingsActivity;
import nerd.tuxmobil.fahrplan.congress.sidepane.OnSidePaneCloseListener;
import nerd.tuxmobil.fahrplan.congress.utils.ConfirmationDialog;
import nerd.tuxmobil.fahrplan.congress.utils.FahrplanMisc;
public class MainActivity extends BaseActivity implements
OnSidePaneCloseListener,
FahrplanFragment.OnRefreshEventMarkers,
CertificateDialogFragment.OnCertAccepted,
AbstractListFragment.OnLectureListClick,
FragmentManager.OnBackStackChangedListener,
ConfirmationDialog.OnConfirmationDialogClicked {
private static final String LOG_TAG = "MainActivity";
private static final String VENUE_LEIPZIG_MESSE = "leipzig-messe";
private ProgressDialog progress = null;
private ProgressBar progressBar = null;
private boolean showUpdateAction = true;
private static MainActivity instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
MyApp.LogDebug(LOG_TAG, "onCreate");
setContentView(R.layout.main_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
progressBar = findViewById(R.id.progress);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.fahrplan);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
int actionBarColor = ContextCompat.getColor(this, R.color.colorActionBar);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(actionBarColor));
TraceDroidEmailSender.sendStackTraces(this);
progress = null;
AppRepository appRepository = AppRepository.Companion.getInstance(this);
MyApp.meta = appRepository.readMeta();
FahrplanMisc.loadDays(this);
MyApp.LogDebug(LOG_TAG, "task_running:" + MyApp.task_running);
switch (MyApp.task_running) {
case FETCH:
MyApp.LogDebug(LOG_TAG, "fetch was pending, restart");
showFetchingStatus();
break;
case PARSE:
MyApp.LogDebug(LOG_TAG, "parse was pending, restart");
showParsingStatus();
break;
case NONE:
if ((MyApp.meta.getNumDays() == 0) && (savedInstanceState == null)) {
MyApp.LogDebug(LOG_TAG, "fetch in onCreate bc. numDays==0");
fetchFahrplan();
}
break;
}
getSupportFragmentManager().addOnBackStackChangedListener(this);
if (findViewById(R.id.schedule) != null) {
if (findFragment(FahrplanFragment.FRAGMENT_TAG) == null) {
replaceFragment(R.id.schedule, new FahrplanFragment(),
FahrplanFragment.FRAGMENT_TAG);
}
}
if (findViewById(R.id.detail) == null) {
removeFragment(EventDetailFragment.FRAGMENT_TAG);
}
initUserEngagement();
}
private void initUserEngagement() {
int actionColor = ContextCompat.getColor(this, R.color.colorAccent);
final BaseSnack snack = new DefaultRateSnack()
.overrideTitleText(getString(R.string.snack_engage_rate_title))
.overrideActionText(getString(R.string.snack_engage_rate_action));
snack.setActionColor(actionColor);
SnackEngageBuilder snackEngageBuilder = SnackEngage.from(this);
if (VENUE_LEIPZIG_MESSE.equals(BuildConfig.VENUE)) {
OpenURLSnack c3navSnack = new C3navSnack(this);
c3navSnack.withConditions(
new NeverAgainWhenClickedOnce(),
new AfterNumberOfOpportunities(7));
snackEngageBuilder.withSnack(c3navSnack);
}
snackEngageBuilder
.withSnack(snack)
.build()
.engageWhenAppropriate();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
MyApp.LogDebug(LOG_TAG, "onNewIntent");
setIntent(intent);
}
public void onGotResponse(@NonNull FetchScheduleResult fetchScheduleResult) {
HttpStatus status = fetchScheduleResult.getHttpStatus();
MyApp.LogDebug(LOG_TAG, "Response... " + status);
MyApp.task_running = TASKS.NONE;
if (MyApp.meta.getNumDays() == 0) {
hideProgressDialog();
}
if ((status == HttpStatus.HTTP_OK) || (status == HttpStatus.HTTP_NOT_MODIFIED)) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Time now = new Time();
now.setToNow();
long millis = now.toMillis(true);
Editor edit = prefs.edit();
edit.putLong("last_fetch", millis);
edit.commit();
}
if (status != HttpStatus.HTTP_OK) {
switch (status) {
case HTTP_CANCELLED:
break;
case HTTP_LOGIN_FAIL_UNTRUSTED_CERTIFICATE:
CertificateDialogFragment dialogFragment = CertificateDialogFragment.newInstance(fetchScheduleResult.getExceptionMessage());
dialogFragment.show(getSupportFragmentManager(), CertificateDialogFragment.FRAGMENT_TAG);
break;
}
CustomHttpClient.showHttpError(this, status, fetchScheduleResult.getHostName());
progressBar.setVisibility(View.INVISIBLE);
showUpdateAction = true;
supportInvalidateOptionsMenu();
return;
}
MyApp.LogDebug(LOG_TAG, "yehhahh");
progressBar.setVisibility(View.INVISIBLE);
showUpdateAction = true;
supportInvalidateOptionsMenu();
MyApp.fahrplan_xml = fetchScheduleResult.getScheduleXml();
MyApp.meta.setETag(fetchScheduleResult.getETag());
// Parser is automatically invoked when response has been received.
showParsingStatus();
MyApp.task_running = TASKS.PARSE;
}
public void onParseDone(Boolean result, String version) {
MyApp.LogDebug(LOG_TAG, "parseDone: " + result + " , numDays=" + MyApp.meta.getNumDays());
MyApp.task_running = TASKS.NONE;
MyApp.fahrplan_xml = null;
if (MyApp.meta.getNumDays() == 0) {
hideProgressDialog();
}
progressBar.setVisibility(View.INVISIBLE);
showUpdateAction = true;
supportInvalidateOptionsMenu();
Fragment fragment = findFragment(FahrplanFragment.FRAGMENT_TAG);
if (fragment != null) {
((FahrplanFragment) fragment).onParseDone(result, version);
}
fragment = findFragment(ChangeListFragment.FRAGMENT_TAG);
if (fragment != null && fragment instanceof ChangeListFragment) {
((ChangeListFragment) fragment).onRefresh();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean(BundleKeys.PREFS_CHANGES_SEEN, true)) {
showChangesDialog();
}
}
public void showFetchingStatus() {
if (MyApp.meta.getNumDays() == 0) {
// initial load
MyApp.LogDebug(LOG_TAG, "fetchFahrplan with numDays == 0");
progress = ProgressDialog.show(this, "", getResources().getString(
R.string.progress_loading_data), true);
} else {
MyApp.LogDebug(LOG_TAG, "show fetch status");
progressBar.setVisibility(View.VISIBLE);
showUpdateAction = false;
supportInvalidateOptionsMenu();
}
}
public void showParsingStatus() {
if (MyApp.meta.getNumDays() == 0) {
// initial load
progress = ProgressDialog.show(this, "", getResources().getString(
R.string.progress_processing_data), true);
} else {
MyApp.LogDebug(LOG_TAG, "show parse status");
progressBar.setVisibility(View.VISIBLE);
showUpdateAction = false;
supportInvalidateOptionsMenu();
}
}
public void fetchFahrplan() {
if (MyApp.task_running == TASKS.NONE) {
MyApp.task_running = TASKS.FETCH;
showFetchingStatus();
AppRepository appRepository = AppRepository.Companion.getInstance(this);
String url = appRepository.readScheduleUrl();
appRepository.loadSchedule(url, MyApp.meta.getETag(), fetchScheduleResult -> {
onGotResponse(fetchScheduleResult);
return null;
}, (result, version) -> {
onParseDone(result, version);
return null;
});
} else {
MyApp.LogDebug(LOG_TAG, "fetch already in progress");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
hideProgressDialog();
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean(BundleKeys.PREFS_CHANGES_SEEN, true) == false) {
showChangesDialog();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.mainmenu, menu);
MenuItem item = menu.findItem(R.id.item_refresh);
if (item != null) {
item.setVisible(showUpdateAction);
}
return true;
}
void showChangesDialog() {
Fragment fragment = findFragment(ChangesDialog.FRAGMENT_TAG);
if (fragment == null) {
List<Lecture> changedLectures = FahrplanMisc.readChanges(this);
DialogFragment changesDialog = ChangesDialog.newInstance(
MyApp.meta.getVersion(),
FahrplanMisc.getChangedLectureCount(changedLectures, false),
FahrplanMisc.getNewLectureCount(changedLectures, false),
FahrplanMisc.getCancelledLectureCount(changedLectures, false),
FahrplanMisc.getChangedLectureCount(changedLectures, true) +
FahrplanMisc.getNewLectureCount(changedLectures, true) +
FahrplanMisc.getCancelledLectureCount(changedLectures, true));
changesDialog.show(getSupportFragmentManager(), ChangesDialog.FRAGMENT_TAG);
}
}
void showAboutDialog() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.addToBackStack(null);
DialogFragment about = new AboutDialog();
about.show(ft, "about");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.item_refresh:
fetchFahrplan();
return true;
case R.id.item_about:
showAboutDialog();
return true;
case R.id.item_alarms:
intent = new Intent(this, AlarmList.class);
startActivityForResult(intent, MyApp.ALARMLIST);
return true;
case R.id.item_settings:
intent = new Intent(this, SettingsActivity.class);
startActivityForResult(intent, MyApp.SETTINGS);
return true;
case R.id.item_changes:
openLectureChanges();
return true;
case R.id.item_starred_list:
openFavorites();
return true;
default:
}
return super.onOptionsItemSelected(item);
}
public void openLectureDetail(Lecture lecture, int mDay) {
if (lecture == null) return;
FrameLayout sidePane = findViewById(R.id.detail);
MyApp.LogDebug(LOG_TAG, "openLectureDetail sidePane=" + sidePane);
if (sidePane != null) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack(EventDetailFragment.FRAGMENT_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
Bundle args = new Bundle();
args.putString(BundleKeys.EVENT_TITLE, lecture.title);
args.putString(BundleKeys.EVENT_SUBTITLE, lecture.subtitle);
args.putString(BundleKeys.EVENT_ABSTRACT, lecture.abstractt);
args.putString(BundleKeys.EVENT_DESCRIPTION, lecture.description);
args.putString(BundleKeys.EVENT_SPEAKERS, lecture.getFormattedSpeakers());
args.putString(BundleKeys.EVENT_LINKS, lecture.links);
args.putString(BundleKeys.EVENT_ID, lecture.lecture_id);
args.putInt(BundleKeys.EVENT_TIME, lecture.startTime);
args.putInt(BundleKeys.EVENT_DAY, mDay);
args.putString(BundleKeys.EVENT_ROOM, lecture.room);
args.putString(BundleKeys.EVENT_SLUG, lecture.slug);
args.putBoolean(BundleKeys.SIDEPANE, true);
EventDetailFragment eventDetailFragment = new EventDetailFragment();
eventDetailFragment.setArguments(args);
replaceFragment(R.id.detail, eventDetailFragment,
EventDetailFragment.FRAGMENT_TAG, EventDetailFragment.FRAGMENT_TAG);
} else {
EventDetail.startForResult(this, lecture, mDay);
}
}
@Override
public void onSidePaneClose(@NonNull String fragmentTag) {
View sidePane = findViewById(R.id.detail);
if (sidePane != null) {
sidePane.setVisibility(View.GONE);
}
removeFragment(fragmentTag);
}
public void reloadAlarms() {
Fragment fragment = findFragment(FahrplanFragment.FRAGMENT_TAG);
if (fragment != null) {
((FahrplanFragment) fragment).loadAlarms(this);
}
}
@Override
public void refreshEventMarkers() {
Fragment fragment = findFragment(FahrplanFragment.FRAGMENT_TAG);
if (fragment != null) {
((FahrplanFragment) fragment).refreshEventMarkers();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case MyApp.ALARMLIST:
case MyApp.EVENTVIEW:
case MyApp.CHANGELOG:
case MyApp.STARRED:
if (resultCode == Activity.RESULT_OK) {
refreshEventMarkers();
}
break;
case MyApp.SETTINGS:
if (resultCode == Activity.RESULT_OK) {
boolean defaultValue = getResources().getBoolean(R.bool.preferences_alternative_highlight_enabled_default_value);
if (intent.getBooleanExtra(BundleKeys.PREFS_ALTERNATIVE_HIGHLIGHT, defaultValue)) {
if (findViewById(R.id.schedule) != null) {
replaceFragment(R.id.schedule, new FahrplanFragment(),
FahrplanFragment.FRAGMENT_TAG);
}
}
}
}
}
@Override
public void onCertAccepted() {
MyApp.LogDebug(LOG_TAG, "fetch on cert accepted.");
fetchFahrplan();
}
@Override
public void onLectureListClick(Lecture lecture) {
if (lecture != null) {
openLectureDetail(lecture, lecture.day);
}
}
@Override
public void onBackStackChanged() {
FragmentManager manager = getSupportFragmentManager();
int detailView = R.id.detail;
toggleSidePaneVisibility(manager, detailView);
supportInvalidateOptionsMenu();
}
private void hideProgressDialog() {
if (progress != null) {
progress.dismiss();
progress = null;
}
}
private void toggleSidePaneVisibility(FragmentManager manager, @IdRes int detailView) {
Fragment fragment = manager.findFragmentById(detailView);
boolean found = fragment != null;
View sidePane = findViewById(detailView);
if (sidePane != null) {
sidePane.setVisibility(found ? View.VISIBLE : View.GONE);
}
}
public void refreshFavoriteList() {
Fragment fragment = findFragment(StarredListFragment.FRAGMENT_TAG);
if (fragment != null) {
((StarredListFragment) fragment).onRefresh(this);
}
ActivityCompat.invalidateOptionsMenu(this);
}
private void openFavorites() {
FrameLayout sidePane = findViewById(R.id.detail);
if (sidePane == null) {
Intent intent = new Intent(this, StarredListActivity.class);
startActivityForResult(intent, MyApp.STARRED);
} else {
sidePane.setVisibility(View.VISIBLE);
replaceFragment(R.id.detail, StarredListFragment.newInstance(true),
StarredListFragment.FRAGMENT_TAG, StarredListFragment.FRAGMENT_TAG);
}
}
public void openLectureChanges() {
FrameLayout sidePane = findViewById(R.id.detail);
if (sidePane == null) {
Intent intent = new Intent(this, ChangeListActivity.class);
startActivityForResult(intent, MyApp.CHANGELOG);
} else {
sidePane.setVisibility(View.VISIBLE);
replaceFragment(R.id.detail, ChangeListFragment.newInstance(true),
ChangeListFragment.FRAGMENT_TAG, ChangeListFragment.FRAGMENT_TAG);
}
}
@Override
public void onAccepted(int dlgRequestCode) {
switch (dlgRequestCode) {
case StarredListFragment.DELETE_ALL_FAVORITES_REQUEST_CODE:
Fragment fragment = findFragment(StarredListFragment.FRAGMENT_TAG);
if (fragment != null) {
((StarredListFragment) fragment).deleteAllFavorites();
}
break;
}
}
@Override
public void onDenied(int dlgRequestCode) {
}
public static MainActivity getInstance() {
return instance;
}
}
|
package org.clintonhealthaccess.lmis.app.services;
import com.google.inject.Inject;
import com.j256.ormlite.dao.Dao;
import org.clintonhealthaccess.lmis.app.models.User;
import org.clintonhealthaccess.lmis.app.persistence.DbUtil;
import org.clintonhealthaccess.lmis.app.remote.LmisServer;
import org.clintonhealthaccess.lmis.app.sync.SyncManager;
import java.sql.SQLException;
import java.util.List;
import static org.clintonhealthaccess.lmis.app.persistence.DbUtil.Operation;
public class UserService {
@Inject
private DbUtil dbUtil;
@Inject
private LmisServer lmisServer;
@Inject
private SyncManager syncManager;
public boolean userRegistered() {
return dbUtil.withDao(User.class, new Operation<User, Boolean>() {
@Override
public Boolean operate(Dao<User, String> dao) throws SQLException {
return dao.countOf() > 0;
}
});
}
public User register(final String username, final String password) {
lmisServer.validateLogin(new User(username, password));
User user = saveUserToDatabase(username, password);
syncManager.createSyncAccount(user);
return user;
}
private User saveUserToDatabase(final String username, final String password) {
return dbUtil.withDao(User.class, new Operation<User, User>() {
@Override
public User operate(Dao<User, String> dao) throws SQLException {
User user = new User(username, password, "KB");
dao.create(user);
return user;
}
});
}
public User getRegisteredUser() throws IndexOutOfBoundsException {
return dbUtil.withDao(User.class, new Operation<User, User>() {
@Override
public User operate(Dao<User, String> dao) throws SQLException {
List<User> users = dao.queryForAll();
return users.get(0);
}
});
}
}
|
package nodomain.freeyourgadget.gadgetbridge.test;
import android.support.annotation.NonNull;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import nodomain.freeyourgadget.gadgetbridge.Logging;
import nodomain.freeyourgadget.gadgetbridge.util.FileUtils;
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.Assert.fail;
/**
* Tests dynamic enablement and disablement of file appenders.
*/
public class LoggingTest extends TestBase {
public LoggingTest() throws Exception {
}
private Logging logging = new Logging() {
@Override
protected String createLogDirectory() throws IOException {
return logFilesDir.getAbsolutePath();
}
};
@After
public void tearDown() {
assertTrue(FileUtils.deleteRecursively(getLogFilesDir()));
}
@NonNull
private File getLogFilesDir() {
String dirName = System.getProperty(Logging.PROP_LOGFILES_DIR);
if (dirName != null && dirName.length() > 5) {
File dir = new File(dirName);
return dir;
}
fail("Property " + Logging.PROP_LOGFILES_DIR + " has invalid value: " + dirName);
return null; // not reached
}
@Test
public void testToggleLogging() {
try {
File dir = getLogFilesDir();
} catch (AssertionError ignored) {
// expected, as not yet set up
}
try {
logging.setupLogging(true);
File dir = getLogFilesDir();
assertEquals(1, dir.list().length);
assertNotNull(logging.getFileLogger());
assertTrue(logging.getFileLogger().isStarted());
logging.setupLogging(false);
assertNotNull(logging.getFileLogger());
assertFalse(logging.getFileLogger().isStarted());
logging.setupLogging(true);
assertNotNull(logging.getFileLogger());
assertTrue(logging.getFileLogger().isStarted());
} catch (AssertionError ex) {
logging.debugLoggingConfiguration();
System.err.println(System.getProperty("java.class.path"));
throw ex;
}
}
}
|
package deltadak.ui;
import deltadak.Database;
import deltadak.HomeworkTask;
import javafx.beans.InvalidationListener;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldTreeCell;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.*;
import javafx.scene.text.TextAlignment;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import static java.lang.Math.min;
/**
* Custom TextFieldTreeCell, because we can't set the converter on a regular
* TreeCell.
*/
public class CustomTreeCell extends TextFieldTreeCell<HomeworkTask> {
/** Temporary fix for too long labels. Should equal the size of the combobox plus the size of the checkbox plus the size of the little arrow to view subtasks. */
private int LABEL_MAGIK = 215;
private ObservableList<String> comboList;
private TreeItem<HomeworkTask> root; // the root item of the TreeView
private Controller controller;
private HBox cellBox;
private CheckBox checkBox;
private Label label;
private ComboBox<String> comboBox;
private ContextMenu contextMenu;
/**
* Each CustomTreeCell keeps a reference to the listener of the
* ComboBox, in order to choose whether to block it temporarily or not.
*/
InvalidationListenerWithBlocker labelChangeListener;
ChangeListenerWithBlocker doneChangeListener;
/**
* Constructor for the CustomTreeCell.
* @param controller To keep a reference to the Controller to access
* methods.
* @param root The root of the TreeView this CustomTreeCell is a part of.
*/
CustomTreeCell(Controller controller, TreeItem<HomeworkTask> root) {
this.controller = controller;
this.root = root;
checkBox = new CheckBox();
comboList = FXCollections
.observableArrayList(Database.INSTANCE.getLabels());
comboList.add(0, "<no label>");
comboBox = new ComboBox<>(comboList);
}
/**
* Adds to a cell:
* - the converter,
* - listeners for a changed value,
* - drag and drop listeners,
* - what has to happen when editing,
* - context menu.
* @param tree The TreeView this TreeCell is a part of.
* @param localDate The date to which this TreeView (and thus TreeCell) belongs.
*/
public void setup(TreeView<HomeworkTask> tree, LocalDate localDate) {
// update text on changes
setConverter(new TaskConverter(this));
// update label on changes
comboBox.valueProperty().addListener(
(observable, oldValue, newValue) -> {
HomeworkTask task = this.getTreeItem().getValue();
if (newValue.equals("<no label>")) {
task.setLabel("");
comboBox.setValue("");
} else {
task.setLabel(newValue);
}
}
);
// If an item is selected, deselect all other items.
tree.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
// We use our custom select method.
select(
tree, () -> tree.getSelectionModel().select(newValue)
);
}
});
setOnLabelChangeListener(tree, localDate);
setOnDoneChangeListener(tree, localDate);
setOnDragDetected();
setOnDragOver();
setOnDragEntered(tree);
setOnDragExited(tree);
setOnDragDropped(tree, localDate);
setOnDragDone(tree, localDate);
setupSubtasksEditing(tree, localDate);
// create the context menu
contextMenu = createContextMenu(tree, localDate);
}
/**
* Initialize what happens after the user edited a subtask.
* @param tree The TreeView in which an item was edited.
* @param localDate The day of the TreeView.
*/
private void setupSubtasksEditing(TreeView<HomeworkTask> tree, LocalDate localDate) {
tree.setOnEditCommit(event -> {
TreeItem<HomeworkTask> editingItem = getTreeView().getEditingItem();
// if we are editing one of the subtasks
if(!editingItem.getParent().equals(root)) {
// if we're not adding an empty task, create another subtask
if(!event.getNewValue().getText().equals("")){
createSubTask(editingItem.getParent());
}
} else { // if we are not editing a subtask
// insert the task in the expanded table
controller.insertExpandedItem(editingItem.getValue()
.getDatabaseID(), false);
}
// update the database with the current first level items
controller.updateDatabase(localDate, controller.convertTreeToArrayList(tree));
});
}
/**
* Select a TreeItem in a TreeView, and deselect all other items.
* @param tree Any TreeView.
* @param selectionFunction The function to select the right item, can select using index or TreeItems. e.g. tree.getSelectionModel().select(index)
*/
private void select(TreeView<HomeworkTask> tree, Runnable selectionFunction) {
// We want to clear the selection on all the other listviews, otherwise weird 'half-selected' greyed out cells are left behind.
// A TreeView is inside a VBox inside the GridPane, so node will be a VBox
// Hence we need to circumvent a little to clear selection of all other listviews
for(Node node : tree.getParent().getParent().getChildrenUnmodifiable()) {
if (node instanceof VBox) {
// We assume the title (a Label) is first, Pane is second, treeview is third
Node treeNode = ((VBox) node).getChildren().get(2);
// First deselect all of them...
if ((treeNode instanceof TreeView) ) {
((TreeView) treeNode).getSelectionModel().clearSelection();
}
}
}
// ... then reselect this one
selectionFunction.run();
}
/**
* Sets the layout of a TreeCell. Always contains a CheckBox and
* a Label (text). Also contains a ComboBox if the Cell is the root of a
* task.
* @param homeworkTask The Homework task to be displayed in the Cell.
* @param empty Whether or not the new Cell displays data.
*/
@Override
public void updateItem(HomeworkTask homeworkTask, boolean empty) {
super.updateItem(homeworkTask, empty);
if(isEmpty()) {
setGraphic(null);
setText(null);
} else {
// create the items that are on every cell
cellBox = new HBox(10);
// block the listener on the checkbox when we manually toggle it
// so it corresponds to the value in the database
doneChangeListener.setBlock(true);
boolean done = homeworkTask.getDone();
checkBox.setSelected(done); // manually toggle (if necessary)
doneChangeListener.setBlock(false); // unblock the listener
label = new Label(homeworkTask.getText());
// This won't work for long text without spaces, and more.
// label.prefWidthProperty().bind(getTreeView().widthProperty().subtract(comboBox.widthProperty()).subtract(checkBox.widthProperty()));
// combobox.getWidth() is equal to 0 here, we can't use that.
// Result:
// label.setPrefWidth(getTreeView().getWidth() - LABEL_MAGIK);
// This works? :
label.prefWidthProperty().bind(getTreeView().widthProperty()
.subtract(LABEL_MAGIK));
label.setWrapText(true);
label.setTextAlignment(TextAlignment.JUSTIFY);
// Get style from the database and apply to the item
String color = homeworkTask.getColor();
// On dark backgrounds, change text color.
setWhiteComboboxText();
setStyle("-fx-control-inner-background: "
+ controller.convertColorToHex(color));
// set the style on the label
setDoneStyle(done);
// if the item is first level, it has to show a course label
// (ComboBox), and it has to have a context menu
if(getTreeItem().getParent().equals(root)) {
// Before setting value, we need to temporarily disable the
// listener, otherwise it fires and goes unnecessarily updating
// the database, which takes a lot of time.
labelChangeListener.setBlock(true);
comboBox.setValue((homeworkTask.getLabel() != null) ? homeworkTask.getLabel() : "<null>");
labelChangeListener.setBlock(false);
// create a region to make sure that the ComboBox is aligned
// on the right
Region region = new Region();
HBox.setHgrow(region, Priority.ALWAYS);
cellBox.getChildren().addAll(checkBox, label, region, comboBox);
// set the context menu
setContextMenu(contextMenu);
setGraphic(cellBox);
setText(null);
} else {
setContextMenu(null); // disable the context menu on subtasks
cellBox.getChildren().addAll(checkBox, label);
setGraphic(cellBox);
setText(null);
}
}
}
/**
* set listener on the ComboBox to update the database when the
* selected index changes
*
* @param tree TreeView which the LabelCell is in, needed for updating
* the database
* @param day LocalDate which we need for updating the database
*/
private void setOnLabelChangeListener(TreeView<HomeworkTask> tree,
LocalDate day) {
InvalidationListener invalidationListener = observable -> {
controller.updateDatabase(day, controller
.convertTreeToArrayList(tree));
// We do not need to cleanup here, as no tasks
// were added or deleted.
};
// Pass the invalidationlistener on to the custom listener
labelChangeListener = new InvalidationListenerWithBlocker(invalidationListener);
// update label in database when selecting a different one
comboBox.getSelectionModel().selectedIndexProperty()
.addListener(labelChangeListener);
}
/**
* Sets a change listener on the CheckBox, to update the database on changes.
* @param tree The TreeView the current TreeCell is in. We need this to update the database.
* @param localDate The date of the TreeView, and thus all the HomeworkTasks, in which the CheckBox is toggled.
*/
void setOnDoneChangeListener(TreeView<HomeworkTask> tree, LocalDate localDate) {
ChangeListener<Boolean> changeListener =
(observable, oldValue, newValue) -> {
getTreeItem().getValue().setDone(newValue);
// set the style on the label
if(label != null) {
setDoneStyle(newValue);
}
// Deselect the item, otherwise the selector changes color and overrides the item color.
select(tree, () -> {});
/* If the item of which the checkbox is toggled is
* a subtask, then we check if all subtasks are done.
* If so, we mark its parent task as done.
*/
if(!getTreeItem().getParent().equals(root)) {
// the total number of subtasks of its parent
int totalSubtasks = getTreeItem().getParent()
.getChildren().size();
// the number of those tasks that are marked as done
int doneSubtasks = getDoneSubtasks(getTreeItem().getParent());
// if all the tasks are done, we mark the parent task
// as done
// This is a bit complicated by the idea that we always provide one more empty subtask to be edited.
// Which means that with more than one subtask, the total of done subtasks should be one less than the total.
// Border case: when there is only one subtask, it needs to be checked for the parent to be checked,
// so the amount of done subtasks needs to be at least one.
if((totalSubtasks == (doneSubtasks + 1)) && (doneSubtasks > 0)) {
// calling ...getparent().getValue().setDone(true)
// is not enough to trigger the event listener of
// the parent item
HomeworkTask parentOld = getTreeItem().getParent().getValue();
HomeworkTask parent = new
HomeworkTask(true,
parentOld.getText(),
parentOld.getLabel(),
parentOld.getColor(),
parentOld.getDatabaseID());
getTreeItem().getParent().setValue(parent);
}
}
controller.updateDatabase(localDate, controller
.convertTreeToArrayList(tree));
};
doneChangeListener = new ChangeListenerWithBlocker<Boolean>(changeListener);
checkBox.selectedProperty().addListener(doneChangeListener);
// checkBox.selectedProperty().addListener(
// (observable, oldValue, newValue) -> {
// getTreeItem().getValue().setDone(newValue);
// // set the style on the label
// if(label != null) {
// setDoneStyle(newValue);
// // Deselect the item, otherwise the selector changes color and overrides the item color.
// select(tree, () -> {});
// /* If the item of which the checkbox is toggled is
// * a subtask, then we check if all subtasks are done.
// * If so, we mark its parent task as done.
// */
// if(!getTreeItem().getParent().equals(root)) {
// // the total number of subtasks of its parent
// int totalSubtasks = getTreeItem().getParent()
// .getChildren().size();
// // the number of those tasks that are marked as done
// int doneSubtasks = getDoneSubtasks(getTreeItem().getParent());
// // if all the tasks are done, we mark the parent task
// // as done
// // This is a bit complicated by the idea that we always provide one more empty subtask to be edited.
// // Which means that with more than one subtask, the total of done subtasks should be one less than the total.
// // Border case: when there is only one subtask, it needs to be checked for the parent to be checked,
// // so the amount of done subtasks needs to be at least one.
// if((totalSubtasks == (doneSubtasks + 1)) && (doneSubtasks > 0)) {
// // calling ...getparent().getValue().setDone(true)
// // is not enough to trigger the event listener of
// // the parent item
// HomeworkTask parentOld = getTreeItem().getParent().getValue();
// HomeworkTask parent = new
// HomeworkTask(true,
// parentOld.getText(),
// parentOld.getLabel(),
// parentOld.getColor(),
// parentOld.getDatabaseID());
// getTreeItem().getParent().setValue(parent);
// controller.updateDatabase(localDate, controller
// .convertTreeToArrayList(tree));
}
/**
* Creates a context menu to be able to add a subtask, repeat a task, or
* change the colour of a task.
* @param tree The TreeView this TreeCell is a part of.
* @param day The day to which this TreeView (and thus TreeCell) belongs.
* @return The ContextMenu.
*/
ContextMenu createContextMenu(final TreeView<HomeworkTask> tree,
final LocalDate day) {
// create the context menu
ContextMenu contextMenu = new ContextMenu();
// MenuItem to add a subtask
MenuItem addSubTaskMenuItem = new MenuItem("Add subtask");
// MenuItem that holds a menu to choose for how long to repeat the task
Menu repeatTasksMenu = makeRepeatMenu(this, day);
// a separator; a horizontal line
SeparatorMenuItem separatorMenuItem = new SeparatorMenuItem();
// the different colours to be added
MenuItem firstColor = new MenuItem("Green");
MenuItem secondColor = new MenuItem("Blue");
MenuItem thirdColor = new MenuItem("Red");
MenuItem defaultColor = new MenuItem("White");
// add all the items to the context menu
contextMenu.getItems()
.addAll(addSubTaskMenuItem, repeatTasksMenu, separatorMenuItem,
firstColor, secondColor, thirdColor, defaultColor);
addSubTaskMenuItem.setOnAction(event -> createSubTask(getTreeItem()));
// sets an action on all the colour items
for (int i = 2; i < contextMenu.getItems().size(); i++) {
MenuItem colorMenuItem = contextMenu.getItems().get(i);
colorMenuItem.setOnAction(event1 -> {
controller.setBackgroundColor(colorMenuItem.getText(), this);
controller.updateDatabase(day, controller
.convertTreeToArrayList(tree));
controller.cleanUp(tree);
});
}
return contextMenu;
}
/**
* Creates an empty subtask, a child, of the parentItem.
* @param parentItem The item to create a subtask in/under.
*/
private void createSubTask(TreeItem parentItem) {
// add a new subtask
TreeItem<HomeworkTask> emptyItem = new TreeItem<>(
new HomeworkTask());
parentItem.getChildren().add(emptyItem);
// select the new subtask
getTreeView().getSelectionModel().select(emptyItem);
// get the index of the new subtask
int index = getTreeView().getSelectionModel().getSelectedIndex();
// layout the TreeView again (otherwise we can't directly
// edit an item)
getTreeView().layout();
// create a new TreeItem from the selected index, we need this
// to do this to be able to edit it (pointer to emptyItem
// is lost?)
TreeItem<HomeworkTask> item = getTreeView().getTreeItem(index);
// finnaly we can edit!
getTreeView().edit(item);
}
/**
* Creates the Menu to be able to choose for how long to repeat a task.
* See {@link #createContextMenu}.
* @param customTreeCell The TreeCell to show the context menu on.
* @param day The day the TreeCell is in, to be able to calculate on what
* other days the task will have to be placed.
* @return A drop down Menu.
*/
private Menu makeRepeatMenu(CustomTreeCell customTreeCell, LocalDate day) {
Menu repeatTasksMenu = new Menu("Repeat for x weeks");
for (int i = 1; i < 9; i++) {
MenuItem menuItem = new MenuItem(String.valueOf(i));
repeatTasksMenu.getItems().add(menuItem);
}
List<MenuItem> repeatMenuItems = repeatTasksMenu.getItems();
for (MenuItem repeatMenuItem : repeatMenuItems) {
repeatMenuItem.setOnAction(event12 -> {
int repeatNumber = Integer.valueOf(repeatMenuItem.getText());
HomeworkTask homeworkTaskToRepeat = customTreeCell.getItem();
repeatTask(repeatNumber, homeworkTaskToRepeat, day);
});
}
return repeatTasksMenu;
}
/**
* Repeats a task for a number of weeks.
* @param repeatNumber The number of weeks to repeat the task.
* @param homeworkTask The HomeworkTask to be repeated.
* @param day The current day, to be able to calculate on what days to
* add the task.
*/
private void repeatTask(final int repeatNumber, final HomeworkTask homeworkTask, LocalDate day) {
for (int i = 0; i < repeatNumber; i++) {
// add one week to the day to put the task there
LocalDate newDay = day.plusWeeks(1);
// copy the task and its subtasks to the new day in the database
Database.INSTANCE.copyAndInsertTask(newDay, homeworkTask);
}
// refresh the console to see the newly copied tasks
controller.refreshAllDays();
}
/**
* Sets the style of the text of a task, depending on whether the task
* is done or not.
*
* @param done boolean, true if the task is done, false if not done.
*/
private void setDoneStyle(boolean done) {
String color = getItem().getColor();
if(done) {
label.getStyleClass().remove("label");
// Remove the white text of the combobox, which we set earlier when the background color is dark.
comboBox.getStyleClass().remove("combobox-text-white");
// Dark colors need a light text.
switch (color) {
case "Red":
case "Blue": // and item is selected
label.getStyleClass().add("label-done-light");
comboBox.getStyleClass().add("combobox-done-light");
break;
case "Green":
label.getStyleClass().add("label-done-dark");
comboBox.getStyleClass().add("combobox-done-dark");
break;
default:
label.getStyleClass().add("label-done");
comboBox.getStyleClass().add("combobox-done");
break;
}
} else {
// Remove all the classes which styled the 'done' style on the item.
label.getStyleClass().removeAll("label-done", "label-done-light", "label-done-dark");
label.getStyleClass().add("label");
comboBox.getStyleClass().removeAll("combobox-done", "combobox-done-light", "combobox-done-dark");
// Re-add white text for dark backgrounds.
setWhiteComboboxText();
}
}
/**
* Useful for dark background colors.
*/
private void setWhiteComboboxText() {
String color = getItem().getColor();
if (color.equals("Red")) {
comboBox.getStyleClass().add("combobox-text-white");
} else {
comboBox.getStyleClass().remove("combobox-text-white");
}
}
/**
* Counts the number of subtasks of taskTreeItem that are marked as done.
*
* @param taskTreeItem The TreeItem<HomeworkTask> of which to count the
* done subtasks.
* @return int, the number of subtasks that are marked as done.
*/
private int getDoneSubtasks(TreeItem<HomeworkTask> taskTreeItem) {
List<TreeItem<HomeworkTask>> subtasks = taskTreeItem.getChildren();
int count = 0;
for (TreeItem<HomeworkTask> subtask : subtasks) {
if (subtask.getValue().getDone()) {
count++;
}
}
return count;
}
/**
* When the dragging is detected, we place the content of the LabelCell
* in the DragBoard.
*/
void setOnDragDetected() {
setOnDragDetected(event -> {
boolean isParentTask = getTreeItem().getParent().equals(root);
boolean isEmpty = getTreeItem().getValue().getText().equals("");
if (!isEmpty && isParentTask) {
Dragboard db = startDragAndDrop(TransferMode.MOVE);
ClipboardContent content = new ClipboardContent();
content.put(controller.DATA_FORMAT, getTreeItem()
.getValue());
db.setContent(content);
}
event.consume();
});
}
/**
* Sets on drag over.
*/
void setOnDragOver() {
setOnDragOver(event -> {
if (!Objects.equals(event.getGestureSource(), this) && event
.getDragboard().hasContent(controller.DATA_FORMAT)) {
event.acceptTransferModes(TransferMode.MOVE);
}
event.consume();
});
}
/**
* Sets on drag entered.
* @param tree TreeView to style as focused.
*/
void setOnDragEntered(TreeView<HomeworkTask> tree) {
setOnDragEntered(event -> {
if ((!Objects.equals(event.getGestureSource(), this)) && event
.getDragboard().hasContent(controller.DATA_FORMAT)) {
tree.setStyle("-fx-background-color: -fx-accent;");
}
event.consume();
});
}
/**
* Sets on drag exited.
* @param tree TreeView to style as not focused.
*/
void setOnDragExited(TreeView<HomeworkTask> tree) {
setOnDragExited(event -> {
tree.setStyle("-fx-background-color: -fx-base;");
event.consume();
});
}
/**
* updates the ListView and database when a CustomTreeCell is being dropped
*
* @param tree TreeView needed for updating the database
* @param day LocalDate needed for updating the database
*/
void setOnDragDropped(final TreeView<HomeworkTask> tree, final LocalDate day) {
setOnDragDropped(event -> {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasContent(controller.DATA_FORMAT)) {
HomeworkTask newHomeworkTask
= (HomeworkTask)db.getContent(controller.DATA_FORMAT);
//insert new task, removing will happen in onDragDone
int index = min(getIndex(), tree.getRoot().getChildren()
.size()); // item can be dropped way below
// the existing list
//we have put an empty item instead of no items
//because otherwise there are no treeCells that can
// receive an item
if (tree.getRoot().getChildren().get(index).getValue().getText().equals("")) {
tree.getRoot().getChildren().get(index)
.setValue(newHomeworkTask); //replace empty item
} else {
TreeItem<HomeworkTask> item = new TreeItem<>(newHomeworkTask);
tree.getRoot().getChildren().add(index, item);
}
success = true;
// update tasks in database (old day?)
controller.updateParentDatabase(day,
controller.getParentTasks(
controller.convertTreeToArrayList(tree)
)
);
// Clear selection on all other items immediately. This will result in a smooth reaction, whereas otherwise it takes a bit of noticable time before selection of the just-dragged item (on its previous location) is cleared.
select(tree,
() -> {}
);
}
event.setDropCompleted(success);
event.consume();
// clean up immediately for a smooth reaction
controller.cleanUp(tree);
// works to let the subtasks show up after the drag, except when dragging a task with subtasks in the same list...
controller.refreshAllDays();
});
}
/**
* removing the original copy
*
* @param tree TreeView needed for updating the database
* @param day LocalDate needed for updating the database
*/
void setOnDragDone(final TreeView<HomeworkTask> tree, final LocalDate day) {
setOnDragDone(event -> {
//ensures the original element is only removed on a
// valid copy transfer (no dropping outside listviews)
if (event.getTransferMode() == TransferMode.MOVE) {
Dragboard db = event.getDragboard();
HomeworkTask newHomeworkTask
= (HomeworkTask)db.getContent(controller.DATA_FORMAT);
HomeworkTask emptyHomeworkTask = new HomeworkTask();
//remove original item
//item can have been moved up (so index becomes one
// too much)
// or such that the index didn't change, like to
// another day
// If item was moved to an other day, or down in same list
TreeItem<HomeworkTask> currentItem = tree.getRoot().getChildren().get(getIndex());
String currentText = currentItem.getValue().getText();
// if text at current location is equal to
String newText = newHomeworkTask.getText();
if (currentText.equals(newText)) {
tree.getRoot().getChildren().get(getIndex())
.setValue(emptyHomeworkTask);
setGraphic(null);
// deleting blank row from database which updating creates
} else { // item was moved up in same tree
// we never get here...
int index = getIndex() + 1;
tree.getRoot().getChildren().get(index)
.setValue(emptyHomeworkTask);
}
// update in database (new day?)
controller.updateParentDatabase(day,
controller.getParentTasks(
controller.convertTreeToArrayList(tree)
)
);
}
event.consume();
// clean up immediately for a smooth reaction
controller.cleanUp(tree);
});
}
}
|
package cpw.mods.fml.client;
import java.awt.Dimension;
import java.util.ArrayList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.FontRenderer;
import net.minecraft.client.GuiButton;
import net.minecraft.client.GuiScreen;
import net.minecraft.client.GuiSmallButton;
import net.minecraft.shared.StringTranslate;
import net.minecraft.client.Tessellator;
import org.lwjgl.opengl.GL11;
import com.google.common.base.Strings;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
/**
* @author cpw
*
*/
public class GuiModList extends GuiScreen
{
private GuiScreen mainMenu;
private GuiSlotModList modList;
private int selected = -1;
private ModContainer selectedMod;
private int listWidth;
private ArrayList<ModContainer> mods;
/**
* @param mainMenu
*/
public GuiModList(GuiScreen mainMenu)
{
this.mainMenu=mainMenu;
this.mods=new ArrayList<ModContainer>();
FMLClientHandler.instance().addSpecialModEntries(mods);
for (ModContainer mod : Loader.instance().getModList()) {
if (mod.getMetadata()!=null && mod.getMetadata().parentMod==null && !Strings.isNullOrEmpty(mod.getMetadata().parent)) {
String parentMod = mod.getMetadata().parent;
ModContainer parentContainer = Loader.instance().getIndexedModList().get(parentMod);
if (parentContainer != null)
{
mod.getMetadata().parentMod = parentContainer;
parentContainer.getMetadata().childMods.add(mod);
continue;
}
}
else if (mod.getMetadata()!=null && mod.getMetadata().parentMod!=null)
{
continue;
}
mods.add(mod);
}
}
@Override
public void func_73866_w_()
{
for (ModContainer mod : mods) {
listWidth=Math.max(listWidth,getFontRenderer().func_78256_a(mod.getName()) + 10);
listWidth=Math.max(listWidth,getFontRenderer().func_78256_a(mod.getVersion()) + 10);
}
listWidth=Math.min(listWidth, 150);
StringTranslate translations = StringTranslate.func_74808_a();
this.field_73887_h.add(new GuiSmallButton(6, this.field_73880_f / 2 - 75, this.field_73881_g - 38, translations.func_74805_b("gui.done")));
this.modList=new GuiSlotModList(this, mods, listWidth);
this.modList.registerScrollButtons(this.field_73887_h, 7, 8);
}
@Override
protected void func_73875_a(GuiButton button) {
if (button.field_73742_g)
{
switch (button.field_73741_f)
{
case 6:
this.field_73882_e.func_71373_a(this.mainMenu);
return;
}
}
super.func_73875_a(button);
}
public int drawLine(String line, int offset, int shifty)
{
this.field_73886_k.func_78276_b(line, offset, shifty, 0xd7edea);
return shifty + 10;
}
@Override
public void func_73863_a(int p_571_1_, int p_571_2_, float p_571_3_)
{
this.modList.drawScreen(p_571_1_, p_571_2_, p_571_3_);
this.func_73732_a(this.field_73886_k, "Mod List", this.field_73880_f / 2, 16, 0xFFFFFF);
int offset = this.listWidth + 20;
if (selectedMod != null) {
GL11.glEnable(GL11.GL_BLEND);
if (!selectedMod.getMetadata().autogenerated) {
int shifty = 35;
if (!selectedMod.getMetadata().logoFile.isEmpty())
{
int texture = this.field_73882_e.field_71446_o.func_78341_b(selectedMod.getMetadata().logoFile);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.field_73882_e.field_71446_o.func_78342_b(texture);
Dimension dim = TextureFXManager.instance().getTextureDimensions(texture);
int top = 32;
Tessellator tess = Tessellator.field_78398_a;
tess.func_78382_b();
tess.func_78374_a(offset, top + dim.height, field_73735_i, 0, 1);
tess.func_78374_a(offset + dim.width, top + dim.height, field_73735_i, 1, 1);
tess.func_78374_a(offset + dim.width, top, field_73735_i, 1, 0);
tess.func_78374_a(offset, top, field_73735_i, 0, 0);
tess.func_78381_a();
shifty += 65;
}
this.field_73886_k.func_78261_a(selectedMod.getMetadata().name, offset, shifty, 0xFFFFFF);
shifty += 12;
shifty = drawLine(String.format("Version: %s (%s)", selectedMod.getDisplayVersion(), selectedMod.getVersion()), offset, shifty);
shifty = drawLine(String.format("Mod ID: '%s' Mod State: %s", selectedMod.getModId(), Loader.instance().getModState(selectedMod)), offset, shifty);
if (!selectedMod.getMetadata().credits.isEmpty()) {
shifty = drawLine(String.format("Credits: %s", selectedMod.getMetadata().credits), offset, shifty);
}
shifty = drawLine(String.format("Authors: %s", selectedMod.getMetadata().getAuthorList()), offset, shifty);
shifty = drawLine(String.format("URL: %s", selectedMod.getMetadata().url), offset, shifty);
shifty = drawLine(selectedMod.getMetadata().childMods.isEmpty() ? "No child mods for this mod" : String.format("Child mods: %s", selectedMod.getMetadata().getChildModList()), offset, shifty);
this.getFontRenderer().func_78279_b(selectedMod.getMetadata().description, offset, shifty + 10, this.field_73880_f - offset - 20, 0xDDDDDD);
} else {
offset = ( this.listWidth + this.field_73880_f ) / 2;
this.func_73732_a(this.field_73886_k, selectedMod.getName(), offset, 35, 0xFFFFFF);
this.func_73732_a(this.field_73886_k, String.format("Version: %s",selectedMod.getVersion()), offset, 45, 0xFFFFFF);
this.func_73732_a(this.field_73886_k, String.format("Mod State: %s",Loader.instance().getModState(selectedMod)), offset, 55, 0xFFFFFF);
this.func_73732_a(this.field_73886_k, "No mod information found", offset, 65, 0xDDDDDD);
this.func_73732_a(this.field_73886_k, "Ask your mod author to provide a mod mcmod.info file", offset, 75, 0xDDDDDD);
}
GL11.glDisable(GL11.GL_BLEND);
}
super.func_73863_a(p_571_1_, p_571_2_, p_571_3_);
}
Minecraft getMinecraftInstance() {
return field_73882_e;
}
FontRenderer getFontRenderer() {
return field_73886_k;
}
/**
* @param var1
*/
public void selectModIndex(int var1)
{
this.selected=var1;
if (var1>=0 && var1<=mods.size()) {
this.selectedMod=mods.get(selected);
} else {
this.selectedMod=null;
}
}
public boolean modIndexSelected(int var1)
{
return var1==selected;
}
}
|
package org.commcare.tasks;
import android.content.Context;
import android.content.Intent;
import android.support.v4.util.Pair;
import net.sqlcipher.database.SQLiteDatabase;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.conn.ConnectTimeoutException;
import org.commcare.CommCareApplication;
import org.commcare.android.database.app.models.UserKeyRecord;
import org.commcare.android.database.user.models.ACase;
import org.commcare.data.xml.DataModelPullParser;
import org.commcare.engine.cases.CaseUtils;
import org.commcare.interfaces.HttpRequestEndpoints;
import org.commcare.logging.AndroidLogger;
import org.commcare.logging.analytics.GoogleAnalyticsFields;
import org.commcare.models.database.SqlStorage;
import org.commcare.models.encryption.ByteEncrypter;
import org.commcare.models.encryption.CryptUtil;
import org.commcare.modern.models.RecordTooLargeException;
import org.commcare.network.DataPullRequester;
import org.commcare.network.RemoteDataPullResponse;
import org.commcare.preferences.CommCarePreferences;
import org.commcare.resources.model.CommCareOTARestoreListener;
import org.commcare.services.CommCareSessionService;
import org.commcare.tasks.templates.CommCareTask;
import org.commcare.utils.FormSaveUtil;
import org.commcare.utils.SessionUnavailableException;
import org.commcare.utils.bitcache.BitCache;
import org.commcare.xml.AndroidTransactionParserFactory;
import org.javarosa.core.model.User;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.storage.StorageFullException;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.xml.util.ActionableInvalidStructureException;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import javax.crypto.SecretKey;
/**
* @author ctsims
*/
public abstract class DataPullTask<R>
extends CommCareTask<Void, Integer, ResultAndError<DataPullTask.PullTaskResult>, R>
implements CommCareOTARestoreListener {
private final String server;
private final String username;
private final String password;
private final Context context;
private int mCurrentProgress;
private int mTotalItems;
private long mSyncStartTime;
private boolean wasKeyLoggedIn;
public static final int DATA_PULL_TASK_ID = 10;
public static final int PROGRESS_STARTED = 0;
public static final int PROGRESS_CLEANED = 1;
public static final int PROGRESS_AUTHED = 2;
private static final int PROGRESS_DONE = 4;
public static final int PROGRESS_RECOVERY_NEEDED = 8;
public static final int PROGRESS_RECOVERY_STARTED = 16;
private static final int PROGRESS_RECOVERY_FAIL_SAFE = 32;
private static final int PROGRESS_RECOVERY_FAIL_BAD = 64;
public static final int PROGRESS_PROCESSING = 128;
public static final int PROGRESS_DOWNLOADING = 256;
public static final int PROGRESS_DOWNLOADING_COMPLETE = 512;
private DataPullRequester dataPullRequester;
private boolean loginNeeded;
private UserKeyRecord ukrForLogin;
public DataPullTask(String username, String password,
String server, Context context, DataPullRequester dataPullRequester) {
this.server = server;
this.username = username;
this.password = password;
this.context = context;
this.taskId = DATA_PULL_TASK_ID;
this.dataPullRequester = dataPullRequester;
this.requestor = dataPullRequester.getHttpGenerator(username, password);
TAG = DataPullTask.class.getSimpleName();
}
public DataPullTask(String username, String password,
String server, Context context) {
this(username, password, server, context, CommCareApplication._().getDataPullRequester());
}
// TODO PLM: once this task is refactored into manageable components, it should use the
// ManagedAsyncTask pattern of checking for isCancelled() and aborting at safe places.
@Override
protected void onCancelled() {
super.onCancelled();
if (wasKeyLoggedIn) {
CommCareApplication._().releaseUserResourcesAndServices();
}
}
private HttpRequestEndpoints requestor;
@Override
protected ResultAndError<PullTaskResult> doTaskBackground(Void... params) {
if (!CommCareSessionService.sessionAliveLock.tryLock()) {
// Don't try to sync if logging out is occurring
return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE,
"Cannot sync while a logout is in process");
}
try {
return doTaskBackgroundHelper();
} finally {
CommCareSessionService.sessionAliveLock.unlock();
}
}
private ResultAndError<PullTaskResult> doTaskBackgroundHelper() {
publishProgress(PROGRESS_STARTED);
recordSyncAttemptTime();
Logger.log(AndroidLogger.TYPE_USER, "Starting Sync");
setLoginNeeded();
AndroidTransactionParserFactory factory = getTransactionParserFactory();
byte[] wrappedEncryptionKey = getEncryptionKey();
if (wrappedEncryptionKey == null) {
this.publishProgress(PROGRESS_DONE);
return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE,
"Unable to generate encryption key");
} else {
factory.initUserParser(wrappedEncryptionKey);
}
if (isCancelled()) {
// Avoid making http request if user cancelled the task (NOTE: In this case, the result
// returned is never processed since cancelled task results are sent to onCancelled.
return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE, "");
}
PullTaskResult responseError = PullTaskResult.UNKNOWN_FAILURE;
try {
ResultAndError<PullTaskResult> resultFromRequest = makeRequestAndHandleResponse(factory);
if (resultFromRequest != null) {
return resultFromRequest;
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Timed out listening to receive data during sync");
responseError = PullTaskResult.CONNECTION_TIMEOUT;
} catch (ConnectTimeoutException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Timed out listening to receive data during sync");
responseError = PullTaskResult.CONNECTION_TIMEOUT;
} catch (ClientProtocolException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Couldn't sync due network error|" + e.getMessage());
} catch (UnknownHostException e) {
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Couldn't sync due to bad network");
responseError = PullTaskResult.UNREACHABLE_HOST;
} catch (IOException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Couldn't sync due to IO Error|" + e.getMessage());
}
if (loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
this.publishProgress(PROGRESS_DONE);
return new ResultAndError<>(responseError);
}
private void setLoginNeeded() {
try {
loginNeeded = !CommCareApplication._().getSession().isActive();
} catch (SessionUnavailableException sue) {
//expected if we aren't initialized.
loginNeeded = true;
}
}
private AndroidTransactionParserFactory getTransactionParserFactory() {
return new AndroidTransactionParserFactory(context, requestor) {
boolean publishedAuth = false;
@Override
public void reportProgress(int progress) {
if (!publishedAuth) {
DataPullTask.this.publishProgress(PROGRESS_AUTHED, progress);
publishedAuth = true;
}
}
};
}
private byte[] getEncryptionKey() {
byte[] key;
if (loginNeeded) {
initUKRForLogin();
if (ukrForLogin == null) {
return null;
}
key = ByteEncrypter.wrapByteArrayWithString(ukrForLogin.getEncryptedKey(), password);
} else {
//Only purge cases if we already had a logged in user. Otherwise we probably can't read the DB.
CaseUtils.purgeCases();
key = CommCareApplication._().getSession().getLoggedInUser().getWrappedKey();
}
this.publishProgress(PROGRESS_CLEANED); // Either way, we don't want to do this step again
return key;
}
private void initUKRForLogin() {
if (shouldGenerateFirstKey()) {
SecretKey newKey = CryptUtil.generateSemiRandomKey();
if (newKey == null) {
return;
}
String sandboxId = PropertyUtils.genUUID().replace("-", "");
ukrForLogin = new UserKeyRecord(username, UserKeyRecord.generatePwdHash(password),
ByteEncrypter.wrapByteArrayWithString(newKey.getEncoded(), password),
new Date(), new Date(Long.MAX_VALUE), sandboxId);
} else {
ukrForLogin = UserKeyRecord.getCurrentValidRecordByPassword(CommCareApplication._().getCurrentApp(), username, password, true);
if (ukrForLogin == null) {
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Shouldn't be able to not have a valid key record when OTA restoring with a key server");
}
}
}
private static boolean shouldGenerateFirstKey() {
String keyServer = CommCarePreferences.getKeyServer();
return keyServer == null || keyServer.equals("");
}
/*
* @return the proper result, or null if we have not yet been able to determine the result to
* return
* @throws IOException
*/
private ResultAndError<PullTaskResult> makeRequestAndHandleResponse(AndroidTransactionParserFactory factory)
throws IOException {
RemoteDataPullResponse pullResponse = dataPullRequester.makeDataPullRequest(this, requestor, server, !loginNeeded);
Logger.log(AndroidLogger.TYPE_USER, "Request opened. Response code: " + pullResponse.responseCode);
if (pullResponse.responseCode == 401) {
return handleAuthFailed();
} else if (pullResponse.responseCode >= 200 && pullResponse.responseCode < 300) {
return handleSuccessResponseCode(pullResponse, factory);
} else if (pullResponse.responseCode == 412) {
return handleBadLocalState(factory);
} else if (pullResponse.responseCode == 500) {
return handleServerError();
}
return null;
}
private ResultAndError<PullTaskResult> handleAuthFailed() {
//If we logged in, we need to drop those credentials
if (loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
Logger.log(AndroidLogger.TYPE_USER, "Bad Auth Request for user!|" + username);
return new ResultAndError<>(PullTaskResult.AUTH_FAILED);
}
/**
* @return the proper result, or null if we have not yet been able to determine the result to
* return
* @throws IOException
*/
private ResultAndError<PullTaskResult> handleSuccessResponseCode(
RemoteDataPullResponse pullResponse, AndroidTransactionParserFactory factory)
throws IOException {
handleLoginNeededOnSuccess();
this.publishProgress(PROGRESS_AUTHED, 0);
if (isCancelled()) {
// About to enter data commit phase; last chance to finish early if cancelled.
return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE, "");
}
this.publishProgress(PROGRESS_DOWNLOADING_COMPLETE, 0);
Logger.log(AndroidLogger.TYPE_USER, "Remote Auth Successful|" + username);
try {
BitCache cache = pullResponse.writeResponseToCache(context);
String syncToken = readInput(cache.retrieveCache(), factory);
updateUserSyncToken(syncToken);
onSuccessfulSync();
return new ResultAndError<>(PullTaskResult.DOWNLOAD_SUCCESS);
} catch (XmlPullParserException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_USER, "User Sync failed due to bad payload|" + e.getMessage());
return new ResultAndError<>(PullTaskResult.BAD_DATA, e.getMessage());
} catch (ActionableInvalidStructureException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_USER, "User Sync failed due to bad payload|" + e.getMessage());
return new ResultAndError<>(PullTaskResult.BAD_DATA_REQUIRES_INTERVENTION, e.getLocalizedMessage());
} catch (InvalidStructureException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_USER, "User Sync failed due to bad payload|" + e.getMessage());
return new ResultAndError<>(PullTaskResult.BAD_DATA, e.getMessage());
} catch (UnfullfilledRequirementsException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "User sync failed oddly, unfulfilled reqs |" + e.getMessage());
return null;
} catch (IllegalStateException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "User sync failed oddly, ISE |" + e.getMessage());
return null;
} catch (RecordTooLargeException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Storage Full during user sync |" + e.getMessage());
return new ResultAndError<>(PullTaskResult.STORAGE_FULL);
}
}
private void handleLoginNeededOnSuccess() {
if (loginNeeded) {
// This is currently necessary to make sure that data is encoded, but there is
// probably a better way to do it
CommCareApplication._().startUserSession(
ByteEncrypter.unwrapByteArrayWithString(ukrForLogin.getEncryptedKey(), password),
ukrForLogin, false);
wasKeyLoggedIn = true;
}
}
/**
* @return the proper result, or null if we have not yet been able to determine the result to
* return
* @throws IOException
*/
private ResultAndError<PullTaskResult> handleBadLocalState(AndroidTransactionParserFactory factory) {
Pair<Integer, String> returnCodeAndMessage = recover(requestor, factory);
int returnCode = returnCodeAndMessage.first;
String failureReason = returnCodeAndMessage.second;
if (returnCode == PROGRESS_DONE) {
// Recovery was successful
onSuccessfulSync();
return new ResultAndError<>(PullTaskResult.DOWNLOAD_SUCCESS);
} else if (returnCode == PROGRESS_RECOVERY_FAIL_SAFE || returnCode == PROGRESS_RECOVERY_FAIL_BAD) {
// wipe our login if one happened
if (loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
this.publishProgress(PROGRESS_DONE);
return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE, failureReason);
} else {
if (loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
return null;
}
}
private void onSuccessfulSync() {
recordSuccessfulSyncTime();
Intent i = new Intent("org.commcare.dalvik.api.action.data.update");
this.context.sendBroadcast(i);
if (loginNeeded) {
CommCareApplication._().getAppStorage(UserKeyRecord.class).write(ukrForLogin);
}
Logger.log(AndroidLogger.TYPE_USER, "User Sync Successful|" + username);
updateCurrentUser(password);
this.publishProgress(PROGRESS_DONE);
}
private ResultAndError<PullTaskResult> handleServerError() {
if (loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
Logger.log(AndroidLogger.TYPE_USER, "500 Server Error|" + username);
return new ResultAndError<>(PullTaskResult.SERVER_ERROR, "");
}
@Override
public void tryAbort() {
if (requestor != null) {
requestor.abortCurrentRequest();
}
}
private static void recordSyncAttemptTime() {
//TODO: This should be per _user_, not per app
CommCareApplication._().getCurrentApp().getAppPreferences().edit()
.putLong("last-ota-restore", new Date().getTime()).commit();
}
private static void recordSuccessfulSyncTime() {
CommCareApplication._().getCurrentApp().getAppPreferences().edit()
.putLong("last-succesful-sync", new Date().getTime()).commit();
}
//TODO: This and the normal sync share a ton of code. It's hard to really... figure out the right way to
private Pair<Integer, String> recover(HttpRequestEndpoints requestor, AndroidTransactionParserFactory factory) {
this.publishProgress(PROGRESS_RECOVERY_NEEDED);
Logger.log(AndroidLogger.TYPE_USER, "Sync Recovery Triggered");
BitCache cache;
//This chunk is the safe field of operations which can all fail in IO in such a way that we can
//just report back that things didn't work and don't need to attempt any recovery or additional
//work
try {
// Make a new request without all of the flags
RemoteDataPullResponse pullResponse = dataPullRequester.makeDataPullRequest(this, requestor, server, false);
//We basically only care about a positive response, here. Anything else would have been caught by the other request.
if (!(pullResponse.responseCode >= 200 && pullResponse.responseCode < 300)) {
return new Pair<>(PROGRESS_RECOVERY_FAIL_SAFE, "");
}
//Grab a cache. The plan is to download the incoming data, wipe (move) the existing db, and then
//restore fresh from the downloaded file
cache = pullResponse.writeResponseToCache(context);
} catch (IOException e) {
e.printStackTrace();
//Ok, well, we're bailing here, but we didn't make any changes
Logger.log(AndroidLogger.TYPE_USER, "Sync Recovery Failed due to IOException|" + e.getMessage());
return new Pair<>(PROGRESS_RECOVERY_FAIL_SAFE, "");
}
this.publishProgress(PROGRESS_RECOVERY_STARTED);
Logger.log(AndroidLogger.TYPE_USER, "Sync Recovery payload downloaded");
//Ok. Here's where things get real. We now have a stable copy of the fresh data from the
//server, so it's "safe" for us to wipe the casedb copy of it.
//CTS: We're not doing this in a super good way right now, need to be way more fault tolerant.
//this is the temporary implementation of everything past this point
//Wipe storage
//TODO: move table instead. Should be straightforward with sandboxed db's
CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class).removeAll();
String failureReason = "";
try {
//Get new data
String syncToken = readInput(cache.retrieveCache(), factory);
updateUserSyncToken(syncToken);
Logger.log(AndroidLogger.TYPE_USER, "Sync Recovery Succesful");
return new Pair<>(PROGRESS_DONE, "");
} catch (ActionableInvalidStructureException e) {
e.printStackTrace();
failureReason = e.getLocalizedMessage();
} catch (InvalidStructureException | XmlPullParserException
| UnfullfilledRequirementsException | StorageFullException
| SessionUnavailableException | IOException e) {
e.printStackTrace();
failureReason = e.getMessage();
} finally {
//destroy temp file
cache.release();
}
//OK, so we would have returned success by now if things had worked out, which means that instead we got an error
//while trying to parse everything out. We need to recover from that error here and rollback the changes
//TODO: Roll back changes
Logger.log(AndroidLogger.TYPE_USER, "Sync recovery failed|" + failureReason);
return new Pair<>(PROGRESS_RECOVERY_FAIL_BAD, failureReason);
}
private void updateCurrentUser(String password) {
SqlStorage<User> storage = CommCareApplication._().getUserStorage("USER", User.class);
User u = storage.getRecordForValue(User.META_USERNAME, username);
CommCareApplication._().getSession().setCurrentUser(u, password);
}
private void updateUserSyncToken(String syncToken) throws StorageFullException {
SqlStorage<User> storage = CommCareApplication._().getUserStorage("USER", User.class);
try {
User u = storage.getRecordForValue(User.META_USERNAME, username);
u.setLastSyncToken(syncToken);
storage.write(u);
} catch (NoSuchElementException nsee) {
//TODO: Something here? Maybe figure out if we downloaded a user from the server and attach the data to it?
}
}
private String readInput(InputStream stream, AndroidTransactionParserFactory factory)
throws InvalidStructureException, IOException, XmlPullParserException,
UnfullfilledRequirementsException {
DataModelPullParser parser;
factory.initCaseParser();
factory.initStockParser();
Hashtable<String, String> formNamespaces = FormSaveUtil.getNamespaceToFilePathMap(context);
factory.initFormInstanceParser(formNamespaces);
//this is _really_ coupled, but we'll tolerate it for now because of the absurd performance gains
SQLiteDatabase db = CommCareApplication._().getUserDbHandle();
try {
db.beginTransaction();
parser = new DataModelPullParser(stream, factory, true, false, this);
parser.parse();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
//Return the sync token ID
return factory.getSyncToken();
}
//BEGIN - OTA Listener methods below - Note that most of the methods
//below weren't really implemented
@Override
public void onUpdate(int numberCompleted) {
mCurrentProgress = numberCompleted;
int millisecondsElapsed = (int)(System.currentTimeMillis() - mSyncStartTime);
this.publishProgress(PROGRESS_PROCESSING, mCurrentProgress, mTotalItems, millisecondsElapsed);
}
@Override
public void setTotalForms(int totalItemCount) {
mTotalItems = totalItemCount;
mCurrentProgress = 0;
mSyncStartTime = System.currentTimeMillis();
this.publishProgress(PROGRESS_PROCESSING, mCurrentProgress, mTotalItems, 0);
}
@Override
public void statusUpdate(int statusNumber) {
}
@Override
public void refreshView() {
}
@Override
public void getCredentials() {
}
@Override
public void promptRetry(String msg) {
}
@Override
public void onSuccess() {
}
@Override
public void onFailure(String failMessage) {
}
public void reportDownloadProgress(int totalRead) {
publishProgress(DataPullTask.PROGRESS_DOWNLOADING, totalRead);
}
public enum PullTaskResult {
DOWNLOAD_SUCCESS(-1),
AUTH_FAILED(GoogleAnalyticsFields.VALUE_AUTH_FAILED),
BAD_DATA(GoogleAnalyticsFields.VALUE_BAD_DATA),
BAD_DATA_REQUIRES_INTERVENTION(GoogleAnalyticsFields.VALUE_BAD_DATA_REQUIRES_INTERVENTION),
UNKNOWN_FAILURE(GoogleAnalyticsFields.VALUE_UNKNOWN_FAILURE),
UNREACHABLE_HOST(GoogleAnalyticsFields.VALUE_UNREACHABLE_HOST),
CONNECTION_TIMEOUT(GoogleAnalyticsFields.VALUE_CONNECTION_TIMEOUT),
SERVER_ERROR(GoogleAnalyticsFields.VALUE_SERVER_ERROR),
STORAGE_FULL(GoogleAnalyticsFields.VALUE_STORAGE_FULL);
private final int googleAnalyticsValue;
PullTaskResult(int googleAnalyticsValue) {
this.googleAnalyticsValue = googleAnalyticsValue;
}
public int getCorrespondingGoogleAnalyticsValue() {
return googleAnalyticsValue;
}
public String getCorrespondingGoogleAnalyticsLabel() {
if (this == DOWNLOAD_SUCCESS) {
return GoogleAnalyticsFields.LABEL_SYNC_SUCCESS;
} else {
return GoogleAnalyticsFields.LABEL_SYNC_FAILURE;
}
}
}
}
|
package com.spun.util.date;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.spun.util.DateUtils;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.approvaltests.Approvals;
import org.approvaltests.utils.WithTimeZone;
import org.junit.jupiter.api.Test;
import org.lambda.query.Query;
public class DateRangeTest
{
@Test
public void testIsIn() {
DateRange range = new DateRange(date(40), date(20));
assertTrue(range.contains(date(40)));
assertTrue(range.contains(date(30)));
assertFalse(range.contains(date(20)));
assertFalse(range.contains(date(10)));
}
@Test
public void testFilter() {
DateRange range = new DateRange(quickDate(20), quickDate(40));
Timestamp dates[] = {quickDate(50), quickDate(40), quickDate(30), quickDate(20), quickDate(10)};
Approvals.verifyAll("Dates", Query.where(dates, d -> range.contains(d)));
}
public static Timestamp quickDate(int daysPastNewYears)
{
Timestamp start = DateUtils.parse("2001/01/01");
Calendar calendar = DateUtils.asCalendar(start);
calendar.add(GregorianCalendar.DAY_OF_YEAR, daysPastNewYears);
return DateUtils.asTimestamp(calendar.getTime());
}
public static Timestamp date(int daysAgo)
{
return DateUtils.getStartOfXDaysAgo(daysAgo);
}
@Test
public void testGetWeeks() {
DateRange d = new DateRange(DateUtils.parse("2008/10/01"), DateUtils.parse("2008/11/01"));
Approvals.verifyAll("week", d.getWeeks());
}
@Test
public void testContainsDayOfWeek() {
DateRange d = new DateRange(DateUtils.parse("2008/11/11"), DateUtils.parse("2008/11/15"));
assertTrue(d.containsDayOfWeek(Calendar.THURSDAY));
assertFalse(d.containsDayOfWeek(Calendar.MONDAY));
}
@Test
public void testGetFirstDayOfWeek() {
DateRange d = new DateRange(DateUtils.parse("2008/11/11"), DateUtils.parse("2008/11/15"));
Date expected = new Date(DateUtils.parse("2008/11/13").getTime());
assertEquals(expected, d.getFirst(Calendar.THURSDAY));
}
@Test
public void testGetMonths() {
try (WithTimeZone tz = new WithTimeZone("UTC"))
{
DateRange d = new DateRange(DateUtils.parse("2008/01/01"), DateUtils.parse("2009/01/01"));
Approvals.verifyAll("months", d.getMonths());
}
}
@Test
public void testGetQuarters() {
DateRange d = new DateRange(DateUtils.parse("2008/01/01"), DateUtils.parse("2009/01/01"));
Approvals.verifyAll("months", d.getQuarters());
}
@Test
public void testGetRangeContaining() {
DateRange d = new DateRange(DateUtils.parse("2008/01/01"), DateUtils.parse("2009/01/01"));
DateRange containing = DateRange.getRangeContaining(d.getQuarters(), d.getMonths()[0]);
Approvals.verify(containing.toString());
}
}
|
package im.actor.messenger.app.view;
import android.content.Context;
import android.net.Uri;
import android.util.AttributeSet;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import java.io.File;
import im.actor.model.entity.Avatar;
import im.actor.model.entity.Contact;
import im.actor.model.entity.Dialog;
import im.actor.model.files.FileSystemReference;
import im.actor.model.viewmodel.FileVM;
import im.actor.model.viewmodel.FileVMCallback;
import im.actor.model.viewmodel.GroupVM;
import im.actor.model.viewmodel.UserVM;
import static im.actor.messenger.app.Core.messenger;
public class AvatarView extends SimpleDraweeView {
private FileVM bindedFile;
private int size;
private float placeholderTextSize;
private int currentId;
public AvatarView(Context context, GenericDraweeHierarchy hierarchy) {
super(context, hierarchy);
}
public AvatarView(Context context) {
super(context);
}
public AvatarView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AvatarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void init(int size, float placeholderTextSize) {
this.size = size;
this.placeholderTextSize = placeholderTextSize;
GenericDraweeHierarchyBuilder builder =
new GenericDraweeHierarchyBuilder(getResources());
GenericDraweeHierarchy hierarchy = builder
.setFadeDuration(200)
.setRoundingParams(new RoundingParams()
.setRoundAsCircle(true)
.setRoundingMethod(RoundingParams.RoundingMethod.BITMAP_ONLY))
// .setOverlay(new AvatarBorderDrawable())
.build();
setHierarchy(hierarchy);
}
public void bind(Dialog dialog) {
bind(dialog.getDialogAvatar(), dialog.getDialogTitle(), dialog.getPeer().getPeerId(), false);
}
public void bind(Contact contact) {
bind(contact.getAvatar(), contact.getName(), contact.getUid(), false);
}
public void bind(UserVM user, boolean forceNewTextSize) {
bind(user.getAvatar().get(), user.getName().get(), user.getId(), forceNewTextSize);
}
public void bind(GroupVM group) {
bind(group.getAvatar().get(), group.getName().get(), group.getId(), false);
}
public void bind(Avatar avatar, String title, int id, boolean forceNewTextSize) {
// Same avatar
if (currentId == id) {
return;
}
currentId = new Integer(id);
getHierarchy().setPlaceholderImage(new AvatarPlaceholderDrawable(title, id, placeholderTextSize, getContext(), forceNewTextSize));
if (bindedFile != null) {
bindedFile.detach();
bindedFile = null;
}
// Nothing to bind
if (avatar == null || avatar.getSmallImage() == null) {
setImageURI(null);
return;
}
bindedFile = messenger().bindFile(avatar.getSmallImage().getFileReference(), true, new FileVMCallback() {
@Override
public void onNotDownloaded() {
}
@Override
public void onDownloading(float progress) {
}
@Override
public void onDownloaded(FileSystemReference reference) {
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.fromFile(new File(reference.getDescriptor())))
.setResizeOptions(new ResizeOptions(size, size))
.build();
PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
.setOldController(getController())
.setImageRequest(request)
.build();
setController(controller);
}
});
}
public void bindRaw(String fileName) {
if (bindedFile != null) {
bindedFile.detach();
bindedFile = null;
}
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.fromFile(new File(fileName)))
.setResizeOptions(new ResizeOptions(size, size))
.setAutoRotateEnabled(true)
.build();
PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
.setOldController(getController())
.setImageRequest(request)
.build();
setController(controller);
}
public void unbind() {
if (bindedFile != null) {
bindedFile.detach();
bindedFile = null;
}
setImageURI(null);
}
}
|
package com.perm.kate.api;
import java.io.Serializable;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Comment implements Serializable {
private static final long serialVersionUID = 1L;
public long cid;
public long from_id;
public long date;
public String message;
public long reply_to_uid;
public long reply_to_cid;
public WallMessage post;//parent post, used only for notifications type "reply_comment". Can be moved to Notification class.
public ArrayList<Attachment> attachments=new ArrayList<Attachment>();
//likes
public int like_count;
public boolean user_like;
public boolean can_like;
public static Comment parse(JSONObject o) throws NumberFormatException, JSONException{
Comment comment=new Comment();
comment.cid = Long.parseLong(o.getString("cid"));
comment.from_id = Long.parseLong(o.getString("from_id"));
comment.date = o.optLong("date");
comment.message = Api.unescape(o.optString("text"));
String reply_to_uid = o.optString("reply_to_uid");
if (reply_to_uid != null && !reply_to_uid.equals(""))
comment.reply_to_uid = Long.parseLong(reply_to_uid);
String reply_to_cid = o.optString("reply_to_cid");
if (reply_to_cid != null && !reply_to_cid.equals(""))
comment.reply_to_cid = Long.parseLong(reply_to_cid);
parseLikes(o, comment);
JSONArray attachments=o.optJSONArray("attachments");
comment.attachments=Attachment.parseAttachments(attachments, 0, 0, null);
return comment;
}
private static void parseLikes(JSONObject o, Comment comment) throws JSONException {
if (o.has("likes")){
JSONObject jlikes = o.getJSONObject("likes");
comment.like_count = jlikes.optInt("count");
comment.user_like = jlikes.optInt("user_likes")==1;
comment.can_like = jlikes.optInt("can_like")==1;
}
}
//for group topic comments
public static Comment parseTopicComment(JSONObject o) throws NumberFormatException, JSONException {
Comment comment = new Comment();
comment.cid = o.getLong("id");
comment.from_id = o.optLong("from_id");
comment.date = o.optLong("date");
comment.message = Api.unescape(o.optString("text"));
parseLikes(o, comment);
JSONArray attachments=o.optJSONArray("attachments");
comment.attachments=Attachment.parseAttachments(attachments, 0, 0, null);
return comment;
}
public static Comment parseNoteComment(JSONObject o) throws NumberFormatException, JSONException {
Comment comment = new Comment();
comment.cid = Long.parseLong(o.getString("id"));
comment.from_id = Long.parseLong(o.getString("uid"));
comment.date = Long.parseLong(o.getString("date"));
comment.message = Api.unescape(o.getString("message"));
return comment;
}
public static Comment parseNotificationComment(JSONObject o, boolean parse_post) throws NumberFormatException, JSONException{
Comment comment = new Comment();
comment.cid = Long.parseLong(o.getString("id"));
comment.from_id = Long.parseLong(o.getString("owner_id"));
comment.date = Long.parseLong(o.getString("date"));
comment.message = Api.unescape(o.getString("text"));
if (o.has("likes")){
JSONObject jlikes = o.getJSONObject("likes");
comment.like_count = jlikes.optInt("count");
comment.user_like = jlikes.optInt("user_likes")==1;
}
if(parse_post){
JSONObject post_json=o.getJSONObject("post");
comment.post=WallMessage.parse(post_json);
}
return comment;
}
}
|
package ch.elexis.core.ui.views;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.wb.swt.SWTResourceManager;
import ch.elexis.admin.AccessControlDefaults;
import ch.elexis.core.constants.Preferences;
import ch.elexis.core.data.activator.CoreHub;
import ch.elexis.core.data.events.ElexisEvent;
import ch.elexis.core.data.events.ElexisEventDispatcher;
import ch.elexis.core.data.events.ElexisEventListener;
import ch.elexis.core.data.events.Heartbeat.HeartListener;
import ch.elexis.core.lock.types.LockResponse;
import ch.elexis.core.model.issue.Priority;
import ch.elexis.core.model.issue.ProcessStatus;
import ch.elexis.core.model.issue.Type;
import ch.elexis.core.services.holder.LocalLockServiceHolder;
import ch.elexis.core.ui.UiDesk;
import ch.elexis.core.ui.actions.RestrictedAction;
import ch.elexis.core.ui.dialogs.ReminderDetailDialog;
import ch.elexis.core.ui.events.ElexisUiEventListenerImpl;
import ch.elexis.core.ui.icons.Images;
import ch.elexis.core.ui.locks.AcquireLockBlockingUi;
import ch.elexis.core.ui.locks.ILockHandler;
import ch.elexis.core.ui.locks.LockRequestingAction;
import ch.elexis.core.ui.locks.LockResponseHelper;
import ch.elexis.core.ui.util.SWTHelper;
import ch.elexis.core.ui.util.ViewMenus;
import ch.elexis.data.Anwender;
import ch.elexis.data.Kontakt;
import ch.elexis.data.Patient;
import ch.elexis.data.PersistentObject;
import ch.elexis.data.Query;
import ch.elexis.data.Reminder;
import ch.rgw.io.Settings;
import ch.rgw.tools.TimeTool;
public class ReminderListsView extends ViewPart implements HeartListener, ISelectionProvider {
public static final String ID = "ch.elexis.core.ui.views.reminderlistsview"; //$NON-NLS-1$
private int filterDueDateDays = CoreHub.userCfg.get(Preferences.USR_REMINDER_FILTER_DUE_DAYS, -1);
private boolean autoSelectPatient = CoreHub.userCfg.get(Preferences.USR_REMINDER_AUTO_SELECT_PATIENT, false);
private boolean showOnlyDueReminders = CoreHub.userCfg.get(Preferences.USR_REMINDERSOPEN, false);
private boolean showAllReminders = (CoreHub.userCfg.get(Preferences.USR_REMINDEROTHERS, false)
&& CoreHub.acl.request(AccessControlDefaults.ADMIN_VIEW_ALL_REMINDERS));
private boolean showSelfCreatedReminders = CoreHub.userCfg.get(Preferences.USR_REMINDEROWN, false);
private Composite viewParent;
private Text txtSearch;
private ReminderFilter filter = new ReminderFilter();
private ViewerSelectionComposite viewerSelectionComposite;
private Composite viewersParent;
private ScrolledComposite viewersScrolledComposite;
private HeaderComposite currentPatientHeader;
private TableViewer currentPatientViewer;
private HeaderComposite generalPatientHeader;
private TableViewer generalPatientViewer;
private HeaderComposite generalHeader;
private TableViewer generalViewer;
private Font boldFont;
private Color colorInProgress;
private Color colorDue;
private Color colorOverdue;
private Color colorOpen;
private List<Reminder> currentSelection = new ArrayList<Reminder>();
private ListenerList<ISelectionChangedListener> selectionChangedListeners = new ListenerList<>();
private Patient actPatient;
private long cvHighestLastUpdate;
private Action reloadAction = new Action(Messages.PatHeuteView_reloadAction) {
{
setImageDescriptor(Images.IMG_REFRESH.getImageDescriptor());
setToolTipText(Messages.PatHeuteView_reloadToolTip);
}
@Override
public void run() {
refresh();
}
};
private Action deleteReminderAction = new Action(Messages.ReminderView_deleteAction) {
{
setImageDescriptor(Images.IMG_DELETE.getImageDescriptor());
setToolTipText(Messages.ReminderView_deleteToolTip);
}
@Override
public void run() {
StructuredSelection sel = (StructuredSelection) getSelection();
if (sel != null && sel.size() == 1 && sel.getFirstElement() instanceof Reminder) {
Reminder r = (Reminder) sel.getFirstElement();
LockResponse lockResponse = LocalLockServiceHolder.get().acquireLock(r);
if (lockResponse.isOk()) {
r.delete();
LocalLockServiceHolder.get().releaseLock(r);
} else {
LockResponseHelper.showInfo(lockResponse, r, null);
}
refreshKeepLabels();
}
}
@Override
public boolean isEnabled() {
StructuredSelection sel = (StructuredSelection) getSelection();
return (sel != null && sel.size() == 1 && sel.getFirstElement() instanceof Reminder);
}
};
private Action newReminderAction = new Action(Messages.ReminderView_newReminderAction) {
{
setImageDescriptor(Images.IMG_NEW.getImageDescriptor());
setToolTipText(Messages.ReminderView_newReminderToolTip);
}
@Override
public void run() {
ReminderDetailDialog erd = null;
erd = new ReminderDetailDialog(getViewSite().getShell());
int retVal = erd.open();
if (retVal == Dialog.OK) {
Reminder reminder = erd.getReminder();
LocalLockServiceHolder.get().acquireLock(reminder);
LocalLockServiceHolder.get().releaseLock(reminder);
}
refresh();
}
};
private Action toggleAutoSelectPatientAction = new Action(Messages.ReminderView_activatePatientAction,
Action.AS_CHECK_BOX) {
{
setImageDescriptor(Images.IMG_PERSON.getImageDescriptor());
setToolTipText(Messages.ReminderView_toggleSelectPatientActionTooltip);
setChecked(autoSelectPatient);
}
@Override
public void run() {
autoSelectPatient = toggleAutoSelectPatientAction.isChecked();
CoreHub.userCfg.set(Preferences.USR_REMINDER_AUTO_SELECT_PATIENT, autoSelectPatient);
}
};
private Action showOthersRemindersAction =
new RestrictedAction(AccessControlDefaults.ADMIN_VIEW_ALL_REMINDERS,
Messages.ReminderView_foreignAction, Action.AS_CHECK_BOX) {
{
setToolTipText(Messages.ReminderView_foreignTooltip);
setImageDescriptor(Images.IMG_ACHTUNG.getImageDescriptor());
}
@Override
public void doRun(){
showAllReminders = showOthersRemindersAction.isChecked();
CoreHub.userCfg.set(Preferences.USR_REMINDEROTHERS, showAllReminders);
refresh();
}
};
private Action showSelfCreatedReminderAction = new Action(Messages.ReminderView_myRemindersAction,
Action.AS_CHECK_BOX) { // $NON-NLS-1$
{
setToolTipText(Messages.ReminderView_myRemindersToolTip); // $NON-NLS-1$
}
@Override
public void run() {
showSelfCreatedReminders = showSelfCreatedReminderAction.isChecked();
CoreHub.userCfg.set(Preferences.USR_REMINDEROWN, showSelfCreatedReminders);
refresh();
}
};
private Action showOnlyOwnDueReminderToggleAction = new Action(Messages.ReminderView_onlyDueAction,
Action.AS_CHECK_BOX) { // $NON-NLS-1$
{
setToolTipText(Messages.ReminderView_onlyDueToolTip); // $NON-NLS-1$
}
@Override
public void run() {
showOnlyDueReminders = showOnlyOwnDueReminderToggleAction.isChecked();
CoreHub.userCfg.set(Preferences.USR_REMINDERSOPEN, showOnlyDueReminders);
refresh();
}
};
private RestrictedAction selectPatientAction = new RestrictedAction(AccessControlDefaults.PATIENT_DISPLAY,
Messages.ReminderView_activatePatientAction, Action.AS_UNSPECIFIED) {
{
setImageDescriptor(Images.IMG_PERSON.getImageDescriptor());
setToolTipText(Messages.ReminderView_activatePatientTooltip);
}
public void doRun() {
StructuredSelection sel = (StructuredSelection) getSelection();
if (sel != null && sel.size() != 1) {
SWTHelper.showInfo(Messages.ReminderView_onePatOnly, Messages.ReminderView_onlyOnePatientForActivation);
} else if (sel != null && sel.size() > 0) {
Reminder reminder = (Reminder) sel.getFirstElement();
Patient patient = reminder.getKontakt();
Anwender creator = reminder.getCreator();
if (patient != null) {
if (!patient.getId().equals(creator.getId())) {
ElexisEventDispatcher.fireSelectionEvent(patient);
}
}
}
}
@Override
public boolean isEnabled() {
StructuredSelection sel = (StructuredSelection) getSelection();
if (sel != null && sel.size() == 1 && sel.getFirstElement() instanceof Reminder) {
Reminder reminder = (Reminder) sel.getFirstElement();
return reminder.isPatientRelated();
}
return false;
}
};
private ElexisEventListener eeli_pat = new ElexisUiEventListenerImpl(Patient.class) {
public void runInUi(final ElexisEvent ev) {
if (((Patient) ev.getObject()).equals(actPatient)) {
return;
}
actPatient = (Patient) ev.getObject();
clearSelection();
patientRefresh();
/**
* ch.elexis.core.data.events.PatientEventListener will be called on opposite
* Preferences.USR_SHOWPATCHGREMINDER condition.
*/
if (!CoreHub.userCfg.get(Preferences.USR_SHOWPATCHGREMINDER, true)) {
UiDesk.asyncExec(new Runnable() {
public void run() {
List<Reminder> list = Reminder.findOpenRemindersResponsibleFor(
CoreHub.getLoggedInContact(), false, (Patient) ev.getObject(), true);
if (list.size() != 0) {
StringBuilder sb = new StringBuilder();
for (Reminder r : list) {
sb.append(r.getSubject() + "\n");
sb.append(r.getMessage() + "\n\n");
}
SWTHelper.alert(Messages.ReminderView_importantRemindersCaption, sb.toString());
}
}
});
}
}
};
private ElexisEventListener eeli_user = new ElexisUiEventListenerImpl(Anwender.class,
ElexisEvent.EVENT_USER_CHANGED) {
public void runInUi(ElexisEvent ev) {
refreshUserConfiguration();
refresh();
}
};
private ElexisEventListener eeli_reminder = new ElexisUiEventListenerImpl(Reminder.class,
ElexisEvent.EVENT_RELOAD | ElexisEvent.EVENT_CREATE | ElexisEvent.EVENT_UPDATE) {
public void catchElexisEvent(ElexisEvent ev) {
refresh();
}
};
@Override
public void createPartControl(Composite parent) {
viewParent = new Composite(parent, SWT.NONE);
viewParent.setLayout(new GridLayout());
txtSearch = new Text(viewParent, SWT.SEARCH);
txtSearch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
txtSearch.setMessage(Messages.ReminderView_txtSearch_message);
txtSearch.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
clearSelection();
filter.setFilterText(txtSearch.getText());
refreshKeepLabels();
}
});
boldFont = SWTResourceManager.getBoldFont(txtSearch.getFont());
viewerSelectionComposite = new ViewerSelectionComposite(viewParent, SWT.NONE);
viewerSelectionComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
viewersScrolledComposite = new ScrolledComposite(viewParent, SWT.V_SCROLL);
viewersScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
viewersScrolledComposite.setExpandVertical(true);
viewersScrolledComposite.setExpandHorizontal(true);
viewersScrolledComposite.addListener(SWT.Resize, event -> {
int width = viewersScrolledComposite.getClientArea().width;
viewersScrolledComposite.setMinSize(viewersParent.computeSize(width, SWT.DEFAULT));
});
viewersParent = new Composite(viewersScrolledComposite, SWT.NONE);
viewersParent.setBackground(UiDesk.getColor(UiDesk.COL_WHITE));
GridLayout layout = new GridLayout();
layout.horizontalSpacing = 0;
layout.verticalSpacing = 0;
layout.marginHeight = 0;
layout.marginWidth = 0;
viewersParent.setLayout(layout);
viewersScrolledComposite.setContent(viewersParent);
currentPatientHeader = new HeaderComposite(viewersParent, SWT.NONE);
currentPatientHeader.setTextFont(boldFont);
currentPatientHeader.setText("aktueller Patient");
currentPatientViewer = new TableViewer(viewersParent, SWT.FULL_SELECTION | SWT.BORDER | SWT.VIRTUAL);
currentPatientViewer.getTable().setHeaderVisible(true);
currentPatientViewer.setContentProvider(ArrayContentProvider.getInstance());
GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd.heightHint = 100;
currentPatientViewer.getTable().setLayoutData(gd);
currentPatientViewer.setComparator(new ReminderComparator());
currentPatientViewer.addFilter(filter);
currentPatientViewer.addSelectionChangedListener(getSelectionListener());
currentPatientViewer.addDoubleClickListener(getDoubleClickListener());
createTypeColumn(currentPatientViewer, 20, 0);
createDateColumn(currentPatientViewer, 80, 1);
createResponsibleColumn(currentPatientViewer, 40, 2);
createPatientColumn(currentPatientViewer, 120, 3);
createDescriptionColumn(currentPatientViewer, 400, 4);
generalPatientHeader = new HeaderComposite(viewersParent, SWT.NONE);
generalPatientHeader.setTextFont(boldFont);
generalPatientHeader.setText("alle Patienten");
generalPatientViewer = new TableViewer(viewersParent, SWT.FULL_SELECTION | SWT.BORDER | SWT.VIRTUAL);
generalPatientViewer.getTable().setHeaderVisible(true);
generalPatientViewer.setContentProvider(ArrayContentProvider.getInstance());
gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd.heightHint = 100;
generalPatientViewer.getTable().setLayoutData(gd);
generalPatientViewer.setComparator(new ReminderComparator());
generalPatientViewer.addFilter(filter);
generalPatientViewer.addSelectionChangedListener(getSelectionListener());
generalPatientViewer.addDoubleClickListener(getDoubleClickListener());
createTypeColumn(generalPatientViewer, 20, 0);
createDateColumn(generalPatientViewer, 80, 1);
createResponsibleColumn(generalPatientViewer, 40, 2);
createPatientColumn(generalPatientViewer, 120, 3);
createDescriptionColumn(generalPatientViewer, 400, 4);
generalHeader = new HeaderComposite(viewersParent, SWT.NONE);
generalHeader.setTextFont(boldFont);
generalHeader.setText("allgemein");
generalViewer = new TableViewer(viewersParent, SWT.FULL_SELECTION | SWT.BORDER | SWT.VIRTUAL);
generalViewer.getTable().setHeaderVisible(true);
generalViewer.setContentProvider(ArrayContentProvider.getInstance());
gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd.heightHint = 100;
generalViewer.getTable().setLayoutData(gd);
generalViewer.setComparator(new ReminderComparator());
generalViewer.addFilter(filter);
generalViewer.addSelectionChangedListener(getSelectionListener());
generalViewer.addDoubleClickListener(getDoubleClickListener());
createTypeColumn(generalViewer, 20, 0);
createDateColumn(generalViewer, 80, 1);
createResponsibleColumn(generalViewer, 40, 2);
createPatientColumn(generalViewer, 120, 3);
createDescriptionColumn(generalViewer, 400, 4);
viewerSelectionComposite.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
StructuredSelection selection = (StructuredSelection) event.getSelection();
updateViewerSelection(selection);
refresh();
}
});
actPatient = ElexisEventDispatcher.getSelectedPatient();
viewerSelectionComposite.loadSelection();
updateViewerSelection((StructuredSelection) viewerSelectionComposite.getSelection());
refreshUserConfiguration();
ViewMenus menu = new ViewMenus(getViewSite());
menu.createToolbar(reloadAction, newReminderAction, toggleAutoSelectPatientAction);
MenuManager timeFilterSubMenu = new MenuManager("Zeitraum Anzeige");
FilterTimeAction action30 = new FilterTimeAction(30);
FilterTimeAction action60 = new FilterTimeAction(60);
FilterTimeAction action90 = new FilterTimeAction(90);
action30.setOthers(Arrays.asList(action60, action90));
action60.setOthers(Arrays.asList(action30, action90));
action90.setOthers(Arrays.asList(action30, action60));
timeFilterSubMenu.add(action30);
timeFilterSubMenu.add(action60);
timeFilterSubMenu.add(action90);
MenuManager menuManager = new MenuManager();
menuManager.add(new ReminderStatusSubMenu());
menuManager.add(deleteReminderAction);
menuManager.add(timeFilterSubMenu);
menuManager.add(showOnlyOwnDueReminderToggleAction);
menuManager.add(showSelfCreatedReminderAction);
menuManager.add(showOthersRemindersAction);
currentPatientViewer.getTable().setMenu(menuManager.createContextMenu(currentPatientViewer.getTable()));
generalPatientViewer.getTable().setMenu(menuManager.createContextMenu(generalPatientViewer.getTable()));
generalViewer.getTable().setMenu(menuManager.createContextMenu(generalViewer.getTable()));
ElexisEventDispatcher.getInstance().addListeners(eeli_pat, eeli_user, eeli_reminder);
}
@Override
public void dispose() {
ElexisEventDispatcher.getInstance().removeListeners(eeli_pat, eeli_user, eeli_reminder);
}
private void updateViewerSelection(StructuredSelection selection) {
viewersParent.setRedraw(false);
hideControl(currentPatientHeader);
hideControl(currentPatientViewer.getTable());
hideControl(generalPatientHeader);
hideControl(generalPatientViewer.getTable());
hideControl(generalHeader);
hideControl(generalViewer.getTable());
if (selection != null && !selection.isEmpty()) {
for (Object selected : selection.toList()) {
if (selected instanceof String) {
if (SELECTIONCOMP_CURRENTPATIENT_ID.equals(selected)) {
showControl(currentPatientHeader);
showControl(currentPatientViewer.getTable());
} else if (SELECTIONCOMP_GENERALPATIENT_ID.equals(selected)) {
showControl(generalPatientHeader);
showControl(generalPatientViewer.getTable());
} else if (SELECTIONCOMP_GENERAL_ID.equals(selected)) {
showControl(generalHeader);
showControl(generalViewer.getTable());
}
}
}
}
viewersParent.setRedraw(true);
int width = viewersScrolledComposite.getClientArea().width;
viewersScrolledComposite.setMinSize(viewersParent.computeSize(width, SWT.DEFAULT));
viewParent.layout(true, true);
}
private void showControl(Control control) {
if (control != null && control.getLayoutData() != null) {
control.setVisible(true);
((GridData) control.getLayoutData()).exclude = false;
}
}
private void hideControl(Control control) {
if (control != null && control.getLayoutData() != null) {
control.setVisible(false);
((GridData) control.getLayoutData()).exclude = true;
}
}
@Override
public void setFocus() {
viewersParent.setFocus();
}
private void refreshKeepLabels() {
if (generalViewer.getTable().isVisible()) {
generalViewer.refresh(false);
}
if (generalPatientViewer.getTable().isVisible()) {
generalPatientViewer.refresh(false);
}
if (currentPatientViewer.getTable().isVisible()) {
currentPatientViewer.refresh(false);
}
}
private void refresh() {
Display.getDefault().asyncExec(() -> {
patientRefresh();
generalRefresh();
int width = viewersScrolledComposite.getClientArea().width;
viewersScrolledComposite.setMinSize(viewersParent.computeSize(width, SWT.DEFAULT));
viewParent.layout(true, true);
});
}
private void patientRefresh() {
if (actPatient != null) {
if (currentPatientViewer.getTable().isVisible()) {
refreshCurrentPatientInput();
}
} else {
currentPatientViewer.setInput(Collections.emptyList());
}
}
private void generalRefresh() {
if (generalViewer.getTable().isVisible()) {
refreshGeneralInput();
}
if (generalPatientViewer.getTable().isVisible()) {
refreshGeneralPatientInput();
}
}
private void refreshCurrentPatientInput() {
if (actPatient != null) {
Query<Reminder> query = new Query<>(Reminder.class, null, null, Reminder.TABLENAME,
new String[] { Reminder.FLD_DUE,
Reminder.FLD_PRIORITY, Reminder.FLD_ACTION_TYPE, Reminder.FLD_CREATOR,
Reminder.FLD_KONTAKT_ID
});
List<Reminder> reminders = Collections.emptyList();
if (showAllReminders
&& CoreHub.acl.request(AccessControlDefaults.ADMIN_VIEW_ALL_REMINDERS)) {
query.add(Reminder.FLD_KONTAKT_ID, Query.EQUALS, actPatient.getId());
if (filterDueDateDays != -1) {
applyDueDateFilter(query);
}
reminders = query.execute();
} else {
reminders = Reminder.findOpenRemindersResponsibleFor(CoreHub.getLoggedInContact(),
showOnlyDueReminders, filterDueDateDays, actPatient, false);
if (showSelfCreatedReminders) {
query.add(Reminder.FLD_CREATOR, Query.EQUALS,
CoreHub.getLoggedInContact().getId());
query.add(Reminder.FLD_KONTAKT_ID, Query.EQUALS, actPatient.getId());
if (filterDueDateDays != -1) {
applyDueDateFilter(query);
}
reminders.addAll(query.execute());
}
}
List<Reminder> input = reminders;
Display.getDefault().asyncExec(() -> {
if (currentPatientViewer != null && !currentPatientViewer.getTable().isDisposed()) {
currentPatientViewer.setInput(input);
viewerSelectionComposite.setCount(SELECTIONCOMP_CURRENTPATIENT_ID,
currentPatientViewer.getTable().getItemCount());
if (input.size() < 5) {
if (((GridData) currentPatientViewer.getTable().getLayoutData()).heightHint != 125) {
((GridData) currentPatientViewer.getTable().getLayoutData()).heightHint = 125;
currentPatientViewer.getTable().getParent().layout(true, true);
}
} else {
if (((GridData) currentPatientViewer.getTable().getLayoutData()).heightHint != 300) {
((GridData) currentPatientViewer.getTable().getLayoutData()).heightHint = 300;
currentPatientViewer.getTable().getParent().layout(true, true);
}
}
}
});
}
}
private void refreshGeneralPatientInput() {
HashSet<Reminder> uniqueReminders = new HashSet<>();
uniqueReminders.addAll(Reminder.findOpenRemindersResponsibleFor(
CoreHub.getLoggedInContact(), showOnlyDueReminders,
filterDueDateDays, null, false));
Query<Reminder> query = new Query<>(Reminder.class, null, null, Reminder.TABLENAME,
new String[] { Reminder.FLD_DUE, Reminder.FLD_PRIORITY, Reminder.FLD_ACTION_TYPE, Reminder.FLD_CREATOR,
Reminder.FLD_KONTAKT_ID });
if (showSelfCreatedReminders) {
query.add(Reminder.FLD_CREATOR, Query.EQUALS, CoreHub.getLoggedInContact().getId());
if (filterDueDateDays != -1) {
applyDueDateFilter(query);
}
uniqueReminders.addAll(query.execute());
}
List<Reminder> filteredReminders = uniqueReminders.parallelStream().filter(r -> r.isPatientRelated())
.collect(Collectors.toList());
Display.getDefault().asyncExec(() -> {
if (generalPatientViewer != null && !generalPatientViewer.getTable().isDisposed()) {
generalPatientViewer.setInput(filteredReminders);
viewerSelectionComposite.setCount(SELECTIONCOMP_GENERALPATIENT_ID,
generalPatientViewer.getTable().getItemCount());
if (generalPatientViewer.getTable().getItemCount() < 5) {
if (((GridData) generalPatientViewer.getTable().getLayoutData()).heightHint != 125) {
((GridData) generalPatientViewer.getTable().getLayoutData()).heightHint = 125;
generalPatientViewer.getTable().getParent().layout(true, true);
}
} else {
if (((GridData) generalPatientViewer.getTable().getLayoutData()).heightHint != 300) {
((GridData) generalPatientViewer.getTable().getLayoutData()).heightHint = 300;
generalPatientViewer.getTable().getParent().layout(true, true);
}
}
}
});
}
private void refreshGeneralInput() {
HashSet<Reminder> uniqueReminders = new HashSet<>();
uniqueReminders.addAll(Reminder.findOpenRemindersResponsibleFor(
CoreHub.getLoggedInContact(), showOnlyDueReminders,
filterDueDateDays, null, false));
Query<Reminder> query = new Query<>(Reminder.class, null, null, Reminder.TABLENAME,
new String[] { Reminder.FLD_DUE, Reminder.FLD_PRIORITY, Reminder.FLD_ACTION_TYPE, Reminder.FLD_CREATOR,
Reminder.FLD_KONTAKT_ID });
if (showSelfCreatedReminders) {
query.add(Reminder.FLD_CREATOR, Query.EQUALS, CoreHub.getLoggedInContact().getId());
if (filterDueDateDays != -1) {
applyDueDateFilter(query);
}
uniqueReminders.addAll(query.execute());
}
List<Reminder> filteredReminders = uniqueReminders.parallelStream().filter(r -> !r.isPatientRelated())
.collect(Collectors.toList());
Display.getDefault().asyncExec(() -> {
if (generalViewer != null && !generalViewer.getTable().isDisposed()) {
generalViewer.setInput(filteredReminders);
viewerSelectionComposite.setCount(SELECTIONCOMP_GENERAL_ID, generalViewer.getTable().getItemCount());
if (generalViewer.getTable().getItemCount() < 5) {
if (((GridData) generalViewer.getTable().getLayoutData()).heightHint != 125) {
((GridData) generalViewer.getTable().getLayoutData()).heightHint = 125;
generalViewer.getTable().getParent().layout(true, true);
}
} else {
if (((GridData) generalViewer.getTable().getLayoutData()).heightHint != 300) {
((GridData) generalViewer.getTable().getLayoutData()).heightHint = 300;
generalViewer.getTable().getParent().layout(true, true);
}
}
}
});
}
private void applyDueDateFilter(Query<Reminder> qbe) {
TimeTool dueDateDays = new TimeTool();
dueDateDays.addDays(filterDueDateDays);
qbe.add(Reminder.FLD_DUE, Query.NOT_EQUAL, "");
qbe.add(Reminder.FLD_DUE, Query.LESS_OR_EQUAL, dueDateDays.toString(TimeTool.DATE_COMPACT));
}
private void refreshUserConfiguration() {
showOnlyOwnDueReminderToggleAction.setChecked(CoreHub.userCfg.get(Preferences.USR_REMINDERSOPEN, true));
showSelfCreatedReminderAction.setChecked(CoreHub.userCfg.get(Preferences.USR_REMINDEROWN, false));
toggleAutoSelectPatientAction
.setChecked(CoreHub.userCfg.get(Preferences.USR_REMINDER_AUTO_SELECT_PATIENT, false));
// // get state from user's configuration
// showOthersRemindersAction.setChecked(CoreHub.userCfg.get(Preferences.USR_REMINDEROTHERS, false));
// // update action's access rights
// showOthersRemindersAction.reflectRight();
Settings cfg = CoreHub.userCfg.getBranch(Preferences.USR_REMINDERCOLORS, true);
colorInProgress = UiDesk.getColorFromRGB(cfg.get(ProcessStatus.IN_PROGRESS.name(), "FFFFFF")); //$NON-NLS-1$ ;
colorDue = UiDesk.getColorFromRGB(cfg.get(ProcessStatus.DUE.name(), "FFFFFF")); //$NON-NLS-1$ ;
colorOverdue = UiDesk.getColorFromRGB(cfg.get(ProcessStatus.OVERDUE.name(), "FF0000")); //$NON-NLS-1$
colorOpen = UiDesk.getColorFromRGB(cfg.get(ProcessStatus.OPEN.name(), "00FF00")); //$NON-NLS-1$
}
private TableViewerColumn createTypeColumn(TableViewer viewer, int width, int columnIndex) {
TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
TableColumn tableColumn = viewerColumn.getColumn();
tableColumn.setWidth(width);
tableColumn.addSelectionListener(getSelectionAdapter(viewer, tableColumn, columnIndex));
viewerColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
return "";
}
@Override
public Image getImage(Object element) {
if (element instanceof Reminder) {
Reminder reminder = (Reminder) element;
Type actionType = reminder.getActionType();
switch (actionType) {
case PRINT:
case PRINT_DRUG_STICKER:
return Images.IMG_PRINTER.getImage();
case MAKE_APPOINTMENT:
return Images.IMG_CALENDAR.getImage();
case DISPENSE_MEDICATION:
return Images.IMG_PILL.getImage();
case PROCESS_SERVICE_RECORDING:
return Images.IMG_MONEY.getImage();
case CHECK_LAB_RESULT:
case READ_DOCUMENT:
return Images.IMG_EYE_WO_SHADOW.getImage();
case SEND_DOCUMENT:
return Images.IMG_MAIL_SEND.getImage();
default:
return null;
}
}
return null;
}
});
return viewerColumn;
}
private TableViewerColumn createDateColumn(TableViewer viewer, int width, int columnIndex) {
TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
TableColumn tableColumn = viewerColumn.getColumn();
tableColumn.setWidth(width);
tableColumn.setText("Datum");
tableColumn.addSelectionListener(getSelectionAdapter(viewer, tableColumn, columnIndex));
viewerColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Reminder reminder = (Reminder) element;
return reminder.get(Reminder.FLD_DUE);
}
@Override
public Color getBackground(Object element) {
Reminder reminder = (Reminder) element;
switch (reminder.getDueState()) {
case 1:
return colorDue;
case 2:
return colorOverdue;
default:
ProcessStatus processStatus = reminder.getProcessStatus();
if (ProcessStatus.OPEN == processStatus) {
return colorOpen;
} else if (ProcessStatus.IN_PROGRESS == processStatus) {
return colorInProgress;
}
return null;
}
}
});
return viewerColumn;
}
private TableViewerColumn createPatientColumn(TableViewer viewer, int width, int columnIndex) {
ColumnViewerToolTipSupport.enableFor(viewer);
TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
TableColumn tableColumn = viewerColumn.getColumn();
tableColumn.setWidth(width);
tableColumn.setText("Patient");
tableColumn.addSelectionListener(getSelectionAdapter(viewer, tableColumn, columnIndex));
viewerColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Reminder reminder = (Reminder) element;
Kontakt k = Kontakt.load(reminder.get(Reminder.FLD_KONTAKT_ID));
return k.getLabel(false);
}
@Override
public String getToolTipText(Object element) {
return getText(element);
}
});
return viewerColumn;
}
private TableViewerColumn createDescriptionColumn(TableViewer viewer, int width, int columnIndex) {
ColumnViewerToolTipSupport.enableFor(viewer);
TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
TableColumn tableColumn = viewerColumn.getColumn();
tableColumn.setWidth(width);
tableColumn.setText("Betreff");
tableColumn.addSelectionListener(getSelectionAdapter(viewer, tableColumn, columnIndex));
viewerColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Reminder reminder = (Reminder) element;
String[] vals = reminder.get(true, Reminder.FLD_MESSAGE, Reminder.FLD_SUBJECT);
return (vals[1].length() > 0) ? vals[1] : vals[0];
}
@Override
public String getToolTipText(Object element) {
return getText(element);
}
@Override
public Font getFont(Object element) {
Reminder reminder = (Reminder) element;
Priority prio = reminder.getPriority();
if (Priority.HIGH == prio) {
return boldFont;
}
return null;
}
});
return viewerColumn;
}
private TableViewerColumn createResponsibleColumn(TableViewer viewer, int width, int columnIndex) {
ColumnViewerToolTipSupport.enableFor(viewer);
TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
TableColumn tableColumn = viewerColumn.getColumn();
tableColumn.setWidth(width);
tableColumn.setText("Zust.");
tableColumn.addSelectionListener(getSelectionAdapter(viewer, tableColumn, columnIndex));
viewerColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Reminder reminder = (Reminder) element;
List<Anwender> responsibles = reminder.getResponsibles();
if (responsibles != null) {
StringJoiner sj = new StringJoiner(", ");
responsibles.forEach(r -> sj.add(r.getLabel(true)));
return sj.toString();
}
return null;
}
@Override
public String getToolTipText(Object element) {
return getText(element);
}
});
return viewerColumn;
}
private ISelectionChangedListener getSelectionListener() {
return new ISelectionChangedListener() {
@SuppressWarnings("unchecked")
@Override
public void selectionChanged(SelectionChangedEvent event){
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
ReminderListsView.this.selectionChanged(selection.toList());
selectPatientAction.setEnabled(selection.size() <= 1);
selectPatientAction.reflectRight();
if (autoSelectPatient && selectPatientAction.isEnabled()) {
selectPatientAction.doRun();
}
}
};
}
private IDoubleClickListener getDoubleClickListener() {
return new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
StructuredSelection selection = (StructuredSelection) event.getSelection();
if (selection != null && !selection.isEmpty()) {
Reminder reminder = (Reminder) selection.getFirstElement();
AcquireLockBlockingUi.aquireAndRun(reminder, new ILockHandler() {
@Override
public void lockAcquired() {
ReminderDetailDialog rdd = new ReminderDetailDialog(UiDesk.getTopShell(), reminder);
int retVal = rdd.open();
if (retVal == Dialog.OK) {
ElexisEventDispatcher.getInstance()
.fire(new ElexisEvent(reminder, getClass(), ElexisEvent.EVENT_UPDATE));
}
}
@Override
public void lockFailed() {
refreshKeepLabels();
}
});
}
}
};
}
private SelectionAdapter getSelectionAdapter(final TableViewer viewer, final TableColumn column, final int index) {
SelectionAdapter selectionAdapter = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ReminderComparator comparator = (ReminderComparator) viewer.getComparator();
comparator.setColumn(index);
int dir = comparator.getDirection();
viewer.getTable().setSortColumn(column);
viewer.getTable().setSortDirection(dir);
viewer.refresh(true);
}
};
return selectionAdapter;
}
private class ReminderComparator extends ViewerComparator implements Comparator<Reminder> {
private int column;
private int direction;
public ReminderComparator() {
column = -1;
direction = SWT.DOWN;
}
@Override
public int compare(Reminder r1, Reminder r2) {
if (column == 1) {
if (direction == SWT.UP) {
return TimeTool.compare(r2.getDateDue(), r1.getDateDue());
} else {
return TimeTool.compare(r1.getDateDue(), r2.getDateDue());
}
} else {
return TimeTool.compare(r1.getDateDue(), r2.getDateDue());
}
}
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
return compare((Reminder) e1, (Reminder) e2);
}
public void setColumn(int index) {
if (column == index) {
// Same column as last sort; toggle the direction
direction = ((direction == SWT.DOWN) ? SWT.UP : SWT.DOWN);
} else {
// New column; do an ascending sort
column = index;
direction = SWT.DOWN;
}
}
public int getDirection() {
return direction;
}
}
private static String SELECTIONCOMP_CURRENTPATIENT_ID = "reminderlistsview.selection.currentpatient";
private static String SELECTIONCOMP_GENERALPATIENT_ID = "reminderlistsview.selection.generalpatient";
private static String SELECTIONCOMP_GENERAL_ID = "reminderlistsview.selection.general";
private class ViewerSelectionComposite extends Composite implements ISelectionProvider {
private List<Action> currentSelection;
private ListenerList<ISelectionChangedListener> selectionChangedListeners;
private ToolBarManager manager;
public ViewerSelectionComposite(Composite parent, int style) {
super(parent, style);
currentSelection = new ArrayList<>();
selectionChangedListeners = new ListenerList<>();
createContent();
}
public void setCount(String id, int itemCount) {
for (IContributionItem item : manager.getItems()) {
if (item.getId().equals(id)) {
IAction action = ((ActionContributionItem) item).getAction();
String text = action.getText();
if (text.indexOf(" (") != -1) {
text = text.substring(0, text.indexOf(" ("));
}
action.setText(text + " (" + itemCount + ")");
item.update();
}
}
manager.update(true);
layout();
}
private void createContent() {
setBackground(UiDesk.getColor(UiDesk.COL_WHITE));
setLayout(new FillLayout());
manager = new ToolBarManager(SWT.WRAP);
manager.add(new Action("aktueller Patient", Action.AS_CHECK_BOX) {
@Override
public String getId() {
return SELECTIONCOMP_CURRENTPATIENT_ID;
}
@Override
public void run() {
if (currentSelection.contains(this)) {
currentSelection.remove(this);
} else {
currentSelection.add(this);
}
fireSelectionChanged();
manager.update(true);
saveSelection();
}
});
manager.add(new Action("alle Patienten", Action.AS_CHECK_BOX) {
@Override
public String getId() {
return SELECTIONCOMP_GENERALPATIENT_ID;
}
@Override
public void run() {
if (currentSelection.contains(this)) {
currentSelection.remove(this);
} else {
currentSelection.add(this);
}
fireSelectionChanged();
manager.update(true);
saveSelection();
}
});
manager.add(new Action("allgemein", Action.AS_CHECK_BOX) {
@Override
public String getId() {
return SELECTIONCOMP_GENERAL_ID;
}
@Override
public void run() {
if (currentSelection.contains(this)) {
currentSelection.remove(this);
} else {
currentSelection.add(this);
}
fireSelectionChanged();
manager.update(true);
saveSelection();
}
});
manager.createControl(this);
}
private void saveSelection() {
List<String> selectedIds = currentSelection.stream().map(action -> action.getId())
.collect(Collectors.toList());
StringJoiner sj = new StringJoiner(",");
selectedIds.forEach(id -> sj.add(id));
CoreHub.userCfg.set(Preferences.USR_REMINDER_VIEWER_SELECTION, sj.toString());
}
public void loadSelection() {
currentSelection.clear();
String[] loadedIds = CoreHub.userCfg.get(Preferences.USR_REMINDER_VIEWER_SELECTION, "").split(",");
for (String id : loadedIds) {
for (IContributionItem item : manager.getItems()) {
if (item.getId().equals(id)) {
IAction action = ((ActionContributionItem) item).getAction();
action.setChecked(true);
currentSelection.add((Action) action);
}
}
fireSelectionChanged();
manager.update(true);
layout();
}
}
@Override
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
@Override
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
@Override
public ISelection getSelection() {
return new StructuredSelection(
currentSelection.stream().map(action -> action.getId()).collect(Collectors.toList()));
}
@Override
public void setSelection(ISelection selection) {
// ignore until needed
}
private void fireSelectionChanged() {
ISelection selection = getSelection();
for (ISelectionChangedListener listener : selectionChangedListeners) {
SelectionChangedEvent event = new SelectionChangedEvent(this, selection);
listener.selectionChanged(event);
}
}
}
private class FilterTimeAction extends Action {
private List<FilterTimeAction> others;
private int days;
public FilterTimeAction(int days) {
super(String.format("nächste %d Tage", days), Action.AS_CHECK_BOX);
this.days = days;
if (filterDueDateDays == days) {
setChecked(true);
}
}
public void setOthers(List<FilterTimeAction> list) {
this.others = list;
}
@Override
public void run() {
if (isChecked()) {
CoreHub.userCfg.set(Preferences.USR_REMINDER_FILTER_DUE_DAYS, days);
filterDueDateDays = days;
clearSelection();
refresh();
} else {
CoreHub.userCfg.set(Preferences.USR_REMINDER_FILTER_DUE_DAYS, -1);
filterDueDateDays = -1;
clearSelection();
refresh();
}
if (others != null) {
for (FilterTimeAction other : others) {
other.setChecked(false);
}
}
}
}
private class ReminderStatusSubMenu extends MenuManager {
public ReminderStatusSubMenu() {
super("Status...");
setRemoveAllWhenShown(true);
addMenuListener(new ReminderStatusSubMenuListener());
}
private class ReminderStatusSubMenuListener implements IMenuListener {
@Override
public void menuAboutToShow(IMenuManager manager) {
StructuredSelection selection = (StructuredSelection) getSelection();
if (selection != null && selection.size() == 1) {
if (selection.getFirstElement() instanceof Reminder) {
Reminder reminder = (Reminder) selection.getFirstElement();
manager.add(new StatusAction(ProcessStatus.OPEN, reminder));
manager.add(new StatusAction(ProcessStatus.IN_PROGRESS, reminder));
manager.add(new StatusAction(ProcessStatus.CLOSED, reminder));
manager.add(new StatusAction(ProcessStatus.ON_HOLD, reminder));
}
} else {
manager.add(new Action("Multiple selection") {
@Override
public boolean isEnabled() {
return false;
}
});
}
}
private class StatusAction extends LockRequestingAction<Reminder> {
private final ProcessStatus representedStatus;
private Reminder reminder;
public StatusAction(ProcessStatus representedStatus, Reminder reminder) {
super(representedStatus.getLocaleText(), SWT.RADIO);
this.representedStatus = representedStatus;
this.reminder = reminder;
ProcessStatus status = reminder.getProcessStatus();
if (ProcessStatus.DUE == status || ProcessStatus.OVERDUE == status) {
setChecked(representedStatus == ProcessStatus.OPEN);
} else {
setChecked(representedStatus == status);
}
}
@Override
public boolean isChecked() {
ProcessStatus status = reminder.getProcessStatus();
if (ProcessStatus.DUE == status || ProcessStatus.OVERDUE == status) {
return (representedStatus == ProcessStatus.OPEN);
} else {
return (representedStatus == reminder.getProcessStatus());
}
}
@Override
public String getText() {
String text = super.getText();
ProcessStatus status = reminder.getProcessStatus();
if ((ProcessStatus.DUE == status || ProcessStatus.OVERDUE == status)
&& (ProcessStatus.OPEN == representedStatus)) {
return text + " (" + status.getLocaleText() + ")";
}
return text;
}
@Override
public Reminder getTargetedObject() {
return reminder;
}
@Override
public void doRun(Reminder element) {
element.setProcessStatus(representedStatus);
ElexisEventDispatcher.getInstance()
.fire(new ElexisEvent(element, Reminder.class, ElexisEvent.EVENT_UPDATE));
}
}
}
}
private class HeaderComposite extends Composite {
private Label header;
private ToolBarManager toolbarManager;
public HeaderComposite(Composite parent, int style) {
super(parent, style);
setBackground(parent.getBackground());
GridLayout layout = new GridLayout();
layout.horizontalSpacing = 0;
layout.verticalSpacing = 0;
layout.marginHeight = 0;
layout.marginWidth = 0;
setLayout(layout);
header = new Label(this, SWT.NONE);
header.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
header.setBackground(getBackground());
toolbarManager = new ToolBarManager();
ToolBar toolbar = toolbarManager.createControl(this);
toolbar.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
toolbar.setBackground(getBackground());
}
public void setTextFont(Font font) {
header.setFont(font);
}
public void setText(String text) {
header.setText(text);
ReminderListsView.this.viewParent.layout(true, true);
}
}
@Override
public void heartbeat() {
long highestLastUpdate = PersistentObject.getHighestLastUpdate(Reminder.TABLENAME);
if (highestLastUpdate > cvHighestLastUpdate) {
refresh();
cvHighestLastUpdate = highestLastUpdate;
}
}
@Override
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
@Override
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
@Override
public ISelection getSelection() {
return new StructuredSelection(currentSelection);
}
@Override
public void setSelection(ISelection arg0) {
// currently not supported
}
private void clearSelection() {
StructuredSelection clear = new StructuredSelection();
currentPatientViewer.setSelection(clear);
generalPatientViewer.setSelection(clear);
generalViewer.setSelection(clear);
}
private void selectionChanged(List<Reminder> list) {
currentSelection.clear();
currentSelection.addAll(list);
fireSelectionChanged();
}
private void fireSelectionChanged() {
ISelection selection = getSelection();
for (ISelectionChangedListener listener : selectionChangedListeners) {
SelectionChangedEvent event = new SelectionChangedEvent(this, selection);
listener.selectionChanged(event);
}
}
}
|
package org.treetank.gui.view.sunburst;
import org.treetank.gui.view.EHover;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PGraphics;
/**
* Encapsulates drawing strategies.
*
* @author Johannes Lichtenberger, University of Konstanz
*
*/
public enum EDraw {
/** Draw directly. */
DRAW {
/** {@inheritDoc} */
@Override
void drawStrategy(final SunburstGUI paramGUI, final SunburstItem paramItem,
final EDrawSunburst paramDraw) {
paramDraw.drawStrategy(paramGUI, paramItem, this);
}
/** {@inheritDoc} */
@Override
void update(final SunburstGUI paramGUI, final SunburstItem paramItem) {
paramItem.update(paramGUI.getMappingMode(), paramGUI.mParent.g);
}
/** {@inheritDoc} */
@Override
void drawOldRevision(final SunburstGUI paramGUI) {
drawStaticOldRevision(paramGUI, paramGUI.mParent.g);
}
/** {@inheritDoc} */
@Override
void drawNewRevision(final SunburstGUI paramGUI) {
drawStaticNewRevision(paramGUI, paramGUI.mParent.g);
}
},
/** Draw into buffer. */
UPDATEBUFFER {
/** {@inheritDoc} */
@Override
void drawStrategy(final SunburstGUI paramGUI, final SunburstItem paramItem,
final EDrawSunburst paramDraw) {
paramDraw.drawStrategy(paramGUI, paramItem, this);
}
/** {@inheritDoc} */
@Override
void update(final SunburstGUI paramGUI, final SunburstItem paramItem) {
paramItem.update(paramGUI.getMappingMode(), paramGUI.mBuffer);
}
/** {@inheritDoc} */
@Override
void drawOldRevision(final SunburstGUI paramGUI) {
drawStaticOldRevision(paramGUI, paramGUI.mBuffer);
}
/** {@inheritDoc} */
@Override
void drawNewRevision(final SunburstGUI paramGUI) {
drawStaticNewRevision(paramGUI, paramGUI.mBuffer);
}
};
/**
* Drawing old revision ring.
*
* @param paramGUI
* {@link SunburstGUI} instance
* @param paramGraphic
* {@link PGraphics} instance
*/
private static void drawStaticOldRevision(final SunburstGUI paramGUI, final PGraphics paramGraphic) {
paramGraphic.pushMatrix();
final float arcRadius = calculateOldRadius(paramGUI, paramGraphic);
drawRevision(paramGUI, paramGraphic, arcRadius);
final String text = "revision " + paramGUI.mDb.getRevisionNumber();
draw(paramGUI, paramGraphic, text, arcRadius);
paramGraphic.popMatrix();
}
/**
* Drawing new revision ring.
*
* @param paramGUI
* {@link SunburstGUI} instance
* @param paramGraphic
* {@link PGraphics} instance
*/
private static void drawStaticNewRevision(final SunburstGUI paramGUI, final PGraphics paramGraphic) {
paramGraphic.pushMatrix();
final float arcRadius = calculateNewRadius(paramGUI, paramGraphic);
drawRevision(paramGUI, paramGraphic, arcRadius);
final String text = "revision " + paramGUI.mSelectedRev;
draw(paramGUI, paramGraphic, text, arcRadius);
paramGraphic.popMatrix();
}
/**
* Draw revision text.
*
* @param paramGUI
* {@link GUI} instance
* @param paramGraphic
* {@link PGraphics} instance
* @param paramItem
* {@link SunburstItem} instance
* @param paramRadius
* arc radius
*/
static void draw(final SunburstGUI paramGUI, final PGraphics paramGraphic, final String paramText,
final float paramArcRadius) {
// We must keep track of our position along the curve.
float arclength = 0;
// For every box
for (int i = 0; i < paramText.length(); i++) {
// Instead of a constant width, we check the width of each character.
final char currentChar = paramText.charAt(i);
final float w = 7f;// paramGUI.mParent.textWidth(currentChar);
// Each box is centered so we move half the width.
arclength += w / 2;
// Angle in radians is the arclength divided by the radius.
// Starting on the left side of the circle by adding PI.
final float theta = PConstants.PI + arclength / paramArcRadius;
if (paramGUI.mParent.recorder != null) {
paramGUI.mParent.recorder.pushMatrix();
// Polar to cartesian coordinate conversion.
paramGUI.mParent.recorder.translate(paramArcRadius * PApplet.cos(theta), paramArcRadius
* PApplet.sin(theta));
// Rotate the box.
paramGUI.mParent.recorder.rotate(theta + PConstants.PI / 2); // rotation is offset by 90
// degrees
// Display the character.
paramGUI.mParent.recorder.fill(0);
paramGUI.mParent.recorder.text(currentChar, 0, 0);
paramGUI.mParent.recorder.popMatrix();
}
paramGraphic.pushMatrix();
// Polar to cartesian coordinate conversion.
paramGraphic.translate(paramArcRadius * PApplet.cos(theta), paramArcRadius * PApplet.sin(theta));
// Rotate the box.
paramGraphic.rotate(theta + PConstants.PI / 2); // rotation is offset by 90 degrees
// Display the character.
paramGraphic.fill(0);
paramGraphic.text(currentChar, 0, 0);
paramGraphic.popMatrix();
// Move halfway again.
arclength += w / 2;
}
if (paramGUI.mParent.recorder != null) {
paramGUI.mParent.recorder.noFill();
}
paramGraphic.noFill();
}
/**
* Calculate radius.
*
* @param paramGUI
* {@link GUI} instance
* @param paramGraphic
* {@link PGraphics} instance
* @return calculated radius
*/
private static float calculateOldRadius(final SunburstGUI paramGUI, final PGraphics paramGraphic) {
final int revisionDepth = paramGUI.mOldDepthMax + 1;
final float radius = paramGUI.calcEqualAreaRadius(revisionDepth, paramGUI.mDepthMax);
final float depthWeight =
paramGUI.calcEqualAreaRadius(revisionDepth + 1, paramGUI.mDepthMax) - radius;
if (paramGUI.mParent.recorder != null) {
paramGUI.mParent.recorder.strokeWeight(depthWeight);
}
paramGraphic.strokeWeight(depthWeight);
return radius + depthWeight / 2;
}
/**
* Calculate radius.
*
* @param paramGUI
* {@link GUI} instance
* @param paramGraphic
* {@link PGraphics} instance
* @return calculated radius
*/
private static float calculateNewRadius(final SunburstGUI paramGUI, final PGraphics paramGraphic) {
final int revisionDepth = paramGUI.mDepthMax - 1;
final float radius = paramGUI.calcEqualAreaRadius(revisionDepth, paramGUI.mDepthMax);
final float depthWeight =
paramGUI.calcEqualAreaRadius(revisionDepth + 1, paramGUI.mDepthMax) - radius;
if (paramGUI.mParent.recorder != null) {
paramGUI.mParent.recorder.strokeWeight(depthWeight);
}
paramGraphic.strokeWeight(depthWeight);
return radius + depthWeight / 2;
}
/**
* Draw revision.
*
* @param paramGUI
* {@link SunburstGUI} instance
* @param paramGraphic
* {@link PGraphics} instance
* @param paramArcRadius
* arc radius
*/
private static void drawRevision(final SunburstGUI paramGUI, final PGraphics paramGraphic,
final float paramArcRadius) {
if (paramGUI.mParent.recorder != null) {
paramGUI.mParent.recorder.stroke(200f);
paramGUI.mParent.recorder.arc(0, 0, paramArcRadius, paramArcRadius, 0, 2 * PConstants.PI);
paramGUI.mParent.recorder.stroke(0f);
}
paramGraphic.stroke(200f);
paramGraphic.arc(0, 0, paramArcRadius, paramArcRadius, 0, 2 * PConstants.PI);
paramGraphic.stroke(0f);
}
/**
* Draw arc.
*
* @param paramGUI
* {@link GUI} instance
* @param paramItem
* {@link SunburstItem} instance
*/
protected void drawArc(final SunburstGUI paramGUI, final SunburstItem paramItem) {
if (paramGUI.mShowArcs) {
if (paramGUI.mUseArc) {
paramItem.drawArc(paramGUI.mInnerNodeArcScale, paramGUI.mLeafArcScale, EHover.FALSE);
} else {
paramItem.drawRect(paramGUI.mInnerNodeArcScale, paramGUI.mLeafArcScale, EHover.FALSE);
}
}
}
/**
* Draw relation line.
*
* @param paramGUI
* {@link GUI} instance
* @param paramItem
* {@link SunburstItem} instance
*/
protected void drawRelation(final SunburstGUI paramGUI, final SunburstItem paramItem) {
if (paramGUI.mShowLines) {
if (paramGUI.mUseBezierLine) {
paramItem.drawRelationBezier();
} else {
paramItem.drawRelationLine();
}
}
}
/**
* Draw dot.
*
* @param paramGUI
* {@link GUI} instance
* @param paramItem
* {@link SunburstItem} instance
*/
protected void drawDot(final SunburstGUI paramGUI, final SunburstItem paramItem) {
paramItem.drawDot(EHover.FALSE);
}
/**
* Update a {@link SunburstItem}.
*
* @param paramGUI
* {@link SunburstGUI} reference
* @param paramItem
* {@link SunburstItem} to update
*/
abstract void update(final SunburstGUI paramGUI, final SunburstItem paramItem);
/**
* Drawing strategy.
*
* @param paramGUI
* {@link SunburstGUI} instance
* @param paramItem
* {@link SunburstItem} to draw
*/
abstract void drawStrategy(final SunburstGUI paramGUI, final SunburstItem paramItem,
final EDrawSunburst paramDraw);
/**
* Draw old revision ring.
*
* @param paramGUI
* {@link SunburstGUI} instance
*/
abstract void drawOldRevision(final SunburstGUI paramGUI);
/**
* Draw new revision ring.
*
* @param paramGUI
* {@link SunburstGUI} instance
*/
abstract void drawNewRevision(final SunburstGUI paramGUI);
/** Determines how to draw. */
public enum EDrawSunburst {
/** Normal sunburst view. */
NORMAL {
/** {@inheritDoc} */
@Override
void
drawStrategy(final SunburstGUI paramGUI, final SunburstItem paramItem, final EDraw paramDraw) {
paramDraw.drawArc(paramGUI, paramItem);
paramDraw.drawRelation(paramGUI, paramItem);
paramDraw.drawDot(paramGUI, paramItem);
}
},
/** Compare sunburst view. */
COMPARE {
/** {@inheritDoc} */
@Override
void
drawStrategy(final SunburstGUI paramGUI, final SunburstItem paramItem, final EDraw paramDraw) {
paramDraw.drawArc(paramGUI, paramItem);
}
};
/**
* Drawing strategy.
*
* @param paramGUI
* {@link SunburstGUI} instance
* @param paramItem
* {@link SunburstItem} to draw
*/
abstract void drawStrategy(final SunburstGUI paramGUI, final SunburstItem paramItem,
final EDraw paramDraw);
}
}
|
package org.chargecar.lcddisplay.helpers;
/**
* @author Paul Dille (pdille@andrew.cmu.edu)
*/
import org.apache.log4j.Logger;
import java.sql.*;
import java.util.*;
public class PostgesConnect {
private static final Logger LOG = Logger.getLogger(PostgesConnect.class);
private Connection conn = null;
private Map<String, Integer> tables = new HashMap<String, Integer>(); //[tableName, numColums]
private static final String database = "template_postgis15";
private static final String databaseUserName = "postgres";
private static final String databasePassword = "test";
public PostgesConnect() {
// connect to the database
LOG.trace("Connecting to postgres db....");
this.conn = connectToDatabaseOrDie();
LOG.trace("Connected to postgres db....");
LOG.trace("Getting information about each table....");
//get table names and number of columns in each table
getTableInfo();
}
public List<List> makeQuery(final Connection conn, final String tableName, final String statement) {
if (conn == null || tables.get(tableName) == null || statement == null) return null;
return makeQuery(conn, tables.get(tableName), statement);
}
public List<List> makeQuery(final Connection conn, final int numCols, final String statement) {
if (conn == null || statement == null) return null;
final List<List> results = new ArrayList<List>();
try {
final Statement st = conn.createStatement();
final ResultSet rs = st.executeQuery(statement);
final List<String> columns = new ArrayList<String>(numCols);
while (rs.next()) {
for (int i = 0; i < numCols; i++)
columns.add(rs.getString(i + 1)); //db starts numbering at 1
results.add(columns);
}
rs.close();
st.close();
} catch (SQLException se) {
LOG.error("Threw a SQLException while creating a list of the query results: " + se);
}
return results;
}
private Connection connectToDatabaseOrDie() {
Connection tmpConn = null;
try {
Class.forName("org.postgresql.Driver"); //ensure the jdbc driver exists in path
final String url = "jdbc:postgresql://localhost/"+database;
tmpConn = DriverManager.getConnection(url, databaseUserName, databasePassword);
} catch (ClassNotFoundException e) {
LOG.trace(e);
System.exit(1);
} catch (SQLException e) {
LOG.trace(e);
System.exit(2);
}
return tmpConn;
}
private void getTableInfo() {
try {
final Statement st = conn.createStatement();
final ResultSet rs = st.executeQuery("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';");
while (rs.next()) {
final String tableName = rs.getString("table_name");
final Statement st2 = conn.createStatement();
final ResultSet rs2 = st2.executeQuery("select count(*) from information_schema.columns where table_name=" + "'" + tableName + "'" + ";");
while (rs2.next()) {
tables.put(tableName, rs2.getInt("count"));
}
rs2.close();
st2.close();
}
rs.close();
st.close();
} catch (SQLException se) {
LOG.error("Threw a SQLException while creating the list of table info: " + se);
}
}
public Connection getConn() {
return conn;
}
}
|
package com.dianping.cat.report.page.cross;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.dal.jdbc.DalException;
import org.unidal.helper.Threads;
import org.unidal.helper.Threads.Task;
import org.unidal.lookup.annotation.Inject;
import org.unidal.webres.helper.Files;
import org.unidal.webres.json.JsonArray;
import org.unidal.webres.json.JsonObject;
import com.dainping.cat.consumer.core.dal.Hostinfo;
import com.dainping.cat.consumer.core.dal.HostinfoDao;
import com.dainping.cat.consumer.core.dal.HostinfoEntity;
import com.dianping.cat.Cat;
import com.dianping.cat.configuration.ServerConfigManager;
public class DomainManager implements Initializable, LogEnabled {
@Inject
private HostinfoDao m_hostInfoDao;
@Inject
private ServerConfigManager m_manager;
private Map<String, String> m_ipDomains = new ConcurrentHashMap<String, String>();
private Set<String> m_unknownIps = new HashSet<String>();
private Map<String, String> m_cmdbs = new ConcurrentHashMap<String, String>();
private Logger m_logger;
private static final String UNKNOWN_PROJECT = "UnknownProject";
private static final String CMDB_URL = "http://cmdb.dp/cmdb/device/s?q=%s&fl=app&tidy=true";
@Override
public void enableLogging(Logger logger) {
m_logger = logger;
}
public String getDomainByIp(String ip) {
String project = m_ipDomains.get(ip);
if (project == null) {
project = m_cmdbs.get(ip);
if (project == null) {
m_unknownIps.add(ip);
return UNKNOWN_PROJECT;
}
}
return project;
}
@Override
public void initialize() throws InitializationException {
if (!m_manager.isLocalMode()) {
try {
List<Hostinfo> infos = m_hostInfoDao.findAllIp(HostinfoEntity.READSET_FULL);
for (Hostinfo info : infos) {
m_ipDomains.put(info.getIp(), info.getDomain());
}
} catch (DalException e) {
Cat.logError(e);
}
Threads.forGroup("Cat").start(new ReloadDomainTask());
}
}
public class ReloadDomainTask implements Task {
@Override
public String getName() {
return "Reload-Ip-DomainInfo";
}
public String parseIp(String content) throws Exception {
JsonObject object = new JsonObject(content);
JsonArray array = object.getJSONArray("app");
if (array.length() > 0) {
return array.getString(0);
}
return null;
}
private void queryFromCMDB() {
Set<String> addIps = new HashSet<String>();
synchronized (m_unknownIps) {
for (String ip : m_unknownIps) {
try {
String cmdb = String.format(CMDB_URL, ip);
URL url = new URL(cmdb);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int nRc = conn.getResponseCode();
if (nRc == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
String content = Files.forIO().readFrom(input, "utf-8");
String domain = parseIp(content.trim());
if (domain != null) {
m_cmdbs.put(ip, domain);
addIps.add(ip);
m_logger.info(String.format("get domain info from cmdb. ip: %s,domain: %s", ip, domain));
} else {
m_logger.error(String.format("can't get domain info from cmdb, ip: %s", ip));
}
}
} catch (Exception e) {
Cat.logError(e);
}
for (String temp : addIps) {
m_unknownIps.remove(temp);
}
}
}
}
private void queryFromDatabase() {
Set<String> addIps = new HashSet<String>();
synchronized (m_unknownIps) {
for (String ip : m_unknownIps) {
try {
Hostinfo hostinfo = m_hostInfoDao.findByIp(ip, HostinfoEntity.READSET_FULL);
addIps.add(hostinfo.getIp());
m_ipDomains.put(hostinfo.getIp(), hostinfo.getDomain());
} catch (Exception e) {
// ignore
}
}
for (String ip : addIps) {
m_unknownIps.remove(ip);
}
}
}
@Override
public void run() {
boolean active = true;
while (active) {
try {
queryFromDatabase();
queryFromCMDB();
} catch (Throwable e) {
Cat.logError(e);
}
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
active = false;
}
}
}
@Override
public void shutdown() {
}
}
}
|
package catan.client.ui.serverconnectmenu;
import catan.client.graphics.masks.RectangularMask;
import catan.client.graphics.masks.RenderMask;
import catan.client.graphics.masks.RoundedRectangularMask;
import catan.client.graphics.ui.*;
import catan.client.input.UserEvent;
import catan.client.input.UserEventListener;
import catan.client.input.UserEventType;
import catan.client.structure.ConnectionInfo;
import catan.client.structure.ServerPool;
import catan.client.ui.ClientScreen;
import catan.client.ui.PopupWindow;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
public class ServerConnectMenu extends ClientScreen {
private RenderMask serverSize;
private RenderMask footerSize;
private int spacing;
private final ServerPool serverPool;
private ConnectionInfo selected;
private final TiledBackground background;
private final ScrollingScreenContainer scroll;
private final ServerListFooter footer;
private ServerDetailPopup editPopup;
public ServerConnectMenu(ServerPool serverPool) {
super("ConnectMenu", "connect");
//Store instance information
this.serverPool = serverPool;
selected = null;
//Create sub-regions
background = new EdgedTiledBackground();
scroll = new ScrollingScreenContainer("ServerScroll", 1, new ServerList());
scroll.enableTransparency();
footer = new ServerListFooter();
//Add everything to the screen.
add(background).setClickable(this);
add(scroll);
add(footer);
}
@Override
protected void resizeContents(RenderMask mask) {
//Resize the background region
background.setMask(mask);
//Resize the server list scroll.
Dimension scrollSize = new Dimension(serverSize.getWidth(), mask.getHeight() - footerSize.getHeight() - 2*spacing);
scroll.setMask(new RectangularMask(scrollSize));
scroll.setInsets(new Insets(0,0,0,0));
//Resize the existing footer
footer.setMask(footerSize);
}
@Override
protected void renderContents() {
center(scroll).y = spacing;
center(footer).y = getMask().getHeight() - footerSize.getHeight();
}
@Override
public void loadConfig(UIConfig config) {
serverSize = new RoundedRectangularMask(config.getLayout().getDimension("list.mask.size"));
footerSize = new RoundedRectangularMask(config.getLayout().getDimension("footer"));
spacing = config.getLayout().getInt("spacing");
}
@Override
public void update() {
scroll.update();
}
private class ServerList extends ScrollingList {
private ServerList() {
super("ServerList", 1, "list");
}
@Override
public void loadConfig(UIConfig config) {
setElementSize(RenderMask.parseMask(config.getLayout().narrow("mask")));
}
@Override
public void onMouseDrag(UserEventListener listener, Point p) {
scroll(0, p.y);
}
@Override
public void onMouseScroll(UserEventListener listener, MouseWheelEvent event) {
scroll(0, 4 * event.getUnitsToScroll());
}
@Override
public void update() {
forceRender();
}
@Override
protected void renderContents() {
//Completely re-render all children
clear();
//TODO: selection logic should not depend on the rendering.
selected = null;
for (ConnectionInfo elt : serverPool)
add(new Element(elt));
super.renderContents();
}
private class Element extends ConfigurableScreenRegion {
private final ConnectionInfo info;
private final TiledBackground background;
private final TextLabel address;
private final TextLabel login;
private Element(ConnectionInfo info) {
super("Element", 1, "item");
this.info = info;
//Create all of the screen objects.
background = new EdgedTiledBackground();
address = new TextLabel("AddressText", 1, "address", "Remote Address : " + info.getHostname() + ":" + info.getPort());
login = new TextLabel("LoginText", 2, "login", "Username: " + info.getUsername());
//Add everything to the screen.
add(login).setClickable(this);
add(background).setClickable(this);
add(address).setClickable(this);
}
@Override
protected void resizeContents(RenderMask mask) {
background.setMask(mask);
address.setPosition(new Point(16, 16));
login.setPosition(new Point(16, 40));
}
@Override
public void onMouseClick(UserEventListener listener, MouseEvent event) {
selected = info;
}
@Override
public void onMouseScroll(UserEventListener listener, MouseWheelEvent event) {
ServerList.this.onMouseScroll(listener, event);
}
@Override
public void onMouseDrag(UserEventListener listener, Point p) {
ServerList.this.onMouseDrag(listener, p);
}
}
}
private class ServerListFooter extends ConfigurableScreenRegion {
private final TiledBackground background;
private final catan.client.graphics.ui.Button newButton;
private final catan.client.graphics.ui.Button editButton;
private final catan.client.graphics.ui.Button connectButton;
private final TextBox passwordBox;
private ServerListFooter() {
super("Footer", 2, "footer");
background = new EdgedTiledBackground();
newButton = new catan.client.graphics.ui.Button("NewButton", 1, "new", "New") {
@Override
public void onMouseClick(UserEventListener listener, MouseEvent event) {
detail(null);
}
};
editButton = new catan.client.graphics.ui.Button("EditButton", 1, "edit", "Edit") {
@Override
public void onMouseClick(UserEventListener listener, MouseEvent event) {
if (selected != null) detail(selected);
}
};
connectButton = new catan.client.graphics.ui.Button("ConenctButton", 1, "connect", "Connect") {
@Override
public void onMouseClick(UserEventListener listener, MouseEvent event) {
connect(listener);
}
};
passwordBox = new TextBox("PasswordBox", 1, "password", "Password", false) {
@Override
public void onAccept(UserEventListener listener) {
connect(listener);
}
};
//Add the objects to the screen
add(background).setClickable(this);
add(newButton);
add(editButton);
add(connectButton);
add(passwordBox);
}
private void detail(ConnectionInfo selected) {
if (editPopup == null) {
editPopup = new ServerDetailPopup(selected);
editPopup.display();
}
}
private void connect(UserEventListener listener) {
if (selected != null) {
serverPool.top(selected);
//TODO: should this be here?
scroll.update();
selected.setPassword(passwordBox.getText());
listener.onUserEvent(new UserEvent(this, UserEventType.Net_Connect, selected));
}
}
@Override
protected void resizeContents(RenderMask mask) {
background.setMask(mask);
}
}
private class ServerDetailPopup extends PopupWindow {
private final ConnectionInfo server;
private final TiledBackground background;
private final TextBox hostname;
private final TextBox port;
private final TextBox username;
private final catan.client.graphics.ui.Button saveButton;
private final catan.client.graphics.ui.Button deleteButton;
private final catan.client.graphics.ui.Button cancelButton;
private ServerDetailPopup(ConnectionInfo server) {
super("ServerDetails", "serverdetail", ServerConnectMenu.this);
this.server = server;
background = new EdgedTiledBackground();
hostname = new TextBox("HostnameBox", 1, "hostname" ,(server == null) ? "Hostname" : server.getHostname(), server != null) {
@Override
protected void onAccept(UserEventListener listener) {
submit(listener);
}
};
port = new TextBox("PortBox", 1, "port" ,(server == null) ? "Port" : server.getPort(), server != null) {
@Override
protected void onAccept(UserEventListener listener) {
submit(listener);
}
};
username = new TextBox("UsernameBox", 1, "username" ,(server == null) ? "Username" : server.getUsername(), server != null) {
@Override
protected void onAccept(UserEventListener listener) {
submit(listener);
}
};
saveButton = new catan.client.graphics.ui.Button("SaveButton", 1, "save", "Save") {
@Override
public void onMouseClick(UserEventListener listener, MouseEvent event) {
submit(listener);
}
};
deleteButton = new catan.client.graphics.ui.Button("DeleteButton", 1, "delete", "Delete") {
@Override
public void onMouseClick(UserEventListener listener, MouseEvent event) {
delete(listener);
}
};
cancelButton = new catan.client.graphics.ui.Button("CancelButton", 1, "cancel", "Cancel") {
@Override
public void onMouseClick(UserEventListener listener, MouseEvent event) {
expire();
}
};
add(background).setClickable(this);
add(hostname);
add(port);
add(username);
add(saveButton);
add(deleteButton);
add(cancelButton);
}
@Override
public void expire() {
editPopup = null;
super.expire();
}
private void delete(UserEventListener listener) {
listener.onUserEvent(new UserEvent(this, UserEventType.Server_Remove, server));
expire();
}
private void submit(UserEventListener listener) {
String hostnameText = hostname.getText();
String portText = port.getText();
String usernameText = username.getText();
ConnectionInfo newInfo = new ConnectionInfo(hostnameText, portText, usernameText);
if (!newInfo.equals(server) && hostnameText.length() > 0 && portText.length() > 0 && usernameText.length() >0) {
listener.onUserEvent(new UserEvent(this, UserEventType.Server_Remove, server));
listener.onUserEvent(new UserEvent(this, UserEventType.Server_Add, newInfo));
}
expire();
}
@Override
public void loadConfig(UIConfig config) {
setMask(RenderMask.parseMask(config.getLayout().narrow("mask")));
}
@Override
public void update() {
}
}
}
|
package br.unb.unbomber.systems;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import br.un.unbomber.components.Transform;
import br.un.unbomber.components.Visual;
import br.unb.bomberman.ui.screens.ScreenDimensions;
import br.unb.unbomber.component.CellPlacement;
import br.unb.unbomber.component.Draw;
import br.unb.unbomber.component.Movable;
import br.unb.unbomber.core.BaseSystem;
import br.unb.unbomber.core.Component;
import br.unb.unbomber.core.Entity;
import br.unb.unbomber.core.EntityManager;
import br.unb.unbomber.gridphysics.Vector2D;
import br.unb.unbomber.ui.skin.LoadTexture;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
public class RenderSystem extends BaseSystem {
private OrthographicCamera cam;
private Array<Entity> renderQueue;
private Comparator<Entity> comparator;
SpriteBatch batch;
private ScreenDimensions screenDimensions;
public RenderSystem(EntityManager entityManager) {
super(entityManager);
}
public RenderSystem(EntityManager entityManager,
SpriteBatch batch) {
super(entityManager);
this.batch = batch;
comparator = new Comparator<Entity>() {
@Override
public int compare(Entity entityA, Entity entityB) {
return (int)Math.signum(getY(entityB) - getY(entityA));
}
private int getY(Entity entityA) {
CellPlacement placement = (CellPlacement)getEntityManager().getComponent(CellPlacement.class, entityA.getEntityId());
return placement.getCellY();
}
};
this.batch = batch;
}
@Override
public void start() {
screenDimensions = new ScreenDimensions();
cam = new OrthographicCamera();
cam.setToOrtho(false, screenDimensions.getScreenWidth(), screenDimensions.getScreenHeight());
}
@Override
public void update() {
LoadTexture.load(getEntityManager());
List<Component> renderQueue = new ArrayList<Component>();
renderQueue.addAll(getEntityManager().getComponents(Visual.class));
//renderQueue.sort(comparator);
cam.update();
batch.setProjectionMatrix(cam.combined);
for (Component visComponent : renderQueue) {
Visual vis = (Visual) visComponent;
if (vis.getRegion() == null) {
continue;
}
CellPlacement cellPlacement = (CellPlacement) getEntityManager().getComponent(CellPlacement.class, vis.getEntityId());
if(cellPlacement==null){
Draw draw = (Draw) getEntityManager().getComponent(Draw.class, vis.getEntityId());
//LOGGER.log(Level.SEVERE, "trying to draw a "+ draw.getType() +"\n But it has not a placement");
continue;
}
Vector2D<Float> screenPosition;
float width = vis.getRegion().getRegionWidth();
float height = vis.getRegion().getRegionHeight();
Movable movable = (Movable) getEntityManager().getComponent(Movable.class, vis.getEntityId());
if(movable==null){
screenPosition = gridPositionToScreenPosition(cellPlacement.centerPosition(),
vis.getTransform(), width,height );
}else{
screenPosition = gridPositionToScreenPosition(cellPlacement.centerPosition(),
vis.getTransform(), width,height, movable);
}
Transform t = vis.getTransform();
float originX = width * 0.5f;
float originY = height * 0.5f;
// batch.draw(vis.getRegion(),
// screenPosition.getX(),
// screenPosition.getY());
batch.draw(vis.getRegion(),
screenPosition.getX(),
screenPosition.getY(),
originX, originY,
width, height,
t.scalex, t.scaley,
MathUtils.radiansToDegrees * t.rotation);
}
renderQueue.clear();
}
public void processEntity(Entity entity) {
renderQueue.add(entity);
}
public OrthographicCamera getCamera() {
return cam;
}
public Visual getVisual(Entity entity){
Visual visual = (Visual)getEntityManager().getComponent(Visual.class, entity.getEntityId());
return visual;
}
/**
* Method that convert a cell placement from grid reference to screen position.
*
* GridRef -> Up-Down, Left-Right, 1 cell mesure 1.0f u.m.
* ScreenRef -> Down-Up, Left-Right, 1 cell 32 pix
*
* Do linear transformation:
*
* - get the center of the cell
* - rebase to the screen origin (left, down)
* - scale to the configured num pix / cell
* @param cellPlacement
* @return
*/
public Vector2D<Float> gridPositionToScreenPosition(Vector2D<Float> gridRef,
Transform gameTranformation, float width, float height ){
//(0,-1) - invert y axe
Vector2D<Float> orient = new Vector2D<Float>(1.0f, -1.0f);
Vector2D<Float> bringToTheBorder = new Vector2D<Float>(0.0f, -0.5f*screenDimensions.getCellSize());
Vector2D<Float> moveUp = new Vector2D<Float>(0.0f, (float)(screenDimensions.getScreenHeight() - screenDimensions.getHudHeight()) );
float scale = screenDimensions.getCellSize();
Vector2D<Float> repositeTheCenter = new Vector2D<Float>(-0.5f * width, -0.5f * height);
/** Transformations for the game */
Vector2D<Float> gameTransSum = new Vector2D<Float>(gameTranformation.dx, gameTranformation.dy);
return gridRef.mult(orient)//.add(bringToTheBorder)
.mult(scale)
.add(moveUp)//.add(transformC)
.add(gameTransSum)
.add(repositeTheCenter);
}
public Vector2D<Float> gridPositionToScreenPosition(Vector2D<Float> gridRef,
Transform gameTranformation, float width, float height, Movable movable){
/** Transformations for the movement inside a cell */
gridRef = gridRef.add(movable.getCellDisplacement());
return gridPositionToScreenPosition(gridRef,
gameTranformation, width,height );
}
}
|
package com.hadooparchitecturebook;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.ObjectUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* This is the main class that is responsible for doing sessionization in MapReduce
*/
public class MRSessionize {
private static final String LOG_RECORD_REGEX =
"(\\d+.\\d+.\\d+.\\d+).*\\[(.*) \\].*GET (\\S*).*\\d+ \\d+ (\\S+) \\\"(.*)\\\"";
private static final Pattern logRecordPattern = Pattern.compile(LOG_RECORD_REGEX);
private static final String TIMESTAMP_PATTERN = "dd/MMM/yyyy:HH:mm:ss";
private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormat.forPattern(TIMESTAMP_PATTERN);
// In our sessionization algorithm, a session expires in 30 minutes. Another click from the same user after 30 or
// more minutes is a part of a new session
private static final int SESSION_TIMEOUT_IN_MINUTES = 30;
private static final int SESSION_TIMEOUT_IN_MS = SESSION_TIMEOUT_IN_MINUTES * 60 * 1000;
/**
* Mapper class used in Sessionization
*/
public static class SessionizeMapper
extends Mapper<Object, Text, IpTimestampKey, Text> {
private Matcher logRecordMatcher;
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
logRecordMatcher = logRecordPattern.matcher(value.toString());
// We only emit something out if the record matches with our regex. Otherwise, we assume the record is
// busted and simply ignore it
if (logRecordMatcher.matches()) {
String ip = logRecordMatcher.group(1);
DateTime timestamp = DateTime.parse(logRecordMatcher.group(2), TIMESTAMP_FORMATTER);
Long unixTimestamp = timestamp.getMillis();
IpTimestampKey outputKey = new IpTimestampKey(ip, unixTimestamp);
context.write(outputKey, value);
}
}
}
// TODO: NEED TO BUNDLE JODA TIME IN ASSEMBLY
/**
* Reducer class used in Sessionization
*/
public static class SessionizeReducer
extends Reducer<IpTimestampKey, Text, IpTimestampKey, Text> {
private Text result = new Text();
// TODO: This doesn't work. Use UUID? Use 12 digits of IP address + a counter?
private static int sessionId = 0;
private Long lastTimeStamp = null;
public void reduce(IpTimestampKey key, Iterable<Text> values,
Context context
) throws IOException, InterruptedException {
for (Text value : values) {
String logRecord = value.toString();
// If this is the first record for this user or it's been more than the timeout since
// the last click from this user, let's increment the session ID.
if (lastTimeStamp == null || (key.getUnixTimestamp() - lastTimeStamp > SESSION_TIMEOUT_IN_MS)) {
sessionId++;
}
lastTimeStamp = key.getUnixTimestamp();
result.set(logRecord + " " + sessionId);
// Since we only care about printing out the entire record in the result, with session ID appended
// at the end, we just emit out "null" for the key
context.write(null, result);
}
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: MRSessionize <in> <out>");
System.exit(2);
}
Job job = new Job(conf, "MapReduce Sessionization");
job.setJarByClass(MRSessionize.class);
job.setMapperClass(SessionizeMapper.class);
job.setReducerClass(SessionizeReducer.class);
// WARNING: do NOT set the Combiner class
// from the same IP in one place before we can do sessionization
// Also, our reducer doesn't return the same key,value types it takes
// It can't be used on the result of a previous reducer
job.setMapOutputKeyClass(IpTimestampKey.class);
job.setMapOutputValueClass(Text.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(Text.class);
// We need these for secondary sorting.
// We need to shuffle the records (between Map and Reduce phases) by using IP address as key, since that is
// the field we are using for determining uniqueness of users. However, when the records arrive to the reducers,
// we would like them to be sorted in ascending order of their timestamps. This concept is known as secondary
// sorting since we are "secondarily" sorting the records by another key (timestamp, in our case) in addition
// to the shuffle key (also called the "partition" key).
// So, to get some terminology straight.
// Natural key (aka Shuffle key or Partition key) is the key we use to shuffle. IP address in our case
// Secondary Sorting Key is the key we use to sort within each partition that gets sent to the user. Timestamp
// in our case.
// Together, the natural key and secondary sorting key form what we call the composite key. This key is called
// IpTimestampKey in our example.
// For secondary sorting, even though we are partitioning and shuffling by only the natural key, the map output
// key and the reduce input key is the composite key. We, however, use a custom partitioner and custom grouping
// comparator that only uses the natural key part of the composite key to partition and group respectively (both
// happen during the shuffle phase).
// However, we have a different sort comparator which also gets used in the shuffle phase but determines how
// the records are sorted when they enter the reduce phase. This custom sort comparator in our case will make use
// of the entire composite key.
// to be very helpful, if you'd like to read more on the subject.
job.setPartitionerClass(NaturalKeyPartitioner.class);
job.setGroupingComparatorClass(NaturalKeyComparator.class);
job.setSortComparatorClass(CompositeKeyComparator.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
|
package bisq.core.util;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.CurrencyUtil;
import bisq.core.locale.GlobalSettings;
import bisq.core.locale.LanguageUtil;
import bisq.core.locale.Res;
import bisq.core.monetary.Altcoin;
import bisq.core.monetary.Price;
import bisq.core.monetary.Volume;
import bisq.core.offer.Offer;
import bisq.core.offer.OfferPayload;
import bisq.network.p2p.NodeAddress;
import bisq.common.util.MathUtils;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Monetary;
import org.bitcoinj.utils.Fiat;
import org.bitcoinj.utils.MonetaryFormat;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.DurationFormatUtils;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
@Slf4j
public class BSFormatter {
public final static String RANGE_SEPARATOR = " - ";
protected boolean useMilliBit;
protected int scale = 3;
// We don't support localized formatting. Format is always using "." as decimal mark and no grouping separator.
// Input of "," as decimal mark (like in german locale) will be replaced with ".".
// Input of a group separator (1,123,45) lead to an validation error.
// Note: BtcFormat was intended to be used, but it lead to many problems (automatic format to mBit,
// no way to remove grouping separator). It seems to be not optimal for user input formatting.
protected MonetaryFormat coinFormat;
// protected String currencyCode = CurrencyUtil.getDefaultFiatCurrencyAsCode();
protected final MonetaryFormat fiatPriceFormat = new MonetaryFormat().shift(0).minDecimals(4).repeatOptionalDecimals(0, 0);
protected final MonetaryFormat fiatVolumeFormat = new MonetaryFormat().shift(0).minDecimals(2).repeatOptionalDecimals(0, 0);
protected final MonetaryFormat altcoinFormat = new MonetaryFormat().shift(0).minDecimals(8).repeatOptionalDecimals(0, 0);
protected final DecimalFormat decimalFormat = new DecimalFormat("
@Inject
public BSFormatter() {
coinFormat = BisqEnvironment.getParameters().getMonetaryFormat();
}
// BTC
public String formatCoin(Coin coin) {
return formatCoin(coin, -1);
}
@NotNull
public String formatCoin(Coin coin, int decimalPlaces) {
return formatCoin(coin, decimalPlaces, false, 0);
}
public String formatCoin(long value, MonetaryFormat coinFormat) {
return formatCoin(Coin.valueOf(value), -1, false, 0, coinFormat);
}
public String formatCoin(Coin coin, int decimalPlaces, boolean decimalAligned, int maxNumberOfDigits) {
return formatCoin(coin, decimalPlaces, decimalAligned, maxNumberOfDigits, coinFormat);
}
public String formatCoin(Coin coin, int decimalPlaces, boolean decimalAligned, int maxNumberOfDigits, MonetaryFormat coinFormat) {
String formattedCoin = "";
if (coin != null) {
try {
if (decimalPlaces < 0 || decimalPlaces > 4) {
formattedCoin = coinFormat.noCode().format(coin).toString();
} else {
formattedCoin = coinFormat.noCode().minDecimals(decimalPlaces).repeatOptionalDecimals(1, decimalPlaces).format(coin).toString();
}
} catch (Throwable t) {
log.warn("Exception at formatBtc: " + t.toString());
}
}
if (decimalAligned) {
formattedCoin = fillUpPlacesWithEmptyStrings(formattedCoin, maxNumberOfDigits);
}
return formattedCoin;
}
public String formatCoinWithCode(Coin coin) {
return formatCoinWithCode(coin, coinFormat);
}
public String formatCoinWithCode(long value) {
return formatCoinWithCode(Coin.valueOf(value), coinFormat);
}
public String formatCoinWithCode(long value, MonetaryFormat coinFormat) {
return formatCoinWithCode(Coin.valueOf(value), coinFormat);
}
public String formatCoinWithCode(Coin coin, MonetaryFormat coinFormat) {
if (coin != null) {
try {
// we don't use the code feature from coinFormat as it does automatic switching between mBTC and BTC and
// pre and post fixing
return coinFormat.postfixCode().format(coin).toString();
} catch (Throwable t) {
log.warn("Exception at formatBtcWithCode: " + t.toString());
return "";
}
} else {
return "";
}
}
public Coin parseToCoin(String input) {
return parseToCoin(input, coinFormat);
}
public Coin parseToCoin(String input, MonetaryFormat coinFormat) {
if (input != null && input.length() > 0) {
try {
return coinFormat.parse(cleanDoubleInput(input));
} catch (Throwable t) {
log.warn("Exception at parseToBtc: " + t.toString());
return Coin.ZERO;
}
} else {
return Coin.ZERO;
}
}
/**
* Converts to a coin with max. 4 decimal places. Last place gets rounded.
* 0.01234 -> 0.0123
* 0.01235 -> 0.0124
*
* @param input
* @return
*/
public Coin parseToCoinWith4Decimals(String input) {
try {
return Coin.valueOf(new BigDecimal(parseToCoin(cleanDoubleInput(input)).value).setScale(-scale - 1,
BigDecimal.ROUND_HALF_UP).setScale(scale + 1, BigDecimal.ROUND_HALF_UP).toBigInteger().longValue());
} catch (Throwable t) {
if (input != null && input.length() > 0)
log.warn("Exception at parseToCoinWith4Decimals: " + t.toString());
return Coin.ZERO;
}
}
public boolean hasBtcValidDecimals(String input) {
return parseToCoin(input).equals(parseToCoinWith4Decimals(input));
}
/**
* Transform a coin with the properties defined in the format (used to reduce decimal places)
*
* @param coin The coin which should be transformed
* @return The transformed coin
*/
public Coin reduceTo4Decimals(Coin coin) {
return parseToCoin(formatCoin(coin));
}
// FIAT
public String formatFiat(Fiat fiat, MonetaryFormat format, boolean appendCurrencyCode) {
if (fiat != null) {
try {
final String res = format.noCode().format(fiat).toString();
if (appendCurrencyCode)
return res + " " + fiat.getCurrencyCode();
else
return res;
} catch (Throwable t) {
log.warn("Exception at formatFiatWithCode: " + t.toString());
return Res.get("shared.na") + " " + fiat.getCurrencyCode();
}
} else {
return Res.get("shared.na");
}
}
protected Fiat parseToFiat(String input, String currencyCode) {
if (input != null && input.length() > 0) {
try {
return Fiat.parseFiat(currencyCode, cleanDoubleInput(input));
} catch (Exception e) {
log.warn("Exception at parseToFiat: " + e.toString());
return Fiat.valueOf(currencyCode, 0);
}
} else {
return Fiat.valueOf(currencyCode, 0);
}
}
/**
* Converts to a fiat with max. 2 decimal places. Last place gets rounded.
* 0.234 -> 0.23
* 0.235 -> 0.24
*
* @param input
* @return
*/
public Fiat parseToFiatWithPrecision(String input, String currencyCode) {
if (input != null && input.length() > 0) {
try {
return parseToFiat(new BigDecimal(cleanDoubleInput(input)).setScale(2, BigDecimal.ROUND_HALF_UP).toString(),
currencyCode);
} catch (Throwable t) {
log.warn("Exception at parseToFiatWithPrecision: " + t.toString());
return Fiat.valueOf(currencyCode, 0);
}
}
return Fiat.valueOf(currencyCode, 0);
}
public boolean isFiatAlteredWhenPrecisionApplied(String input, String currencyCode) {
return parseToFiat(input, currencyCode).equals(parseToFiatWithPrecision(input, currencyCode));
}
// Altcoin
public String formatAltcoin(Altcoin altcoin) {
return formatAltcoin(altcoin, false);
}
public String formatAltcoinWithCode(Altcoin altcoin) {
return formatAltcoin(altcoin, true);
}
public String formatAltcoin(Altcoin altcoin, boolean appendCurrencyCode) {
if (altcoin != null) {
try {
String res = altcoinFormat.noCode().format(altcoin).toString();
if (appendCurrencyCode)
return res + " " + altcoin.getCurrencyCode();
else
return res;
} catch (Throwable t) {
log.warn("Exception at formatAltcoin: " + t.toString());
return Res.get("shared.na") + " " + altcoin.getCurrencyCode();
}
} else {
return Res.get("shared.na");
}
}
// Volume
public String formatVolume(Offer offer, Boolean decimalAligned, int maxNumberOfDigits) {
return formatVolume(offer, decimalAligned, maxNumberOfDigits, true);
}
public String formatVolume(Offer offer, Boolean decimalAligned, int maxNumberOfDigits, boolean showRange) {
String formattedVolume = offer.isRange() && showRange ? formatVolume(offer.getMinVolume()) + RANGE_SEPARATOR + formatVolume(offer.getVolume()) : formatVolume(offer.getVolume());
if (decimalAligned) {
formattedVolume = fillUpPlacesWithEmptyStrings(formattedVolume, maxNumberOfDigits);
}
return formattedVolume;
}
@NotNull
public String fillUpPlacesWithEmptyStrings(String formattedNumber, int maxNumberOfDigits) {
//FIXME: temporary deactivate adding spaces in front of numbers as we don't use a monospace font right now.
/*int numberOfPlacesToFill = maxNumberOfDigits - formattedNumber.length();
for (int i = 0; i < numberOfPlacesToFill; i++) {
formattedNumber = " " + formattedNumber;
}*/
return formattedNumber;
}
public String formatVolume(Volume volume) {
return formatVolume(volume, fiatVolumeFormat, false);
}
public String formatVolumeWithCode(Volume volume) {
return formatVolume(volume, fiatVolumeFormat, true);
}
public String formatVolume(Volume volume, MonetaryFormat fiatVolumeFormat, boolean appendCurrencyCode) {
if (volume != null) {
Monetary monetary = volume.getMonetary();
if (monetary instanceof Fiat)
return formatFiat((Fiat) monetary, fiatVolumeFormat, appendCurrencyCode);
else
return formatAltcoinVolume((Altcoin) monetary, appendCurrencyCode);
} else {
return "";
}
}
public String formatAltcoinVolume(Altcoin altcoin, boolean appendCurrencyCode) {
if (altcoin != null) {
try {
// TODO quick hack...
String res;
if (altcoin.getCurrencyCode().equals("BSQ"))
res = altcoinFormat.noCode().minDecimals(2).repeatOptionalDecimals(0, 0).format(altcoin).toString();
else
res = altcoinFormat.noCode().format(altcoin).toString();
if (appendCurrencyCode)
return res + " " + altcoin.getCurrencyCode();
else
return res;
} catch (Throwable t) {
log.warn("Exception at formatAltcoinVolume: " + t.toString());
return Res.get("shared.na") + " " + altcoin.getCurrencyCode();
}
} else {
return Res.get("shared.na");
}
}
public String formatVolumeLabel(String currencyCode) {
return formatVolumeLabel(currencyCode, "");
}
public String formatVolumeLabel(String currencyCode, String postFix) {
return Res.get("formatter.formatVolumeLabel",
currencyCode, postFix);
}
// Amount
public String formatAmount(Offer offer) {
return formatAmount(offer, false);
}
public String formatAmount(Offer offer, boolean decimalAligned) {
String formattedAmount = offer.isRange() ? formatCoin(offer.getMinAmount()) + RANGE_SEPARATOR + formatCoin(offer.getAmount()) : formatCoin(offer.getAmount());
if (decimalAligned) {
formattedAmount = fillUpPlacesWithEmptyStrings(formattedAmount, 15);
}
return formattedAmount;
}
public String formatAmount(Offer offer, int decimalPlaces, boolean decimalAligned, int maxPlaces) {
String formattedAmount = offer.isRange() ? formatCoin(offer.getMinAmount(), decimalPlaces) + RANGE_SEPARATOR + formatCoin(offer.getAmount(), decimalPlaces) : formatCoin(offer.getAmount(), decimalPlaces);
if (decimalAligned) {
formattedAmount = fillUpPlacesWithEmptyStrings(formattedAmount, maxPlaces);
}
return formattedAmount;
}
// Price
public String formatPrice(Price price, MonetaryFormat fiatPriceFormat, boolean appendCurrencyCode) {
if (price != null) {
Monetary monetary = price.getMonetary();
if (monetary instanceof Fiat)
return formatFiat((Fiat) monetary, fiatPriceFormat, appendCurrencyCode);
else
return formatAltcoin((Altcoin) monetary, appendCurrencyCode);
} else {
return Res.get("shared.na");
}
}
public String formatPrice(Price price, boolean appendCurrencyCode) {
return formatPrice(price, fiatPriceFormat, true);
}
public String formatPrice(Price price) {
return formatPrice(price, fiatPriceFormat, false);
}
public String formatPrice(Price price, Boolean decimalAligned, int maxPlaces) {
String formattedPrice = formatPrice(price);
if (decimalAligned) {
formattedPrice = fillUpPlacesWithEmptyStrings(formattedPrice, maxPlaces);
}
return formattedPrice;
}
// Market price
public String formatMarketPrice(double price, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode))
return formatMarketPrice(price, 2);
else
return formatMarketPrice(price, 8);
}
public String formatMarketPrice(double price, int precision) {
return formatRoundedDoubleWithPrecision(price, precision);
}
// Other
public String formatRoundedDoubleWithPrecision(double value, int precision) {
decimalFormat.setMinimumFractionDigits(precision);
decimalFormat.setMaximumFractionDigits(precision);
return decimalFormat.format(MathUtils.roundDouble(value, precision)).replace(",", ".");
}
public String getDirectionWithCode(OfferPayload.Direction direction, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode))
return (direction == OfferPayload.Direction.BUY) ? Res.get("shared.buyCurrency", Res.getBaseCurrencyCode()) : Res.get("shared.sellCurrency", Res.getBaseCurrencyCode());
else
return (direction == OfferPayload.Direction.SELL) ? Res.get("shared.buyCurrency", currencyCode) : Res.get("shared.sellCurrency", currencyCode);
}
public String getDirectionWithCodeDetailed(OfferPayload.Direction direction, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode))
return (direction == OfferPayload.Direction.BUY) ? Res.get("shared.buyingBTCWith", currencyCode) : Res.get("shared.sellingBTCFor", currencyCode);
else
return (direction == OfferPayload.Direction.SELL) ? Res.get("shared.buyingCurrency", currencyCode) : Res.get("shared.sellingCurrency", currencyCode);
}
public String arbitratorAddressesToString(List<NodeAddress> nodeAddresses) {
return nodeAddresses.stream().map(NodeAddress::getFullAddress).collect(Collectors.joining(", "));
}
public String languageCodesToString(List<String> languageLocales) {
return languageLocales.stream().map(LanguageUtil::getDisplayName).collect(Collectors.joining(", "));
}
public String formatDateTime(Date date) {
return formatDateTime(date, true);
}
public String formatDateTime(Date date, boolean useLocaleAndLocalTimezone) {
Locale locale = useLocaleAndLocalTimezone ? getLocale() : Locale.US;
DateFormat dateInstance = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
DateFormat timeInstance = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
if (!useLocaleAndLocalTimezone) {
dateInstance.setTimeZone(TimeZone.getTimeZone("UTC"));
timeInstance.setTimeZone(TimeZone.getTimeZone("UTC"));
}
return formatDateTime(date, dateInstance, timeInstance);
}
public String formatDateTime(Date date, DateFormat dateFormatter, DateFormat timeFormatter) {
if (date != null) {
return dateFormatter.format(date) + " " + timeFormatter.format(date);
} else {
return "";
}
}
public String formatDateTimeSpan(Date dateFrom, Date dateTo) {
if (dateFrom != null && dateTo != null) {
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale());
DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale());
return dateFormatter.format(dateFrom) + " " + timeFormatter.format(dateFrom) + RANGE_SEPARATOR + timeFormatter.format(dateTo);
} else {
return "";
}
}
public String formatTime(Date date) {
if (date != null) {
DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale());
return timeFormatter.format(date);
} else {
return "";
}
}
public String formatDate(Date date) {
if (date != null) {
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale());
return dateFormatter.format(date);
} else {
return "";
}
}
public String formatToPercentWithSymbol(double value) {
return formatToPercent(value) + "%";
}
public String formatPercentagePrice(double value) {
return formatToPercentWithSymbol(value);
}
public String formatToPercent(double value) {
DecimalFormat decimalFormat = new DecimalFormat("
decimalFormat.setMinimumFractionDigits(2);
decimalFormat.setMaximumFractionDigits(2);
return decimalFormat.format(MathUtils.roundDouble(value * 100.0, 2)).replace(",", ".");
}
public double parseNumberStringToDouble(String input) throws NumberFormatException {
return Double.parseDouble(cleanDoubleInput(input));
}
public double parsePercentStringToDouble(String percentString) throws NumberFormatException {
String input = percentString.replace("%", "");
input = cleanDoubleInput(input);
double value = Double.parseDouble(input);
return MathUtils.roundDouble(value / 100d, 4);
}
public long parsePriceStringToLong(String currencyCode, String amount, int precision) {
if (amount == null || amount.isEmpty())
return 0;
long value = 0;
try {
double amountValue = Double.parseDouble(amount);
amount = formatRoundedDoubleWithPrecision(amountValue, precision);
value = Price.parse(currencyCode, amount).getValue();
} catch (NumberFormatException ignore) {
// expected NumberFormatException if input is not a number
} catch (Throwable t) {
log.error("parsePriceStringToLong: " + t.toString());
}
return value;
}
public static String convertCharsForNumber(String input) {
// Some languages like finnish use the long dash for the minus
input = input.replace("−", "-");
input = StringUtils.deleteWhitespace(input);
return input.replace(",", ".");
}
protected String cleanDoubleInput(String input) {
input = convertCharsForNumber(input);
if (input.equals("."))
input = input.replace(".", "0.");
if (input.equals("-."))
input = input.replace("-.", "-0.");
// don't use String.valueOf(Double.parseDouble(input)) as return value as it gives scientific
// notation (1.0E-6) which screw up coinFormat.parse
//noinspection ResultOfMethodCallIgnored
// Just called to check if we have a valid double, throws exception otherwise
//noinspection ResultOfMethodCallIgnored
Double.parseDouble(input);
return input;
}
public String formatAccountAge(long durationMillis) {
durationMillis = Math.max(0, durationMillis);
String day = Res.get("time.day").toLowerCase();
String days = Res.get("time.days");
String format = "d\' " + days + "\'";
return StringUtils.replaceOnce(DurationFormatUtils.formatDuration(durationMillis, format), "1 " + days, "1 " + day);
}
public String formatDurationAsWords(long durationMillis) {
return formatDurationAsWords(durationMillis, false, true);
}
public String formatDurationAsWords(long durationMillis, boolean showSeconds, boolean showZeroValues) {
String format = "";
String second = Res.get("time.second");
String minute = Res.get("time.minute");
String hour = Res.get("time.hour").toLowerCase();
String day = Res.get("time.day").toLowerCase();
String days = Res.get("time.days");
String hours = Res.get("time.hours");
String minutes = Res.get("time.minutes");
String seconds = Res.get("time.seconds");
if (durationMillis >= DateUtils.MILLIS_PER_DAY) {
format = "d\' " + days + ", \'";
}
if (showSeconds) {
format += "H\' " + hours + ", \'m\' " + minutes + ", \'s\' " + seconds + "\'";
} else
format += "H\' " + hours + ", \'m\' " + minutes + "\'";
String duration = durationMillis > 0 ? DurationFormatUtils.formatDuration(durationMillis, format) : "";
duration = StringUtils.replacePattern(duration, "^1 " + seconds + "|\\b1 " + seconds, "1 " + second);
duration = StringUtils.replacePattern(duration, "^1 " + minutes + "|\\b1 " + minutes, "1 " + minute);
duration = StringUtils.replacePattern(duration, "^1 " + hours + "|\\b1 " + hours, "1 " + hour);
duration = StringUtils.replacePattern(duration, "^1 " + days + "|\\b1 " + days, "1 " + day);
if (!showZeroValues) {
duration = duration.replace(", 0 seconds", "");
duration = duration.replace(", 0 minutes", "");
duration = duration.replace(", 0 hours", "");
duration = duration.replace("0 days", "");
duration = duration.replace("0 hours, ", "");
duration = duration.replace("0 minutes, ", "");
duration = duration.replace("0 seconds", "");
}
return duration.trim();
}
public String booleanToYesNo(boolean value) {
return value ? Res.get("shared.yes") : Res.get("shared.no");
}
public String getDirectionBothSides(OfferPayload.Direction direction, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
currencyCode = Res.getBaseCurrencyCode();
return direction == OfferPayload.Direction.BUY ?
Res.get("formatter.makerTaker", currencyCode, Res.get("shared.buyer"), currencyCode, Res.get("shared.seller")) :
Res.get("formatter.makerTaker", currencyCode, Res.get("shared.seller"), currencyCode, Res.get("shared.buyer"));
} else {
return direction == OfferPayload.Direction.SELL ?
Res.get("formatter.makerTaker", currencyCode, Res.get("shared.buyer"), currencyCode, Res.get("shared.seller")) :
Res.get("formatter.makerTaker", currencyCode, Res.get("shared.seller"), currencyCode, Res.get("shared.buyer"));
}
}
public String getDirectionForBuyer(boolean isMyOffer, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
String code = Res.getBaseCurrencyCode();
return isMyOffer ?
Res.get("formatter.youAreAsMaker", Res.get("shared.buying"), code, Res.get("shared.selling"), code) :
Res.get("formatter.youAreAsTaker", Res.get("shared.buying"), code, Res.get("shared.selling"), code);
} else {
return isMyOffer ?
Res.get("formatter.youAreAsMaker", Res.get("shared.selling"), currencyCode, Res.get("shared.buying"), currencyCode) :
Res.get("formatter.youAreAsTaker", Res.get("shared.selling"), currencyCode, Res.get("shared.buying"), currencyCode);
}
}
public String getDirectionForSeller(boolean isMyOffer, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
String code = Res.getBaseCurrencyCode();
return isMyOffer ?
Res.get("formatter.youAreAsMaker", Res.get("shared.selling"), code, Res.get("shared.buying"), code) :
Res.get("formatter.youAreAsTaker", Res.get("shared.selling"), code, Res.get("shared.buying"), code);
} else {
return isMyOffer ?
Res.get("formatter.youAreAsMaker", Res.get("shared.buying"), currencyCode, Res.get("shared.selling"), currencyCode) :
Res.get("formatter.youAreAsTaker", Res.get("shared.buying"), currencyCode, Res.get("shared.selling"), currencyCode);
}
}
public String getDirectionForTakeOffer(OfferPayload.Direction direction, String currencyCode) {
String baseCurrencyCode = Res.getBaseCurrencyCode();
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
return direction == OfferPayload.Direction.BUY ?
Res.get("formatter.youAre", Res.get("shared.selling"), baseCurrencyCode, Res.get("shared.buying"), currencyCode) :
Res.get("formatter.youAre", Res.get("shared.buying"), baseCurrencyCode, Res.get("shared.selling"), currencyCode);
} else {
return direction == OfferPayload.Direction.SELL ?
Res.get("formatter.youAre", Res.get("shared.selling"), currencyCode, Res.get("shared.buying"), baseCurrencyCode) :
Res.get("formatter.youAre", Res.get("shared.buying"), currencyCode, Res.get("shared.selling"), baseCurrencyCode);
}
}
public String getOfferDirectionForCreateOffer(OfferPayload.Direction direction, String currencyCode) {
String baseCurrencyCode = Res.getBaseCurrencyCode();
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
return direction == OfferPayload.Direction.BUY ?
Res.get("formatter.youAreCreatingAnOffer.fiat", Res.get("shared.buy"), baseCurrencyCode) :
Res.get("formatter.youAreCreatingAnOffer.fiat", Res.get("shared.sell"), baseCurrencyCode);
} else {
return direction == OfferPayload.Direction.SELL ?
Res.get("formatter.youAreCreatingAnOffer.altcoin", Res.get("shared.buy"), currencyCode, Res.get("shared.selling"), baseCurrencyCode) :
Res.get("formatter.youAreCreatingAnOffer.altcoin", Res.get("shared.sell"), currencyCode, Res.get("shared.buying"), baseCurrencyCode);
}
}
public String getRole(boolean isBuyerMakerAndSellerTaker, boolean isMaker, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
String baseCurrencyCode = Res.getBaseCurrencyCode();
if (isBuyerMakerAndSellerTaker)
return isMaker ?
Res.get("formatter.asMaker", baseCurrencyCode, Res.get("shared.buyer")) :
Res.get("formatter.asTaker", baseCurrencyCode, Res.get("shared.seller"));
else
return isMaker ?
Res.get("formatter.asMaker", baseCurrencyCode, Res.get("shared.seller")) :
Res.get("formatter.asTaker", baseCurrencyCode, Res.get("shared.buyer"));
} else {
if (isBuyerMakerAndSellerTaker)
return isMaker ?
Res.get("formatter.asMaker", currencyCode, Res.get("shared.seller")) :
Res.get("formatter.asTaker", currencyCode, Res.get("shared.buyer"));
else
return isMaker ?
Res.get("formatter.asMaker", currencyCode, Res.get("shared.buyer")) :
Res.get("formatter.asTaker", currencyCode, Res.get("shared.seller"));
}
}
public String formatBytes(long bytes) {
double kb = 1024;
double mb = kb * kb;
DecimalFormat decimalFormat = new DecimalFormat("
if (bytes < kb)
return bytes + " bytes";
else if (bytes < mb)
return decimalFormat.format(bytes / kb) + " KB";
else
return decimalFormat.format(bytes / mb) + " MB";
}
public String getCurrencyPair(String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode))
return Res.getBaseCurrencyCode() + "/" + currencyCode;
else
return currencyCode + "/" + Res.getBaseCurrencyCode();
}
public String getCounterCurrency(String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode))
return currencyCode;
else
return Res.getBaseCurrencyCode();
}
public String getBaseCurrency(String currencyCode) {
if (CurrencyUtil.isCryptoCurrency(currencyCode))
return currencyCode;
else
return Res.getBaseCurrencyCode();
}
public String getCounterCurrencyAndCurrencyPair(String currencyCode) {
return getCounterCurrency(currencyCode) + " (" + getCurrencyPair(currencyCode) + ")";
}
public String getCurrencyNameAndCurrencyPair(String currencyCode) {
return CurrencyUtil.getNameByCode(currencyCode) + " (" + getCurrencyPair(currencyCode) + ")";
}
public String getPriceWithCurrencyCode(String currencyCode) {
return getPriceWithCurrencyCode(currencyCode, "shared.priceInCurForCur");
}
public String getPriceWithCurrencyCode(String currencyCode, String translationKey) {
if (CurrencyUtil.isCryptoCurrency(currencyCode))
return Res.get(translationKey, Res.getBaseCurrencyCode(), currencyCode);
else
return Res.get(translationKey, currencyCode, Res.getBaseCurrencyCode());
}
public Locale getLocale() {
return GlobalSettings.getLocale();
}
}
|
package forklift.consumer;
import com.fasterxml.jackson.databind.ObjectMapper;
import forklift.classloader.RunAsClassLoader;
import forklift.concurrent.Callback;
import forklift.connectors.ConnectorException;
import forklift.connectors.ForkliftConnectorI;
import forklift.connectors.ForkliftMessage;
import forklift.consumer.parser.KeyValueParser;
import forklift.decorators.Audit;
import forklift.decorators.Config;
import forklift.decorators.Headers;
import forklift.decorators.MultiThreaded;
import forklift.decorators.OnMessage;
import forklift.decorators.OnValidate;
import forklift.decorators.Queue;
import forklift.decorators.Retry;
import forklift.decorators.Topic;
import forklift.properties.PropertiesManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
public class Consumer {
private Logger log;
private static AtomicInteger id = new AtomicInteger(1);
private static ObjectMapper mapper = new ObjectMapper();
private final Boolean audit;
private final ClassLoader classLoader;
private final ForkliftConnectorI connector;
private final Map<Class, Map<Class<?>, List<Field>>> injectFields;
private final Class<?> msgHandler;
private final String name;
private final List<Method> onMessage;
private final List<Method> onValidate;
private final Retry retry;
private final Queue queue;
private final Topic topic;
private final ApplicationContext context;
// If a queue can process multiple messages at a time we
// use a thread pool to manage how much cpu load the queue can
// take.
private final BlockingQueue<Runnable> blockQueue;
private final ThreadPoolExecutor threadPool;
private Callback<Consumer> outOfMessages;
private AtomicBoolean running = new AtomicBoolean(false);
public Consumer(Class<?> msgHandler, ForkliftConnectorI connector) {
this(msgHandler, connector, null);
}
public Consumer(Class<?> msgHandler, ForkliftConnectorI connector, ClassLoader classLoader) {
this(msgHandler, connector, classLoader, null);
}
@SuppressWarnings("unchecked")
public Consumer(Class<?> msgHandler, ForkliftConnectorI connector, ClassLoader classLoader, ApplicationContext context) {
this.audit = msgHandler.isAnnotationPresent(Audit.class);
this.classLoader = classLoader;
this.connector = connector;
this.msgHandler = msgHandler;
this.retry = msgHandler.getAnnotation(Retry.class);
this.context = context;
this.topic = msgHandler.getAnnotation(Topic.class);
this.queue = msgHandler.getAnnotation(Queue.class);
if (this.queue != null && this.topic != null)
throw new IllegalArgumentException("Msg Handler cannot consume a queue and topic");
if (this.queue != null)
this.name = queue.value() + ":" + id.getAndIncrement();
else if (this.topic != null)
this.name = topic.value() + ":" + id.getAndIncrement();
else
throw new IllegalArgumentException("Msg Handler must handle a queue or topic.");
log = LoggerFactory.getLogger(this.name);
// Init the thread pools if the msg handler is multi threaded. If the msg handler is single threaded
// it'll just run in the current thread to prevent any message read ahead that would be performed.
if (msgHandler.isAnnotationPresent(MultiThreaded.class)) {
MultiThreaded multiThreaded = msgHandler.getAnnotation(MultiThreaded.class);
log.info("Creating thread pool of {}", multiThreaded.value());
blockQueue = new ArrayBlockingQueue<Runnable>(multiThreaded.value() * 100 + 100);
threadPool = new ThreadPoolExecutor(
Math.min(2, multiThreaded.value()), multiThreaded.value(), 5L, TimeUnit.MINUTES, blockQueue);
} else {
blockQueue = null;
threadPool = null;
}
// Look for all methods that need to be called when a
// message is received.
onMessage = new ArrayList<>();
onValidate = new ArrayList<>();
for (Method m : msgHandler.getDeclaredMethods()) {
if (m.isAnnotationPresent(OnMessage.class))
onMessage.add(m);
else if (m.isAnnotationPresent(OnValidate.class))
onValidate.add(m);
}
injectFields = new HashMap<>();
injectFields.put(Config.class, new HashMap<>());
injectFields.put(javax.inject.Inject.class, new HashMap<>());
injectFields.put(forklift.decorators.Message.class, new HashMap<>());
injectFields.put(forklift.decorators.Headers.class, new HashMap<>());
injectFields.put(forklift.decorators.Properties.class, new HashMap<>());
for (Field f : msgHandler.getDeclaredFields()) {
injectFields.keySet().forEach(type -> {
if (f.isAnnotationPresent(type)) {
f.setAccessible(true);
// Init the list
if (injectFields.get(type).get(f.getType()) == null)
injectFields.get(type).put(f.getType(), new ArrayList<>());
injectFields.get(type).get(f.getType()).add(f);
}
});
}
}
/**
* Creates a JMS consumer and begins listening for messages.
* If the JMS consumer dies, this method will attempt to
* get a new JMS consumer.
*/
public void listen() {
final MessageConsumer consumer;
try {
if (topic != null)
consumer = connector.getTopic(topic.value());
else if (queue != null)
consumer = connector.getQueue(queue.value());
else
throw new RuntimeException("No queue/topic specified");
messageLoop(consumer);
} catch (ConnectorException e) {
e.printStackTrace();
}
}
public String getName() {
return name;
}
public void messageLoop(MessageConsumer consumer) {
try {
running.set(true);
while (running.get()) {
Message jmsMsg;
while ((jmsMsg = consumer.receive(2500)) != null) {
final ForkliftMessage msg = connector.jmsToForklift(jmsMsg);
try {
final Object handler = msgHandler.newInstance();
RunAsClassLoader.run(classLoader, () -> {
inject(msg, handler);
});
// Handle the message.
final MessageRunnable runner = new MessageRunnable(jmsMsg, classLoader, handler, onMessage, onValidate);
if (threadPool != null)
threadPool.execute(runner);
else
runner.run();
} catch (Exception e) {
// If this error occurs we had a massive problem with the conusmer class setup.
log.error("Consumer couldn't be used.", e);
// In this instance just stop the consumer. Someone needs to fix their shit!
running.set(false);
}
}
if (outOfMessages != null)
outOfMessages.handle(this);
}
// Shutdown the pool, but let actively executing work finish.
if (threadPool != null) {
log.info("Shutting down thread pool - active {}", threadPool.getActiveCount());
threadPool.shutdown();
}
} catch (JMSException e) {
running.set(false);
log.error("JMS Error in message loop: ", e);
} finally {
try {
consumer.close();
} catch (Exception e) {
log.error("Error in message loop shutdown:", e);
}
}
}
public void shutdown() {
running.set(false);
}
public void setOutOfMessages(Callback<Consumer> outOfMessages) {
this.outOfMessages = outOfMessages;
}
/**
* Inject the data from a forklift message into an instance of the msgHandler class.
* @param msg containing data
* @param instance an instance of the msgHandler class.
*/
public void inject(ForkliftMessage msg, final Object instance) {
// Inject the forklift msg
injectFields.keySet().stream().forEach(decorator -> {
final Map<Class<?>, List<Field>> fields = injectFields.get(decorator);
fields.keySet().stream().forEach(clazz -> {
fields.get(clazz).forEach(f -> {
try {
if (decorator == forklift.decorators.Message.class) {
if (clazz == ForkliftMessage.class) {
f.set(instance, msg);
} else if (clazz == String.class) {
f.set(instance, msg.getMsg());
} else if (clazz == Map.class) {
// We assume that the map is <String, String>.
f.set(instance, KeyValueParser.parse(msg.getMsg()));
} else {
// Attempt to parse a json
f.set(instance, mapper.readValue(msg.getMsg(), clazz));
}
} else if (decorator == javax.inject.Inject.class) {
if (clazz == ApplicationContext.class) {
f.set(instance, context);
} else {
f.set(instance, context.getBean(clazz));
}
} else if (decorator == Config.class) {
if (clazz == Properties.class) {
forklift.decorators.Config config = f.getAnnotation(forklift.decorators.Config.class);
PropertiesManager.get(config.value());
}
} else if (decorator == Headers.class) {
if (clazz == Map.class) {
f.set(instance, msg.getHeaders());
}
} else if (decorator == forklift.decorators.Properties.class) {
if (clazz == Map.class) {
f.set(instance, msg.getProperties());
}
}
} catch (Exception e) {
log.error("Error injecting data into Msg Handler", e);
throw new RuntimeException("Error injecting data into Msg Handler");
}
});
});
});
}
}
|
package hudson.slaves;
import hudson.Extension;
import hudson.Util;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.DescriptorVisibilityFilter;
import hudson.model.TaskListener;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jenkins.model.Jenkins;
import jenkins.slaves.RemotingWorkDirSettings;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* {@link ComputerLauncher} via JNLP.
*
* @author Stephen Connolly
* @author Kohsuke Kawaguchi
*/
public class JNLPLauncher extends ComputerLauncher {
/**
* If the agent needs to tunnel the connection to the master,
* specify the "host:port" here. This can include the special
* syntax "host:" and ":port" to indicate the default host/port
* shall be used.
*
* <p>
* Null if no tunneling is necessary.
*
* @since 1.250
*/
@CheckForNull
public final String tunnel;
/**
* Additional JVM arguments. Can be null.
* @since 1.297
*/
@CheckForNull
public final String vmargs;
@Nonnull
private RemotingWorkDirSettings workDirSettings;
/**
* Constructor.
* @param tunnel Tunnel settings
* @param vmargs JVM arguments
* @param workDirSettings Settings for Work Directory management in Remoting.
* If {@code null}, {@link RemotingWorkDirSettings#getEnabledDefaults()}
* will be used to enable work directories by default in new agents.
* @since 2.68
*/
@DataBoundConstructor
public JNLPLauncher(@CheckForNull String tunnel, @CheckForNull String vmargs, @Nullable RemotingWorkDirSettings workDirSettings) {
this.tunnel = Util.fixEmptyAndTrim(tunnel);
this.vmargs = Util.fixEmptyAndTrim(vmargs);
this.workDirSettings = workDirSettings != null ? workDirSettings :
RemotingWorkDirSettings.getEnabledDefaults();
}
@Deprecated
public JNLPLauncher(String tunnel, String vmargs) {
// TODO: Enable workDir by default in API? Otherwise classes inheriting from JNLPLauncher
// will need to enable the feature by default as well.
this(tunnel, vmargs, RemotingWorkDirSettings.getDisabledDefaults());
}
/**
* @deprecated This Launcher does not enable the work directory.
* It is recommended to use {@link #JNLPLauncher(boolean)}
*/
@Deprecated
public JNLPLauncher() {
this(false);
}
/**
* Constructor with default options.
*
* @param enableWorkDir If {@code true}, the work directory will be enabled with default settings.
*/
public JNLPLauncher(boolean enableWorkDir) {
this(null, null, enableWorkDir
? RemotingWorkDirSettings.getEnabledDefaults()
: RemotingWorkDirSettings.getDisabledDefaults());
}
protected Object readResolve() {
if (workDirSettings == null) {
// For the migrated code agents are always disabled
workDirSettings = RemotingWorkDirSettings.getDisabledDefaults();
}
return this;
}
/**
* Returns work directory settings.
*
* @since 2.72
*/
@Nonnull
public RemotingWorkDirSettings getWorkDirSettings() {
return workDirSettings;
}
@Override
public boolean isLaunchSupported() {
return false;
}
@Override
public void launch(SlaveComputer computer, TaskListener listener) {
// do nothing as we cannot self start
}
/**
* @deprecated as of 1.XXX
* Use {@link Jenkins#getDescriptor(Class)}
*/
public static /*almost final*/ Descriptor<ComputerLauncher> DESCRIPTOR;
/**
* Gets work directory options as a String.
*
* In public API {@code getWorkDirSettings().toCommandLineArgs(computer)} should be used instead
* @param computer Computer
* @return Command line options for launching with the WorkDir
*/
@Nonnull
@Restricted(NoExternalUse.class)
public String getWorkDirOptions(@Nonnull Computer computer) {
if(!(computer instanceof SlaveComputer)) {
return "";
}
return workDirSettings.toCommandLineString((SlaveComputer)computer);
}
@Extension @Symbol("jnlp")
public static class DescriptorImpl extends Descriptor<ComputerLauncher> {
public DescriptorImpl() {
DESCRIPTOR = this;
}
public String getDisplayName() {
return Messages.JNLPLauncher_displayName();
}
/**
* Checks if Work Dir settings should be displayed.
*
* This flag is checked in {@code config.jelly} before displaying the
* {@link JNLPLauncher#workDirSettings} property.
* By default the configuration is displayed only for {@link JNLPLauncher},
* but the implementation can be overridden.
* @return {@code true} if work directories are supported by the launcher type.
* @since 2.73
*/
public boolean isWorkDirSupported() {
// This property is included only for JNLPLauncher by default.
// Causes JENKINS-45895 in the case of includes otherwise
return DescriptorImpl.class.equals(getClass());
}
};
/**
* Hides the JNLP launcher when the JNLP agent port is not enabled.
*
* @since 2.16
*/
@Extension
public static class DescriptorVisibilityFilterImpl extends DescriptorVisibilityFilter {
/**
* {@inheritDoc}
*/
@Override
public boolean filter(@CheckForNull Object context, @Nonnull Descriptor descriptor) {
return descriptor.clazz != JNLPLauncher.class || Jenkins.getInstance().getTcpSlaveAgentListener() != null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean filterType(@Nonnull Class<?> contextClass, @Nonnull Descriptor descriptor) {
return descriptor.clazz != JNLPLauncher.class || Jenkins.getInstance().getTcpSlaveAgentListener() != null;
}
}
}
|
package net.mgsx.midi.playback;
import net.mgsx.midi.sequence.event.Controller;
import net.mgsx.midi.sequence.util.MidiEventListener;
public abstract class BaseSequencer implements Sequencer
{
protected final MidiEventListener listener;
public BaseSequencer(MidiEventListener listener) {
super();
this.listener = listener;
}
protected void sendAllNotesOff()
{
sendAllNotesOff(listener);
}
public static void sendAllNotesOff(MidiEventListener listener)
{
Controller noteOff = new Controller(0, 0, 123, 0);
for(int i=0 ; i<16 ; i++)
{
noteOff.setChannel(i);
listener.onEvent(noteOff, 0);
}
}
}
|
import java.io.*;
public class Employee{
public String name;
private int age;
public String designation;
private double salary;
// Constructor for Employee class.
public Employee(String name) {
this.name = name;
}
public void setEmpAge(int empAge){
age = empAge;
}
public void setEmpDesignation(String empDesig){
designation = empDesig;
}
public void setEmpSalary(double empSalary){
salary = empSalary;
}
// Print the Employee details.
public void printEmployee(){
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Designation: " + designation);
System.out.println("Salary: " + salary);
}
}
|
package org.json.junit;
import static org.junit.Assert.*;
import java.util.*;
import org.json.*;
import org.junit.*;
import com.jayway.jsonpath.*;
/**
* Enums are not explicitly supported in JSON-Java. But because enums act like
* classes, all required behavior is already be present in some form.
* These tests explore how enum serialization works with JSON-Java.
*/
public class EnumTest {
/**
* To serialize an enum by its getters, use the JSONObject Object constructor.
* The JSONObject ctor handles enum like any other bean. A JSONobject
* is created whose entries are the getter name/value pairs.
*/
@Test
public void jsonObjectFromEnum() {
// If there are no getters then the object is empty.
MyEnum myEnum = MyEnum.VAL2;
JSONObject jsonObject = new JSONObject(myEnum);
assertTrue("simple enum has no getters", jsonObject.length() == 0);
// enum with a getters should create a non-empty object
MyEnumField myEnumField = MyEnumField.VAL2;
jsonObject = new JSONObject(myEnumField);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonObject.toString());
assertTrue("expecting 2 items in top level object",
((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expecting val 2", "val 2".equals(JsonPath.read(doc, "$.value")));
assertTrue("expecting 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal")));
/**
* class which contains enum instances. Each enum should be stored
* in its own JSONObject
*/
MyEnumClass myEnumClass = new MyEnumClass();
myEnumClass.setMyEnum(MyEnum.VAL1);
myEnumClass.setMyEnumField(MyEnumField.VAL3);
jsonObject = new JSONObject(myEnumClass);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonObject.toString());
assertTrue("expecting 2 items in top level object",
((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expecting 2 items in myEnumField object",
((Map<?,?>)(JsonPath.read(doc, "$.myEnumField"))).size() == 2);
assertTrue("expecting 0 items in myEnum object",
((Map<?,?>)(JsonPath.read(doc, "$.myEnum"))).size() == 0);
assertTrue("expecting 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal")));
assertTrue("expecting val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value")));
}
/**
* To serialize an enum by its set of allowed values, use getNames()
* and the the JSONObject Object with names constructor.
*/
@Test
public void jsonObjectFromEnumWithNames() {
String [] names;
JSONObject jsonObject;
MyEnum myEnum = MyEnum.VAL1;
names = JSONObject.getNames(myEnum);
// The values will be MyEnum fields
jsonObject = new JSONObject(myEnum, names);
// validate JSON object
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2")));
assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3")));
MyEnumField myEnumField = MyEnumField.VAL3;
names = JSONObject.getNames(myEnumField);
// The values will be MyEnmField fields
jsonObject = new JSONObject(myEnumField, names);
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2")));
assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3")));
}
/**
* To serialize by assigned value, use the put() methods. The value
* will be stored as a enum type.
*/
@Test
public void enumPut() {
JSONObject jsonObject = new JSONObject();
MyEnum myEnum = MyEnum.VAL2;
jsonObject.put("myEnum", myEnum);
MyEnumField myEnumField = MyEnumField.VAL1;
jsonObject.putOnce("myEnumField", myEnumField);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level objects", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnum")));
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.myEnumField")));
JSONArray jsonArray = new JSONArray();
jsonArray.put(myEnum);
jsonArray.put(1, myEnumField);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 2 top level objects", ((List<?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[0]")));
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$[1]")));
/**
* Leaving these tests because they exercise get, opt, and remove
*/
assertTrue("expecting myEnum value", MyEnum.VAL2.equals(jsonArray.get(0)));
assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.opt(1)));
assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.remove(1)));
}
/**
* The default action of valueToString() is to call object.toString().
* For enums, this means the assigned value will be returned as a string.
*/
@Test
public void enumValueToString() {
String expectedStr1 = "\"VAL1\"";
String expectedStr2 = "\"VAL1\"";
MyEnum myEnum = MyEnum.VAL1;
MyEnumField myEnumField = MyEnumField.VAL1;
MyEnumClass myEnumClass = new MyEnumClass();
String str1 = JSONObject.valueToString(myEnum);
assertTrue("actual myEnum: "+str1+" expected: "+expectedStr1,
str1.equals(expectedStr1));
String str2 = JSONObject.valueToString(myEnumField);
assertTrue("actual myEnumField: "+str2+" expected: "+expectedStr2,
str2.equals(expectedStr2));
/**
* However, an enum within another class will not be rendered
* unless that class overrides default toString()
*/
String expectedStr3 = "\"org.json.junit.MyEnumClass@";
myEnumClass.setMyEnum(MyEnum.VAL1);
myEnumClass.setMyEnumField(MyEnumField.VAL1);
String str3 = JSONObject.valueToString(myEnumClass);
assertTrue("actual myEnumClass: "+str3+" expected: "+expectedStr3,
str3.startsWith(expectedStr3));
}
/**
* In whatever form the enum was added to the JSONObject or JSONArray,
* json[Object|Array].toString should serialize it in a reasonable way.
*/
@Test
public void enumToString() {
MyEnum myEnum = MyEnum.VAL2;
JSONObject jsonObject = new JSONObject(myEnum);
String expectedStr = "{}";
assertTrue("myEnum toString() should be empty", expectedStr.equals(jsonObject.toString()));
MyEnumField myEnumField = MyEnumField.VAL2;
jsonObject = new JSONObject(myEnumField);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected val 2", "val 2".equals(JsonPath.read(doc, "$.value")));
assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal")));
MyEnumClass myEnumClass = new MyEnumClass();
myEnumClass.setMyEnum(MyEnum.VAL1);
myEnumClass.setMyEnumField(MyEnumField.VAL3);
jsonObject = new JSONObject(myEnumClass);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected 2 myEnumField items", ((Map<?,?>)(JsonPath.read(doc, "$.myEnumField"))).size() == 2);
assertTrue("expected 0 myEnum items", ((Map<?,?>)(JsonPath.read(doc, "$.myEnum"))).size() == 0);
assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal")));
assertTrue("expected val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value")));
String [] names = JSONObject.getNames(myEnum);
jsonObject = new JSONObject(myEnum, names);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2")));
assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3")));
names = JSONObject.getNames(myEnumField);
jsonObject = new JSONObject(myEnumField, names);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2")));
assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3")));
expectedStr = "{\"myEnum\":\"VAL2\", \"myEnumField\":\"VAL2\"}";
jsonObject = new JSONObject();
jsonObject.putOpt("myEnum", myEnum);
jsonObject.putOnce("myEnumField", myEnumField);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnum")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnumField")));
JSONArray jsonArray = new JSONArray();
jsonArray.put(myEnum);
jsonArray.put(1, myEnumField);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 2 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[0]")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[1]")));
}
/**
* Wrap should handle enums exactly the same way as the JSONObject(Object)
* constructor.
*/
@Test
public void wrap() {
MyEnum myEnum = MyEnum.VAL2;
JSONObject jsonObject = (JSONObject)JSONObject.wrap(myEnum);
assertTrue("simple enum has no getters", jsonObject.length() == 0);
MyEnumField myEnumField = MyEnumField.VAL2;
jsonObject = (JSONObject)JSONObject.wrap(myEnumField);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected val 2", "val 2".equals(JsonPath.read(doc, "$.value")));
assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal")));
MyEnumClass myEnumClass = new MyEnumClass();
myEnumClass.setMyEnum(MyEnum.VAL1);
myEnumClass.setMyEnumField(MyEnumField.VAL3);
jsonObject = (JSONObject)JSONObject.wrap(myEnumClass);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected 2 myEnumField items", ((Map<?,?>)(JsonPath.read(doc, "$.myEnumField"))).size() == 2);
assertTrue("expected 0 myEnum items", ((Map<?,?>)(JsonPath.read(doc, "$.myEnum"))).size() == 0);
assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal")));
assertTrue("expected val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value")));
}
/**
* It was determined that some API methods should be added to
* support enums:<br>
* JSONObject.getEnum(class, key)<br>
* JSONObject.optEnum(class, key)<br>
* JSONObject.optEnum(class, key, default)<br>
* JSONArray.getEnum(class, index)<br>
* JSONArray.optEnum(class, index)<br>
* JSONArray.optEnum(class, index, default)<br>
* <p>
* Exercise these enum API methods on JSONObject and JSONArray
*/
@Test
public void enumAPI() {
MyEnumClass myEnumClass = new MyEnumClass();
myEnumClass.setMyEnum(MyEnum.VAL1);
MyEnumField myEnumField = MyEnumField.VAL2;
JSONObject jsonObject = new JSONObject();
jsonObject.put("strKey", "value");
jsonObject.put("enumKey", myEnumField);
jsonObject.put("enumClassKey", myEnumClass);
// get a plain old enum
MyEnumField actualEnum = jsonObject.getEnum(MyEnumField.class, "enumKey");
assertTrue("get myEnumField", actualEnum == MyEnumField.VAL2);
// try to get the wrong value
try {
actualEnum = jsonObject.getEnum(MyEnumField.class, "strKey");
assertTrue("should throw an exception for wrong key", false);
} catch (Exception ignored) {}
// get a class that contains an enum
MyEnumClass actualEnumClass = (MyEnumClass)jsonObject.get("enumClassKey");
assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1);
// opt a plain old enum
actualEnum = jsonObject.optEnum(MyEnumField.class, "enumKey");
assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2);
// opt the wrong value
actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey");
assertTrue("opt null", actualEnum == null);
// opt a class that contains an enum
actualEnumClass = (MyEnumClass)jsonObject.opt("enumClassKey");
assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1);
// opt with default a plain old enum
actualEnum = jsonObject.optEnum(MyEnumField.class, "enumKey", null);
assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2);
// opt with default the wrong value
actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey", null);
assertTrue("opt null", actualEnum == null);
// opt with default an index that does not exist
actualEnum = jsonObject.optEnum(MyEnumField.class, "noKey", null);
assertTrue("opt null", actualEnum == null);
/**
* Exercise the proposed enum API methods on JSONArray
*/
JSONArray jsonArray = new JSONArray();
jsonArray.put("value");
jsonArray.put(myEnumField);
jsonArray.put(myEnumClass);
// get a plain old enum
actualEnum = jsonArray.getEnum(MyEnumField.class, 1);
assertTrue("get myEnumField", actualEnum == MyEnumField.VAL2);
// try to get the wrong value
try {
actualEnum = jsonArray.getEnum(MyEnumField.class, 0);
assertTrue("should throw an exception for wrong index", false);
} catch (Exception ignored) {}
// get a class that contains an enum
actualEnumClass = (MyEnumClass)jsonArray.get(2);
assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1);
// opt a plain old enum
actualEnum = jsonArray.optEnum(MyEnumField.class, 1);
assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2);
// opt the wrong value
actualEnum = jsonArray.optEnum(MyEnumField.class, 0);
assertTrue("opt null", actualEnum == null);
// opt a class that contains an enum
actualEnumClass = (MyEnumClass)jsonArray.opt(2);
assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1);
// opt with default a plain old enum
actualEnum = jsonArray.optEnum(MyEnumField.class, 1, null);
assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2);
// opt with default the wrong value
actualEnum = jsonArray.optEnum(MyEnumField.class, 0, null);
assertTrue("opt null", actualEnum == null);
// opt with default an index that does not exist
actualEnum = jsonArray.optEnum(MyEnumField.class, 3, null);
assertTrue("opt null", actualEnum == null);
}
}
|
package org.robovm.bindings.chartboost;
import org.robovm.apple.foundation.NSObject;
public class ChartboostDelegateAdapter extends NSObject implements
ChartboostDelegate {
@Override
public boolean shouldRequestInterstitial(String location) {
return true;
}
@Override
public boolean shouldDisplayInterstitial(String location) {
return true;
}
@Override
public void didDisplayInterstitial(String location) {
}
@Override
public void didFailToLoadInterstitial(String location, CBLoadError loadError) {
}
@Override
public void didCacheInterstitial(String location) {
}
@Override
public void didDismissInterstitial(String location) {
}
@Override
public void didCloseInterstitial(String location) {
}
@Override
public void didClickInterstitial(String location) {
}
@Override
public void didFailToRecordClick(String location, CBClickError clickError) {
}
@Override
public boolean shouldDisplayMoreApps(String location) {
return true;
}
@Override
public void didCacheMoreApps(String location) {
}
@Override
public void didDismissMoreApps(String location) {
}
@Override
public void didCloseMoreApps(String location) {
}
@Override
public void didClickMoreApps(String location) {
}
@Override
public void didFailToLoadMoreApps(String location, CBLoadError loadError) {
}
@Override
public boolean shouldDisplayRewardedVideo(String location) {
return true;
}
@Override
public void didCacheRewardedVideo(String location) {
}
@Override
public void didDismissRewardedVideo(String location) {
}
@Override
public void didCloseRewardedVideo(String location) {
}
@Override
public void didClickRewardedVideo(String location) {
}
@Override
public void didFailToLoadRewardedVideo(String location, CBLoadError loadError) {
}
@Override
public void didCompleteRewardedVideo(String location, int reward) {
}
}
|
package org.chromium.chrome.browser;
import android.os.Build;
import org.chromium.base.CalledByNative;
import org.chromium.chrome.browser.preferences.LocationSettings;
import org.chromium.chrome.browser.preferences.PreferencesLauncher;
import org.chromium.chrome.browser.preferences.ProtectedContentPreferences;
import org.chromium.chrome.browser.preferences.autofill.AutofillPreferences;
import org.chromium.chrome.browser.preferences.password.ManageSavedPasswordsPreferences;
import org.chromium.content.app.ContentApplication;
/**
* Basic application functionality that should be shared among all browser applications that use
* chrome layer.
*/
public abstract class ChromiumApplication extends ContentApplication {
/**
* Returns the class name of the Settings activity.
*/
public abstract String getSettingsActivityName();
/**
* Opens a protected content settings page, if available.
*/
@CalledByNative
protected void openProtectedContentSettings() {
assert Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
PreferencesLauncher.launchSettingsPage(this,
ProtectedContentPreferences.class.getName());
}
@CalledByNative
protected void showAutofillSettings() {
PreferencesLauncher.launchSettingsPage(this,
AutofillPreferences.class.getName());
}
@CalledByNative
protected void showPasswordSettings() {
PreferencesLauncher.launchSettingsPage(this,
ManageSavedPasswordsPreferences.class.getName());
}
/**
* Returns an instance of LocationSettings to be installed as a singleton.
*/
public LocationSettings createLocationSettings() {
return new LocationSettings(this);
}
/**
* Opens the UI to clear browsing data.
* @param tab The tab that triggered the request.
*/
@CalledByNative
protected void openClearBrowsingData(Tab tab) {}
/**
* @return Whether parental controls are enabled. Returning true will disable
* incognito mode.
*/
@CalledByNative
protected abstract boolean areParentalControlsEnabled();
// TODO(yfriedman): This is too widely available. Plumb this through ChromeNetworkDelegate
// instead.
protected abstract PKCS11AuthenticationManager getPKCS11AuthenticationManager();
/**
* @return The user agent string of Chrome.
*/
public static String getBrowserUserAgent() {
return nativeGetBrowserUserAgent();
}
private static native String nativeGetBrowserUserAgent();
}
|
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.psi.*;
import com.intellij.psi.filters.*;
import com.intellij.psi.filters.classes.*;
import com.intellij.psi.filters.element.ExcludeDeclaredFilter;
import com.intellij.psi.filters.element.ModifierFilter;
import com.intellij.psi.filters.element.ReferenceOnFilter;
import com.intellij.psi.filters.getters.UpWalkGetter;
import com.intellij.psi.filters.position.*;
import com.intellij.psi.filters.types.TypeCodeFragmentIsVoidEnabledFilter;
import com.intellij.psi.filters.types.AssignableFromFilter;
import com.intellij.psi.impl.source.jsp.jspJava.JspClass;
import com.intellij.psi.jsp.JspElementType;
import org.jetbrains.annotations.NonNls;
public class JavaCompletionData extends CompletionData{
private static final @NonNls String[] ourBlockFinalizers = {"{", "}", ";", ":", "else"};
public JavaCompletionData(){
declareCompletionSpaces();
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, TrueFilter.INSTANCE);
variant.includeScopeClass(PsiVariable.class);
variant.includeScopeClass(PsiClass.class);
variant.includeScopeClass(PsiFile.class);
variant.addCompletion(new ModifierChooser());
registerVariant(variant);
initVariantsInFileScope();
initVariantsInClassScope();
initVariantsInMethodScope();
initVariantsInFieldScope();
defineScopeEquivalence(PsiMethod.class, PsiClassInitializer.class);
defineScopeEquivalence(PsiMethod.class, PsiCodeFragment.class);
}
private void declareCompletionSpaces() {
declareFinalScope(PsiFile.class);
{
// Class body
final CompletionVariant variant = new CompletionVariant(CLASS_BODY);
variant.includeScopeClass(PsiClass.class, true);
registerVariant(variant);
}
{
// Method body
final CompletionVariant variant = new CompletionVariant(new InsideElementFilter(new ClassFilter(PsiCodeBlock.class)));
variant.includeScopeClass(PsiMethod.class, true);
variant.includeScopeClass(PsiClassInitializer.class, true);
registerVariant(variant);
}
{
// Field initializer
final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("=")));
variant.includeScopeClass(PsiField.class, true);
registerVariant(variant);
}
declareFinalScope(PsiLiteralExpression.class);
declareFinalScope(PsiComment.class);
}
protected void initVariantsInFileScope(){
// package keyword completion
{
final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new StartElementFilter());
variant.addCompletion(PsiKeyword.PACKAGE);
registerVariant(variant);
}
// import keyword completion
{
final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new OrFilter(
new StartElementFilter(),
END_OF_BLOCK
));
variant.addCompletion(PsiKeyword.IMPORT);
registerVariant(variant);
}
// other in file scope
{
final ElementFilter position = new OrFilter(
END_OF_BLOCK,
new LeftNeighbour(
new SuperParentFilter(new ClassFilter(PsiModifierList.class))
),
new StartElementFilter());
final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, position);
variant.includeScopeClass(PsiClass.class);
variant.addCompletion(PsiKeyword.CLASS);
variant.addCompletion(PsiKeyword.INTERFACE);
registerVariant(variant);
}
{
final CompletionVariant variant = new CompletionVariant(PsiTypeCodeFragment.class, new StartElementFilter());
addPrimitiveTypes(variant, TailType.NONE);
final CompletionVariant variant1 = new CompletionVariant(PsiTypeCodeFragment.class,
new AndFilter(
new StartElementFilter(),
new TypeCodeFragmentIsVoidEnabledFilter()
)
);
variant1.addCompletion(PsiKeyword.VOID, TailType.NONE);
registerVariant(variant);
registerVariant(variant1);
}
}
/**
* aClass == null for JspDeclaration scope
*/
protected void initVariantsInClassScope() {
// Completion for extends keyword
// position
{
final ElementFilter position = new AndFilter(
new NotFilter(CLASS_BODY),
new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))),
new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))),
new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))),
new NotFilter(new ScopeFilter(new EnumOrAnnotationTypeFilter())),
new LeftNeighbour(new OrFilter(
new ClassFilter(PsiIdentifier.class),
new TextFilter(">"))));
// completion
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiClass.class, true);
variant.addCompletion(PsiKeyword.EXTENDS);
variant.excludeScopeClass(PsiAnonymousClass.class);
variant.excludeScopeClass(PsiTypeParameter.class);
registerVariant(variant);
}
// Completion for implements keyword
// position
{
final ElementFilter position = new AndFilter(
new NotFilter(CLASS_BODY),
new NotFilter(new BeforeElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))),
new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))),
new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))),
new LeftNeighbour(new OrFilter(
new ClassFilter(PsiIdentifier.class),
new TextFilter(">"))),
new NotFilter(new ScopeFilter(new InterfaceFilter())));
// completion
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiClass.class, true);
variant.addCompletion(PsiKeyword.IMPLEMENTS);
variant.excludeScopeClass(PsiAnonymousClass.class);
registerVariant(variant);
}
// Completion after extends in interface, type parameter and implements in class
// position
{
final ElementFilter position = new AndFilter(
new NotFilter(CLASS_BODY),
new OrFilter(
new AndFilter(
new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, ",")),
new ScopeFilter(new InterfaceFilter())
),
new AndFilter(
new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, "&")),
new ScopeFilter(new ClassFilter(PsiTypeParameter.class))
),
new LeftNeighbour(new TextFilter(PsiKeyword.IMPLEMENTS, ",")))
);
// completion
final OrFilter flags = new OrFilter();
flags.addFilter(new ThisOrAnyInnerFilter(
new AndFilter(
new ClassFilter(PsiClass.class),
new NotFilter(new AssignableFromContextFilter()),
new InterfaceFilter())
));
flags.addFilter(new ClassFilter(PsiPackage.class));
CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiClass.class, true);
variant.excludeScopeClass(PsiAnonymousClass.class);
variant.addCompletionFilterOnElement(flags);
registerVariant(variant);
}
// Completion for classes in class extends
// position
{
final ElementFilter position = new AndFilter(
new NotFilter(CLASS_BODY),
new AndFilter(
new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS)),
new ScopeFilter(new NotFilter(new InterfaceFilter())))
);
// completion
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiClass.class, true);
variant.excludeScopeClass(PsiAnonymousClass.class);
variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(
new AndFilter(
new ClassFilter(PsiClass.class),
new NotFilter(new AssignableFromContextFilter()),
new NotFilter(new InterfaceFilter()),
new ModifierFilter(PsiModifier.FINAL, false))
));
variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class));
registerVariant(variant);
}
{
// declaration start
// position
final CompletionVariant variant = new CompletionVariant(PsiClass.class, new AndFilter(
CLASS_BODY,
new OrFilter(
END_OF_BLOCK,
new LeftNeighbour(new OrFilter(
new SuperParentFilter(new ClassFilter(PsiModifierList.class)),
new AndFilter (new TokenTypeFilter(JavaTokenType.GT),
new SuperParentFilter(new ClassFilter(PsiTypeParameterList.class)))))
)));
// completion
addPrimitiveTypes(variant);
variant.addCompletion(PsiKeyword.VOID);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class));
registerVariant(variant);
}
{
final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ","))));
variant.includeScopeClass(PsiClass.class, true);
variant.addCompletion(PsiKeyword.EXTENDS, TailType.SPACE);
registerVariant(variant);
}
}
private void initVariantsInMethodScope() {
{
// parameters list completion
final CompletionVariant variant = new CompletionVariant(
new LeftNeighbour(new OrFilter(new TextFilter(new String[]{"(", ",", PsiKeyword.FINAL}),
new SuperParentFilter(new ClassFilter(PsiAnnotation.class)))));
variant.includeScopeClass(PsiParameterList.class, true);
addPrimitiveTypes(variant);
variant.addCompletion(PsiKeyword.FINAL);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
registerVariant(variant);
}
// Completion for classes in method throws section
// position
{
final ElementFilter position = new LeftNeighbour(new AndFilter(
new TextFilter(")"),
new ParentElementFilter(new ClassFilter(PsiParameterList.class))));
// completion
CompletionVariant variant = new CompletionVariant(PsiMethod.class, position);
variant.includeScopeClass(PsiClass.class); // for throws on separate line
variant.addCompletion(PsiKeyword.THROWS);
registerVariant(variant);
//in annotation methods
variant = new CompletionVariant(PsiAnnotationMethod.class, position);
variant.addCompletion(PsiKeyword.DEFAULT);
registerVariant(variant);
}
{
// Completion for classes in method throws section
// position
final ElementFilter position = new AndFilter(
new LeftNeighbour(new TextFilter(PsiKeyword.THROWS, ",")),
new InsideElementFilter(new ClassFilter(PsiReferenceList.class))
);
// completion
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiMethod.class, true);
variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new AssignableFromFilter("java.lang.Throwable")));
variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class));
registerVariant(variant);
}
{
// completion for declarations
final CompletionVariant variant = new CompletionVariant(new OrFilter(END_OF_BLOCK, new LeftNeighbour(new TextFilter(PsiKeyword.FINAL))));
variant.includeScopeClass(PsiCodeBlock.class, false);
addPrimitiveTypes(variant);
variant.addCompletion(PsiKeyword.CLASS);
registerVariant(variant);
}
// Completion in cast expressions
{
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new AndFilter(
new TextFilter("("),
new ParentElementFilter(new OrFilter(
new ClassFilter(PsiParenthesizedExpression.class),
new ClassFilter(PsiTypeCastExpression.class))))));
addPrimitiveTypes(variant);
registerVariant(variant);
}
{
// instanceof keyword
final ElementFilter position = new LeftNeighbour(new OrFilter(
new ReferenceOnFilter(new ClassFilter(PsiVariable.class)),
new TextFilter(PsiKeyword.THIS),
new AndFilter(new TextFilter(")"), new ParentElementFilter(new AndFilter(
new ClassFilter(PsiTypeCastExpression.class, false),
new OrFilter(
new ParentElementFilter(new ClassFilter(PsiExpression.class)),
new ClassFilter(PsiExpression.class))))),
new AndFilter(new TextFilter("]"), new ParentElementFilter(new ClassFilter(PsiArrayAccessExpression.class)))));
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiExpression.class, true);
variant.includeScopeClass(PsiMethod.class);
variant.addCompletionFilter(new FalseFilter());
variant.addCompletion(PsiKeyword.INSTANCEOF);
registerVariant(variant);
}
{
// after instanceof keyword
final ElementFilter position = new PreviousElementFilter(new TextFilter(PsiKeyword.INSTANCEOF));
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiExpression.class, true);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
registerVariant(variant);
}
{
// after final keyword
final ElementFilter position = new AndFilter(new SuperParentFilter(new ClassFilter(PsiCodeBlock.class)),
new LeftNeighbour(new TextFilter(PsiKeyword.FINAL)));
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiDeclarationStatement.class, true);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
addPrimitiveTypes(variant);
registerVariant(variant);
}
{
// Keyword completion in start of declaration
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, END_OF_BLOCK);
variant.addCompletion(PsiKeyword.THIS, TailType.NONE);
variant.addCompletion(PsiKeyword.SUPER, TailType.NONE);
addKeywords(variant);
registerVariant(variant);
}
{
// Keyword completion in returns
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new TextFilter(PsiKeyword.RETURN)));
variant.addCompletion(PsiKeyword.THIS, TailType.NONE);
variant.addCompletion(PsiKeyword.SUPER, TailType.NONE);
registerVariant(variant);
}
// Catch/Finally completion
{
final ElementFilter position = new LeftNeighbour(new AndFilter(
new TextFilter("}"),
new ParentElementFilter(new AndFilter(
new LeftNeighbour(new TextFilter(PsiKeyword.TRY)),
new ParentElementFilter(new ClassFilter(PsiTryStatement.class))))));
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiCodeBlock.class, true);
variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH);
variant.addCompletion(PsiKeyword.FINALLY, '{');
variant.addCompletionFilter(new FalseFilter());
registerVariant(variant);
}
// Catch/Finnaly completion
{
final ElementFilter position = new LeftNeighbour(new AndFilter(
new TextFilter("}"),
new ParentElementFilter(new AndFilter(
new LeftNeighbour(new NotFilter(new TextFilter(PsiKeyword.TRY))),
new OrFilter(
new ParentElementFilter(new ClassFilter(PsiTryStatement.class)),
new ParentElementFilter(new ClassFilter(PsiCatchSection.class)))
))));
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiCodeBlock.class, false);
variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH);
variant.addCompletion(PsiKeyword.FINALLY, '{');
//variant.addCompletionFilter(new FalseFilter());
registerVariant(variant);
}
{
// Completion for catches
final CompletionVariant variant = new CompletionVariant(PsiTryStatement.class, new PreviousElementFilter(new AndFilter(
new ParentElementFilter(new ClassFilter(PsiTryStatement.class)),
new TextFilter("(")
)));
variant.includeScopeClass(PsiParameter.class);
variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new AssignableFromFilter("java.lang.Throwable")));
variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class));
registerVariant(variant);
}
// Completion for else expression
// completion
{
final ElementFilter position = new LeftNeighbour(
new OrFilter(
new AndFilter(new TextFilter("}"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 3)),
new AndFilter(new TextFilter(";"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 2))
));
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position);
variant.addCompletion(PsiKeyword.ELSE);
registerVariant(variant);
}
{
// Super/This keyword completion
final ElementFilter position =
new LeftNeighbour(
new AndFilter(
new TextFilter("."),
new LeftNeighbour(
new ReferenceOnFilter(new GeneratorFilter(EqualsFilter.class, new UpWalkGetter(new ClassFilter(PsiClass.class))))
)));
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position);
variant.includeScopeClass(PsiVariable.class);
variant.addCompletion(PsiKeyword.SUPER, TailType.DOT);
variant.addCompletion(PsiKeyword.THIS, TailType.DOT);
registerVariant(variant);
}
{
// Class field completion
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(
new AndFilter(
new TextFilter("."),
new LeftNeighbour(
new OrFilter(
new ReferenceOnFilter(new ClassFilter(PsiClass.class)),
new TextFilter(PRIMITIVE_TYPES),
new TextFilter("]"))))));
variant.includeScopeClass(PsiVariable.class);
variant.addCompletion(PsiKeyword.CLASS, TailType.NONE);
registerVariant(variant);
}
{
// break completion
final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new OrFilter(
new ScopeFilter(new ClassFilter(PsiSwitchStatement.class)),
new InsideElementFilter(new ClassFilter(PsiBlockStatement.class)))));
variant.includeScopeClass(PsiForStatement.class, false);
variant.includeScopeClass(PsiForeachStatement.class, false);
variant.includeScopeClass(PsiWhileStatement.class, false);
variant.includeScopeClass(PsiDoWhileStatement.class, false);
variant.includeScopeClass(PsiSwitchStatement.class, false);
variant.addCompletion(PsiKeyword.BREAK);
registerVariant(variant);
}
{
// continue completion
final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new InsideElementFilter(new ClassFilter(PsiBlockStatement.class))));
variant.includeScopeClass(PsiForeachStatement.class, false);
variant.includeScopeClass(PsiForStatement.class, false);
variant.includeScopeClass(PsiWhileStatement.class, false);
variant.includeScopeClass(PsiDoWhileStatement.class, false);
variant.addCompletion(PsiKeyword.CONTINUE);
registerVariant(variant);
}
{
final CompletionVariant variant = new CompletionVariant(
new AndFilter(
END_OF_BLOCK,
new OrFilter(
new ParentElementFilter(new ClassFilter(PsiSwitchLabelStatement.class)),
new LeftNeighbour(new OrFilter(
new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 2),
new AndFilter(new TextFilter(";", "}"),new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 3)
))))));
variant.includeScopeClass(PsiSwitchStatement.class, true);
variant.addCompletion(PsiKeyword.CASE, TailType.SPACE);
variant.addCompletion(PsiKeyword.DEFAULT, ':');
registerVariant(variant);
}
{
// primitive arrays after new
final CompletionVariant variant = new CompletionVariant(PsiExpression.class, new LeftNeighbour(
new AndFilter(new TextFilter(PsiKeyword.NEW), new LeftNeighbour(new NotFilter(new TextFilter(".", PsiKeyword.THROW)))))
);
variant.includeScopeClass(PsiNewExpression.class, true);
addPrimitiveTypes(variant);
variant.setItemProperty(LookupItem.BRACKETS_COUNT_ATTR, 1);
registerVariant(variant);
}
{
// after new
final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new TextFilter(PsiKeyword.NEW)));
variant.includeScopeClass(PsiNewExpression.class, true);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
registerVariant(variant);
}
{
final CompletionVariant variant = new CompletionVariant(new AndFilter(
new ScopeFilter(new ParentElementFilter(new ClassFilter(PsiThrowStatement.class))),
new ParentElementFilter(new ClassFilter(PsiNewExpression.class)))
);
variant.includeScopeClass(PsiNewExpression.class, false);
variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new AssignableFromFilter("java.lang.Throwable")));
registerVariant(variant);
}
{
// completion in reference parameters
final CompletionVariant variant = new CompletionVariant(TrueFilter.INSTANCE);
variant.includeScopeClass(PsiReferenceParameterList.class, true);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
registerVariant(variant);
}
{
// completion in annotation parameter list
final CompletionVariant variant = new CompletionVariant(TrueFilter.INSTANCE);
variant.includeScopeClass(PsiAnnotationParameterList.class, true);
variant.addCompletionFilterOnElement(
new OrFilter(new ClassFilter(PsiAnnotationMethod.class),
new ClassFilter(PsiClass.class),
new AndFilter (
new ClassFilter(PsiField.class),
new ModifierFilter(PsiModifier.STATIC, PsiModifier.FINAL))));
registerVariant(variant);
}
{
// null completion
final CompletionVariant variant = new CompletionVariant(new NotFilter(new LeftNeighbour(new TextFilter("."))));
variant.addCompletion(PsiKeyword.NULL,TailType.NONE);
variant.includeScopeClass(PsiExpressionList.class);
registerVariant(variant);
}
}
private void initVariantsInFieldScope() {
{
// completion in initializer
final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("=")));
variant.includeScopeClass(PsiVariable.class, false);
variant.addCompletionFilterOnElement(new OrFilter(
new ClassFilter(PsiVariable.class, false),
new ExcludeDeclaredFilter(new ClassFilter(PsiVariable.class))
));
registerVariant(variant);
}
}
private static void addPrimitiveTypes(CompletionVariant variant){
addPrimitiveTypes(variant, CompletionVariant.DEFAULT_TAIL_TYPE);
}
private static void addPrimitiveTypes(CompletionVariant variant, int tailType){
variant.addCompletion(new String[]{
PsiKeyword.SHORT, PsiKeyword.BOOLEAN,
PsiKeyword.DOUBLE, PsiKeyword.LONG,
PsiKeyword.INT, PsiKeyword.FLOAT,
PsiKeyword.CHAR, PsiKeyword.BYTE
}, tailType);
}
private static void addKeywords(CompletionVariant variant){
variant.addCompletion(PsiKeyword.SWITCH, TailType.LPARENTH);
variant.addCompletion(PsiKeyword.WHILE, TailType.LPARENTH);
variant.addCompletion(PsiKeyword.FOR, TailType.LPARENTH);
variant.addCompletion(PsiKeyword.TRY, '{');
variant.addCompletion(PsiKeyword.THROW, TailType.SPACE);
variant.addCompletion(PsiKeyword.RETURN, TailType.SPACE);
variant.addCompletion(PsiKeyword.NEW, TailType.SPACE);
variant.addCompletion(PsiKeyword.ASSERT, TailType.SPACE);
}
private static final AndFilter START_OF_CODE_FRAGMENT = new AndFilter(
new ScopeFilter(new AndFilter(
new ClassFilter(PsiCodeFragment.class),
new ClassFilter(PsiExpressionCodeFragment.class, false),
new ClassFilter(PsiJavaCodeReferenceCodeFragment.class, false),
new ClassFilter(PsiTypeCodeFragment.class, false)
)),
new StartElementFilter()
);
static final ElementFilter END_OF_BLOCK = new OrFilter(
new AndFilter(
new LeftNeighbour(
new OrFilter(
new AndFilter (
new TextFilter(ourBlockFinalizers),
new NotFilter (
new SuperParentFilter(new ClassFilter(PsiAnnotation.class))
)
),
new TextFilter("*/"),
new TokenTypeFilter(JspElementType.HOLDER_TEMPLATE_DATA),
new AndFilter(
new TextFilter(")"),
new NotFilter(
new OrFilter(
new ParentElementFilter(new ClassFilter(PsiExpressionList.class)),
new ParentElementFilter(new ClassFilter(PsiParameterList.class))
)
)
))),
new NotFilter(new TextFilter("."))
),
START_OF_CODE_FRAGMENT
);
private static final String[] PRIMITIVE_TYPES = new String[]{
PsiKeyword.SHORT, PsiKeyword.BOOLEAN,
PsiKeyword.DOUBLE, PsiKeyword.LONG,
PsiKeyword.INT, PsiKeyword.FLOAT,
PsiKeyword.VOID, PsiKeyword.CHAR, PsiKeyword.BYTE
};
private final static ElementFilter CLASS_BODY = new OrFilter(
new AfterElementFilter(new TextFilter("{")),
new ScopeFilter(new ClassFilter(JspClass.class)));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.