lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 10bbee4719a6378d698c5b2ba43403b923bc0121 | 0 | DevelopersGuild/rebel-invader,DevelopersGuild/pew-pew,DevelopersGuild/pew-pew,DevelopersGuild/pew-pew,DevelopersGuild/rebel-invader,DevelopersGuild/rebel-invader | package io.developersguild.rebelinvader;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.PooledEngine;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.RandomXS128;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import io.developersguild.rebelinvader.components.AnimationComponent;
import io.developersguild.rebelinvader.components.BackgroundComponent;
import io.developersguild.rebelinvader.components.BodyComponent;
import io.developersguild.rebelinvader.components.BoundsComponent;
import io.developersguild.rebelinvader.components.BulletComponent;
import io.developersguild.rebelinvader.components.CameraComponent;
import io.developersguild.rebelinvader.components.EnemyComponent;
import io.developersguild.rebelinvader.components.ExplosionComponent;
import io.developersguild.rebelinvader.components.HealthComponent;
import io.developersguild.rebelinvader.components.HeightDisposableComponent;
import io.developersguild.rebelinvader.components.MovementComponent;
import io.developersguild.rebelinvader.components.MissileComponent;
import io.developersguild.rebelinvader.components.PlayerComponent;
import io.developersguild.rebelinvader.components.PowerComponent;
import io.developersguild.rebelinvader.components.StateComponent;
import io.developersguild.rebelinvader.components.StructureComponent;
import io.developersguild.rebelinvader.components.TextureComponent;
import io.developersguild.rebelinvader.components.TransformComponent;
import io.developersguild.rebelinvader.screens.GameScreen;
import io.developersguild.rebelinvader.systems.RenderingSystem;
import io.developersguild.rebelinvader.wgen.WorldGenerator;
/**
* Created by Vihan on 1/10/2016.
*/
public class Level {
public static final float SCREEN_HEIGHT = 15;
public static final float LEVEL_WIDTH = 10;
public static final float LEVEL_HEIGHT = SCREEN_HEIGHT * 20; // I think the second number is the number of screens
public static final int LEVEL_STATE_RUNNING = 1;
public static final int LEVEL_STATE_GAME_OVER = 2;
public static final int LEVEL_STATE_GAME_WON = 3;
public static float playerHeight;
public final RandomXS128 rand;
public int state;
public int score;
private PooledEngine engine;
private WorldGenerator generator;
private World world;
public Level(PooledEngine engine) {
this.engine = engine;
this.rand = new RandomXS128();
}
public void create(World world) {
this.world = world;
Entity player = createPlayer();
createCamera(player);
createNebula();
createStars();
generator = new WorldGenerator(this);
generateObstacles(1.5f * SCREEN_HEIGHT, player);
this.state = LEVEL_STATE_RUNNING;
this.score = 0;
}
private void createCamera(Entity target) {
Entity entity = engine.createEntity();
CameraComponent camera = new CameraComponent();
camera.camera = engine.getSystem(RenderingSystem.class).getCamera();
camera.target = target;
entity.add(camera);
engine.addEntity(entity);
}
private Entity createPlayer() {
Entity entity = engine.createEntity();
AnimationComponent animation = engine.createComponent(AnimationComponent.class);
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
MovementComponent movement = engine.createComponent(MovementComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
PlayerComponent player = engine.createComponent(PlayerComponent.class);
StateComponent state = engine.createComponent(StateComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
animation.animations.put(PlayerComponent.STATE_NORMAL, Assets.shipNormal);
bounds.bounds.width = PlayerComponent.WIDTH;
bounds.bounds.height = PlayerComponent.HEIGHT;
position.pos.set(5.0f, 2.5f, 0.0f);
position.scale.set(2.0f / 3.0f, 2.0f / 3.0f);
// Health
player.maxHealth = (int) PlayerComponent.STARTING_HEALTH;
player.currentHealth = player.maxHealth;
// Create player body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(position.pos.x, position.pos.y);
body.body = world.createBody(bodyDef);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(PlayerComponent.WIDTH / 2.f, PlayerComponent.HEIGHT / 2.f);
// Create a fixture with the shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygon;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
// Assign shape to body
body.body.createFixture(fixtureDef);
// Clean up
polygon.dispose();
state.set(PlayerComponent.STATE_NORMAL);
entity.add(animation);
entity.add(bounds);
entity.add(movement);
entity.add(position);
entity.add(player);
entity.add(body);
entity.add(state);
entity.add(texture);
createHealthBar(entity, null);
createPowerBar(entity, null);
engine.addEntity(entity);
return entity;
}
public void createStructure(float x, float y, Entity player, TextureRegion region) {
Entity entity = engine.createEntity();
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
StateComponent state = engine.createComponent(StateComponent.class);
StructureComponent structure = engine.createComponent(StructureComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
HeightDisposableComponent disposable = engine.createComponent(HeightDisposableComponent.class);
// Health
structure.maxHealth = StructureComponent.STARTING_HEALTH;
structure.currentHealth = structure.maxHealth;
structure.target = player;
state.set(StructureComponent.STATE_ALIVE);
bounds.bounds.width = StructureComponent.WIDTH;
bounds.bounds.height = StructureComponent.HEIGHT;
position.pos.set(x, y, 1.0f);
position.scale.set(1f, 1f);
texture.region = region;
// Create body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.StaticBody;
bodyDef.position.set(position.pos.x, position.pos.y);
body.body = world.createBody(bodyDef);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(StructureComponent.WIDTH / 2.f, StructureComponent.HEIGHT / 2.f);
// Assign shape to body
body.body.createFixture(polygon, 0.0f);
// Clean up
polygon.dispose();
entity.add(structure);
entity.add(bounds);
entity.add(position);
entity.add(state);
entity.add(texture);
entity.add(body);
entity.add(disposable);
createHealthBar(entity, disposable);
engine.addEntity(entity);
}
public void createEnemy(float x, float y, Entity player, int textureIdx) {
Entity entity = engine.createEntity();
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
EnemyComponent enemy = engine.createComponent(EnemyComponent.class);
MovementComponent mov = engine.createComponent(MovementComponent.class);
StateComponent state = engine.createComponent(StateComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
HeightDisposableComponent disposable = engine.createComponent(HeightDisposableComponent.class);
// Health
enemy.maxHealth = EnemyComponent.STARTING_HEALTH;
enemy.currentHealth = enemy.maxHealth;
enemy.target = player;
state.set(EnemyComponent.STATE_ALIVE);
bounds.bounds.width = EnemyComponent.WIDTH;
bounds.bounds.height = EnemyComponent.HEIGHT;
position.pos.set(x, y, 1f);
position.scale.set(2f, 2f);
texture.region = Assets.enemyRegions[textureIdx];
// Create player body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(position.pos.x, position.pos.y);
body.body = world.createBody(bodyDef);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(EnemyComponent.WIDTH / 2.f, EnemyComponent.HEIGHT / 2.f);
// Create a fixture with the shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygon;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
// Assign shape to body
body.body.createFixture(fixtureDef);
// Clean up
polygon.dispose();
entity.add(body);
entity.add(bounds);
entity.add(enemy);
entity.add(mov);
entity.add(position);
entity.add(state);
entity.add(texture);
entity.add(disposable);
createHealthBar(entity, disposable);
engine.addEntity(entity);
}
public void createBullet(Entity origin) {
Entity entity = engine.createEntity();
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
BulletComponent bullet = engine.createComponent(BulletComponent.class);
MovementComponent mov = engine.createComponent(MovementComponent.class);
StateComponent state = engine.createComponent(StateComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
TransformComponent pos = engine.createComponent(TransformComponent.class);
bullet.origin = origin;
state.set(BulletComponent.STATE_NORMAL);
bounds.bounds.width = BulletComponent.WIDTH;
bounds.bounds.height = BulletComponent.HEIGHT;
texture.region = Assets.bulletRegion;
if (origin.getComponent(PlayerComponent.class) != null) { // If player fired
texture.color = Color.WHITE;
} else { // If enemy or anyone else fired
texture.color = Color.RED;
}
// Get origin position
float x = origin.getComponent(TransformComponent.class).pos.x;
float y;
if (origin.getComponent(PlayerComponent.class) != null) { // If player fired
y = origin.getComponent(TransformComponent.class).pos.y + origin.getComponent(BoundsComponent.class).bounds.height / 2f;
// Add randomized horizontal velocity to the bullet
float randomDegree = MathUtils.random(-BulletComponent.HORIZONTAL_SHIFT_DEGREE, BulletComponent.HORIZONTAL_SHIFT_DEGREE);
float randomRadian = randomDegree * MathUtils.degreesToRadians;
bullet.HORIZONTAL_VELOCITY = BulletComponent.PLAYER_BULLET_VELOCITY * (float)Math.tan(randomRadian);
} else { // If enemy or anyone else fired
y = origin.getComponent(TransformComponent.class).pos.y - origin.getComponent(BoundsComponent.class).bounds.height / 2f;
}
pos.pos.set(x, y, 1f);
pos.scale.set(1f, 1f);
// Create bullet body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(pos.pos.x, pos.pos.y);
body.body = world.createBody(bodyDef);
body.body.setBullet(true);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(BulletComponent.WIDTH / 2.f, BulletComponent.HEIGHT / 2.f);
// Create a fixture with the shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygon;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
// Assign shape to body
body.body.createFixture(fixtureDef);
// Clean up
polygon.dispose();
entity.add(body);
entity.add(bounds);
entity.add(bullet);
entity.add(mov);
entity.add(state);
entity.add(texture);
entity.add(pos);
engine.addEntity(entity);
}
public void createMissile(Entity origin) {
Entity entity = engine.createEntity();
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
MissileComponent missile = engine.createComponent(MissileComponent.class);
MovementComponent mov = engine.createComponent(MovementComponent.class);
StateComponent state = engine.createComponent(StateComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
TransformComponent pos = engine.createComponent(TransformComponent.class);
missile.origin = origin;
state.set(MissileComponent.STATE_NORMAL);
missile.accelerator = 0;
missile.currentTime = 0;
bounds.bounds.width = MissileComponent.WIDTH;
bounds.bounds.height = MissileComponent.HEIGHT;
texture.region = Assets.missileRegion;
// Get origin position
float x = origin.getComponent(TransformComponent.class).pos.x;
float y = origin.getComponent(TransformComponent.class).pos.y + origin.getComponent(BoundsComponent.class).bounds.height / 2f;
pos.pos.set(x, y, 1f);
pos.scale.set(1f, 1f);
// Create missile body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(pos.pos.x, pos.pos.y);
body.body = world.createBody(bodyDef);
body.body.setBullet(true);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(MissileComponent.WIDTH / 2.f, MissileComponent.HEIGHT / 2.f);
// Create a fixture with the shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygon;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
// Assign shape to body
body.body.createFixture(fixtureDef);
// Clean up
polygon.dispose();
entity.add(body);
entity.add(bounds);
entity.add(missile);
entity.add(mov);
entity.add(state);
entity.add(texture);
entity.add(pos);
engine.addEntity(entity);
}
public void createExplosion(Entity origin) {
Entity entity = engine.createEntity();
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
ExplosionComponent explosion = engine.createComponent(ExplosionComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
TransformComponent pos = engine.createComponent(TransformComponent.class);
explosion.origin = origin;
explosion.currentTime = 0;
bounds.bounds.width = ExplosionComponent.WIDTH;
bounds.bounds.height = ExplosionComponent.HEIGHT;
texture.region = Assets.explosionTexRegion;
// Get origin position
float x = origin.getComponent(TransformComponent.class).pos.x;
float y = origin.getComponent(TransformComponent.class).pos.y + origin.getComponent(BoundsComponent.class).bounds.height / 2f;
float scaleRatio = 2.0f;
pos.pos.set(x, y, 1f);
pos.scale.set(scaleRatio, scaleRatio);
// Create explosion body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(pos.pos.x, pos.pos.y);
body.body = world.createBody(bodyDef);
//body.body.setBullet(true);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(bounds.bounds.width / 2f * scaleRatio, bounds.bounds.height / 2f * scaleRatio);
// Create a fixture with the shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygon;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
// Assign shape to body
body.body.createFixture(fixtureDef);
// Clean up
polygon.dispose();
entity.add(body);
entity.add(bounds);
entity.add(explosion);
entity.add(texture);
entity.add(pos);
engine.addEntity(entity);
}
private void createHealthBar(Entity target, HeightDisposableComponent disposable) {
Entity entity = engine.createEntity();
if (disposable != null) {
disposable.childEntity = entity;
}
TextureComponent texture = engine.createComponent(TextureComponent.class);
HealthComponent health = engine.createComponent(HealthComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
health.target = target;
health.targetPos = target.getComponent(TransformComponent.class).pos;
health.targetPos.y -= target.getComponent(BoundsComponent.class).bounds.height;
health.doRender = false;
// Determine type of entity
if (target.getComponent(PlayerComponent.class) != null) {
health.maxHealth = PlayerComponent.STARTING_HEALTH * HealthComponent.healthMultiplier;
health.currentHealth = health.maxHealth;
health.lengthRatio = 2.0f / 3.0f;
health.widthRatio = 2.0f / 3.0f;
health.belongsTo = HealthComponent.IS_PLAYER;
position.scale.set(health.lengthRatio, health.widthRatio);
} else if (target.getComponent(StructureComponent.class) != null) {
health.maxHealth = StructureComponent.STARTING_HEALTH * HealthComponent.healthMultiplier;
health.currentHealth = health.maxHealth;
health.lengthRatio = 1.0f / 3.0f;
health.widthRatio = 2.0f / 3.0f;
health.belongsTo = HealthComponent.IS_STRUCTURE;
position.scale.set(health.lengthRatio, health.widthRatio);
} else if (target.getComponent(EnemyComponent.class) != null) {
health.maxHealth = EnemyComponent.STARTING_HEALTH * HealthComponent.healthMultiplier;
health.currentHealth = health.maxHealth;
health.lengthRatio = 2.0f / 3.0f;
health.widthRatio = 2.0f / 3.0f;
health.belongsTo = HealthComponent.IS_ENEMY;
position.scale.set(health.lengthRatio, health.widthRatio);
}
if(target.getComponent(PlayerComponent.class) != null) texture.region = Assets.healthRegionGreen;
else texture.region = Assets.healthRegionRed;
entity.add(health);
entity.add(position);
entity.add(texture);
engine.addEntity(entity);
}
private void createPowerBar(Entity target, HeightDisposableComponent disposable) {
Entity entity = engine.createEntity();
if (disposable != null) {
disposable.childEntity = entity;
}
TextureComponent texture = engine.createComponent(TextureComponent.class);
PowerComponent power = engine.createComponent(PowerComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
power.target = target;
power.targetPos = target.getComponent(TransformComponent.class).pos;
power.targetPos.y -= target.getComponent(BoundsComponent.class).bounds.height;
// Determine type of entity
if (target.getComponent(PlayerComponent.class) != null) {
power.maxPower = PowerComponent.MAX_POWER;
power.currentPower = 0;
power.lengthRatio = 2.0f / 3.0f;
power.widthRatio = 2.0f / 3.0f;
position.scale.set(power.lengthRatio, power.widthRatio);
}
// Prevent overlap with health bar
power.targetPos.y -= power.widthRatio;
// Need a different texture
texture.region = Assets.healthRegionBlue;
entity.add(power);
entity.add(position);
entity.add(texture);
engine.addEntity(entity);
}
private void createNebula() {
Entity entity = engine.createEntity();
BackgroundComponent background = engine.createComponent(BackgroundComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
background.type = BackgroundComponent.TYPE_NEBULA;
texture.region = Assets.bgNebulaRegion;
entity.add(background);
entity.add(position);
entity.add(texture);
engine.addEntity(entity);
}
private void createStars() {
Entity entity = engine.createEntity();
BackgroundComponent background = engine.createComponent(BackgroundComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
background.type = BackgroundComponent.TYPE_STARS;
texture.region = Assets.bgStarsRegion;
entity.add(background);
entity.add(position);
entity.add(texture);
engine.addEntity(entity);
}
//Makes sure that the world is generated up to the given height, and cleans up entities out of bounds
public void generateObstacles(float heightSoFar, Entity player) {
generator.provideWorld(heightSoFar, player);
playerHeight = heightSoFar;
}
}
| core/src/io/developersguild/rebelinvader/Level.java | package io.developersguild.rebelinvader;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.PooledEngine;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.RandomXS128;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import io.developersguild.rebelinvader.components.AnimationComponent;
import io.developersguild.rebelinvader.components.BackgroundComponent;
import io.developersguild.rebelinvader.components.BodyComponent;
import io.developersguild.rebelinvader.components.BoundsComponent;
import io.developersguild.rebelinvader.components.BulletComponent;
import io.developersguild.rebelinvader.components.CameraComponent;
import io.developersguild.rebelinvader.components.EnemyComponent;
import io.developersguild.rebelinvader.components.ExplosionComponent;
import io.developersguild.rebelinvader.components.HealthComponent;
import io.developersguild.rebelinvader.components.HeightDisposableComponent;
import io.developersguild.rebelinvader.components.MovementComponent;
import io.developersguild.rebelinvader.components.MissileComponent;
import io.developersguild.rebelinvader.components.PlayerComponent;
import io.developersguild.rebelinvader.components.PowerComponent;
import io.developersguild.rebelinvader.components.StateComponent;
import io.developersguild.rebelinvader.components.StructureComponent;
import io.developersguild.rebelinvader.components.TextureComponent;
import io.developersguild.rebelinvader.components.TransformComponent;
import io.developersguild.rebelinvader.screens.GameScreen;
import io.developersguild.rebelinvader.systems.RenderingSystem;
import io.developersguild.rebelinvader.wgen.WorldGenerator;
/**
* Created by Vihan on 1/10/2016.
*/
public class Level {
public static final float SCREEN_HEIGHT = 15;
public static final float LEVEL_WIDTH = 10;
public static final float LEVEL_HEIGHT = SCREEN_HEIGHT * 20; // I think the second number is the number of screens
public static final int LEVEL_STATE_RUNNING = 1;
public static final int LEVEL_STATE_GAME_OVER = 2;
public static final int LEVEL_STATE_GAME_WON = 3;
public static float playerHeight;
public final RandomXS128 rand;
public int state;
public int score;
private PooledEngine engine;
private WorldGenerator generator;
private World world;
public Level(PooledEngine engine) {
this.engine = engine;
this.rand = new RandomXS128();
}
public void create(World world) {
this.world = world;
Entity player = createPlayer();
createCamera(player);
createNebula();
createStars();
generator = new WorldGenerator(this);
generateObstacles(1.5f * SCREEN_HEIGHT, player);
this.state = LEVEL_STATE_RUNNING;
this.score = 0;
}
private void createCamera(Entity target) {
Entity entity = engine.createEntity();
CameraComponent camera = new CameraComponent();
camera.camera = engine.getSystem(RenderingSystem.class).getCamera();
camera.target = target;
entity.add(camera);
engine.addEntity(entity);
}
private Entity createPlayer() {
Entity entity = engine.createEntity();
AnimationComponent animation = engine.createComponent(AnimationComponent.class);
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
MovementComponent movement = engine.createComponent(MovementComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
PlayerComponent player = engine.createComponent(PlayerComponent.class);
StateComponent state = engine.createComponent(StateComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
animation.animations.put(PlayerComponent.STATE_NORMAL, Assets.shipNormal);
bounds.bounds.width = PlayerComponent.WIDTH;
bounds.bounds.height = PlayerComponent.HEIGHT;
position.pos.set(5.0f, 2.5f, 0.0f);
position.scale.set(2.0f / 3.0f, 2.0f / 3.0f);
// Health
player.maxHealth = (int) PlayerComponent.STARTING_HEALTH;
player.currentHealth = player.maxHealth;
// Create player body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(position.pos.x, position.pos.y);
body.body = world.createBody(bodyDef);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(PlayerComponent.WIDTH / 2.f, PlayerComponent.HEIGHT / 2.f);
// Create a fixture with the shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygon;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
// Assign shape to body
body.body.createFixture(fixtureDef);
// Clean up
polygon.dispose();
state.set(PlayerComponent.STATE_NORMAL);
entity.add(animation);
entity.add(bounds);
entity.add(movement);
entity.add(position);
entity.add(player);
entity.add(body);
entity.add(state);
entity.add(texture);
createHealthBar(entity, null);
createPowerBar(entity, null);
engine.addEntity(entity);
return entity;
}
public void createStructure(float x, float y, Entity player, TextureRegion region) {
Entity entity = engine.createEntity();
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
StateComponent state = engine.createComponent(StateComponent.class);
StructureComponent structure = engine.createComponent(StructureComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
HeightDisposableComponent disposable = engine.createComponent(HeightDisposableComponent.class);
// Health
structure.maxHealth = StructureComponent.STARTING_HEALTH;
structure.currentHealth = structure.maxHealth;
structure.target = player;
state.set(StructureComponent.STATE_ALIVE);
bounds.bounds.width = StructureComponent.WIDTH;
bounds.bounds.height = StructureComponent.HEIGHT;
position.pos.set(x, y, 1.0f);
position.scale.set(1f, 1f);
texture.region = region;
// Create body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.StaticBody;
bodyDef.position.set(position.pos.x, position.pos.y);
body.body = world.createBody(bodyDef);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(StructureComponent.WIDTH / 2.f, StructureComponent.HEIGHT / 2.f);
// Assign shape to body
body.body.createFixture(polygon, 0.0f);
// Clean up
polygon.dispose();
entity.add(structure);
entity.add(bounds);
entity.add(position);
entity.add(state);
entity.add(texture);
entity.add(body);
entity.add(disposable);
createHealthBar(entity, disposable);
engine.addEntity(entity);
}
public void createEnemy(float x, float y, Entity player, int textureIdx) {
Entity entity = engine.createEntity();
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
EnemyComponent enemy = engine.createComponent(EnemyComponent.class);
MovementComponent mov = engine.createComponent(MovementComponent.class);
StateComponent state = engine.createComponent(StateComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
HeightDisposableComponent disposable = engine.createComponent(HeightDisposableComponent.class);
// Health
enemy.maxHealth = EnemyComponent.STARTING_HEALTH;
enemy.currentHealth = enemy.maxHealth;
enemy.target = player;
state.set(EnemyComponent.STATE_ALIVE);
bounds.bounds.width = EnemyComponent.WIDTH;
bounds.bounds.height = EnemyComponent.HEIGHT;
position.pos.set(x, y, 1f);
position.scale.set(2f, 2f);
texture.region = Assets.enemyRegions[textureIdx];
// Create player body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(position.pos.x, position.pos.y);
body.body = world.createBody(bodyDef);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(EnemyComponent.WIDTH / 2.f, EnemyComponent.HEIGHT / 2.f);
// Create a fixture with the shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygon;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
// Assign shape to body
body.body.createFixture(fixtureDef);
// Clean up
polygon.dispose();
entity.add(body);
entity.add(bounds);
entity.add(enemy);
entity.add(mov);
entity.add(position);
entity.add(state);
entity.add(texture);
entity.add(disposable);
createHealthBar(entity, disposable);
engine.addEntity(entity);
}
public void createBullet(Entity origin) {
Entity entity = engine.createEntity();
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
BulletComponent bullet = engine.createComponent(BulletComponent.class);
MovementComponent mov = engine.createComponent(MovementComponent.class);
StateComponent state = engine.createComponent(StateComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
TransformComponent pos = engine.createComponent(TransformComponent.class);
bullet.origin = origin;
state.set(BulletComponent.STATE_NORMAL);
bounds.bounds.width = BulletComponent.WIDTH;
bounds.bounds.height = BulletComponent.HEIGHT;
texture.region = Assets.bulletRegion;
if (origin.getComponent(PlayerComponent.class) != null) { // If player fired
texture.color = Color.WHITE;
} else { // If enemy or anyone else fired
texture.color = Color.RED;
}
// Get origin position
float x = origin.getComponent(TransformComponent.class).pos.x;
float y;
if (origin.getComponent(PlayerComponent.class) != null) { // If player fired
y = origin.getComponent(TransformComponent.class).pos.y + origin.getComponent(BoundsComponent.class).bounds.height / 2f;
// Add randomized horizontal velocity to the bullet
float randomDegree = MathUtils.random(-BulletComponent.HORIZONTAL_SHIFT_DEGREE, BulletComponent.HORIZONTAL_SHIFT_DEGREE);
float randomRadian = randomDegree * MathUtils.degreesToRadians;
bullet.HORIZONTAL_VELOCITY = BulletComponent.PLAYER_BULLET_VELOCITY * (float)Math.tan(randomRadian);
} else { // If enemy or anyone else fired
y = origin.getComponent(TransformComponent.class).pos.y - origin.getComponent(BoundsComponent.class).bounds.height / 2f;
}
pos.pos.set(x, y, 1f);
pos.scale.set(1f, 1f);
// Create bullet body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(pos.pos.x, pos.pos.y);
body.body = world.createBody(bodyDef);
body.body.setBullet(true);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(BulletComponent.WIDTH / 2.f, BulletComponent.HEIGHT / 2.f);
// Create a fixture with the shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygon;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
// Assign shape to body
body.body.createFixture(fixtureDef);
// Clean up
polygon.dispose();
entity.add(body);
entity.add(bounds);
entity.add(bullet);
entity.add(mov);
entity.add(state);
entity.add(texture);
entity.add(pos);
engine.addEntity(entity);
}
public void createMissile(Entity origin) {
Entity entity = engine.createEntity();
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
MissileComponent missile = engine.createComponent(MissileComponent.class);
MovementComponent mov = engine.createComponent(MovementComponent.class);
StateComponent state = engine.createComponent(StateComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
TransformComponent pos = engine.createComponent(TransformComponent.class);
missile.origin = origin;
state.set(MissileComponent.STATE_NORMAL);
missile.accelerator = 0;
missile.currentTime = 0;
bounds.bounds.width = MissileComponent.WIDTH;
bounds.bounds.height = MissileComponent.HEIGHT;
texture.region = Assets.missileRegion;
// Get origin position
float x = origin.getComponent(TransformComponent.class).pos.x;
float y = origin.getComponent(TransformComponent.class).pos.y + origin.getComponent(BoundsComponent.class).bounds.height / 2f;
pos.pos.set(x, y, 1f);
pos.scale.set(1f, 1f);
// Create missile body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(pos.pos.x, pos.pos.y);
body.body = world.createBody(bodyDef);
body.body.setBullet(true);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(MissileComponent.WIDTH / 2.f, MissileComponent.HEIGHT / 2.f);
// Create a fixture with the shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygon;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
// Assign shape to body
body.body.createFixture(fixtureDef);
// Clean up
polygon.dispose();
entity.add(body);
entity.add(bounds);
entity.add(missile);
entity.add(mov);
entity.add(state);
entity.add(texture);
entity.add(pos);
engine.addEntity(entity);
}
public void createExplosion(Entity origin) {
Entity entity = engine.createEntity();
BodyComponent body = engine.createComponent(BodyComponent.class);
BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
ExplosionComponent explosion = engine.createComponent(ExplosionComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
TransformComponent pos = engine.createComponent(TransformComponent.class);
explosion.origin = origin;
explosion.currentTime = 0;
bounds.bounds.width = ExplosionComponent.WIDTH;
bounds.bounds.height = ExplosionComponent.HEIGHT;
texture.region = Assets.explosionTexRegion;
// Get origin position
float x = origin.getComponent(TransformComponent.class).pos.x;
float y = origin.getComponent(TransformComponent.class).pos.y + origin.getComponent(BoundsComponent.class).bounds.height / 2f;
float scaleRatio = 1.0f;
pos.pos.set(x, y, 1f);
pos.scale.set(scaleRatio, scaleRatio);
// Create explosion body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(pos.pos.x, pos.pos.y);
body.body = world.createBody(bodyDef);
//body.body.setBullet(true);
body.body.setUserData(this);
// Define a shape with the vertices
PolygonShape polygon = new PolygonShape();
polygon.setAsBox(bounds.bounds.width / 2f * scaleRatio, bounds.bounds.height / 2f * scaleRatio);
// Create a fixture with the shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = polygon;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
// Assign shape to body
body.body.createFixture(fixtureDef);
// Clean up
polygon.dispose();
entity.add(body);
entity.add(bounds);
entity.add(explosion);
entity.add(texture);
entity.add(pos);
engine.addEntity(entity);
}
private void createHealthBar(Entity target, HeightDisposableComponent disposable) {
Entity entity = engine.createEntity();
if (disposable != null) {
disposable.childEntity = entity;
}
TextureComponent texture = engine.createComponent(TextureComponent.class);
HealthComponent health = engine.createComponent(HealthComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
health.target = target;
health.targetPos = target.getComponent(TransformComponent.class).pos;
health.targetPos.y -= target.getComponent(BoundsComponent.class).bounds.height;
health.doRender = false;
// Determine type of entity
if (target.getComponent(PlayerComponent.class) != null) {
health.maxHealth = PlayerComponent.STARTING_HEALTH * HealthComponent.healthMultiplier;
health.currentHealth = health.maxHealth;
health.lengthRatio = 2.0f / 3.0f;
health.widthRatio = 2.0f / 3.0f;
health.belongsTo = HealthComponent.IS_PLAYER;
position.scale.set(health.lengthRatio, health.widthRatio);
} else if (target.getComponent(StructureComponent.class) != null) {
health.maxHealth = StructureComponent.STARTING_HEALTH * HealthComponent.healthMultiplier;
health.currentHealth = health.maxHealth;
health.lengthRatio = 1.0f / 3.0f;
health.widthRatio = 2.0f / 3.0f;
health.belongsTo = HealthComponent.IS_STRUCTURE;
position.scale.set(health.lengthRatio, health.widthRatio);
} else if (target.getComponent(EnemyComponent.class) != null) {
health.maxHealth = EnemyComponent.STARTING_HEALTH * HealthComponent.healthMultiplier;
health.currentHealth = health.maxHealth;
health.lengthRatio = 2.0f / 3.0f;
health.widthRatio = 2.0f / 3.0f;
health.belongsTo = HealthComponent.IS_ENEMY;
position.scale.set(health.lengthRatio, health.widthRatio);
}
if(target.getComponent(PlayerComponent.class) != null) texture.region = Assets.healthRegionGreen;
else texture.region = Assets.healthRegionRed;
entity.add(health);
entity.add(position);
entity.add(texture);
engine.addEntity(entity);
}
private void createPowerBar(Entity target, HeightDisposableComponent disposable) {
Entity entity = engine.createEntity();
if (disposable != null) {
disposable.childEntity = entity;
}
TextureComponent texture = engine.createComponent(TextureComponent.class);
PowerComponent power = engine.createComponent(PowerComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
power.target = target;
power.targetPos = target.getComponent(TransformComponent.class).pos;
power.targetPos.y -= target.getComponent(BoundsComponent.class).bounds.height;
// Determine type of entity
if (target.getComponent(PlayerComponent.class) != null) {
power.maxPower = PowerComponent.MAX_POWER;
power.currentPower = 0;
power.lengthRatio = 2.0f / 3.0f;
power.widthRatio = 2.0f / 3.0f;
position.scale.set(power.lengthRatio, power.widthRatio);
}
// Prevent overlap with health bar
power.targetPos.y -= power.widthRatio;
// Need a different texture
texture.region = Assets.healthRegionBlue;
entity.add(power);
entity.add(position);
entity.add(texture);
engine.addEntity(entity);
}
private void createNebula() {
Entity entity = engine.createEntity();
BackgroundComponent background = engine.createComponent(BackgroundComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
background.type = BackgroundComponent.TYPE_NEBULA;
texture.region = Assets.bgNebulaRegion;
entity.add(background);
entity.add(position);
entity.add(texture);
engine.addEntity(entity);
}
private void createStars() {
Entity entity = engine.createEntity();
BackgroundComponent background = engine.createComponent(BackgroundComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
TransformComponent position = engine.createComponent(TransformComponent.class);
background.type = BackgroundComponent.TYPE_STARS;
texture.region = Assets.bgStarsRegion;
entity.add(background);
entity.add(position);
entity.add(texture);
engine.addEntity(entity);
}
//Makes sure that the world is generated up to the given height, and cleans up entities out of bounds
public void generateObstacles(float heightSoFar, Entity player) {
generator.provideWorld(heightSoFar, player);
playerHeight = heightSoFar;
}
}
| Explosion radius larger
| core/src/io/developersguild/rebelinvader/Level.java | Explosion radius larger | <ide><path>ore/src/io/developersguild/rebelinvader/Level.java
<ide> float x = origin.getComponent(TransformComponent.class).pos.x;
<ide> float y = origin.getComponent(TransformComponent.class).pos.y + origin.getComponent(BoundsComponent.class).bounds.height / 2f;
<ide>
<del> float scaleRatio = 1.0f;
<add> float scaleRatio = 2.0f;
<ide>
<ide> pos.pos.set(x, y, 1f);
<ide> pos.scale.set(scaleRatio, scaleRatio); |
|
Java | apache-2.0 | 3e9a15a4e66891d2b7cda699756e27d3f9634245 | 0 | cniesen/rice,jwillia/kc-rice1,cniesen/rice,shahess/rice,jwillia/kc-rice1,gathreya/rice-kc,rojlarge/rice-kc,kuali/kc-rice,geothomasp/kualico-rice-kc,rojlarge/rice-kc,sonamuthu/rice-1,bhutchinson/rice,kuali/kc-rice,rojlarge/rice-kc,sonamuthu/rice-1,ewestfal/rice,jwillia/kc-rice1,gathreya/rice-kc,ewestfal/rice,UniversityOfHawaiiORS/rice,gathreya/rice-kc,bhutchinson/rice,kuali/kc-rice,geothomasp/kualico-rice-kc,ewestfal/rice,jwillia/kc-rice1,shahess/rice,ewestfal/rice,bhutchinson/rice,gathreya/rice-kc,ewestfal/rice,geothomasp/kualico-rice-kc,shahess/rice,kuali/kc-rice,ewestfal/rice-svn2git-test,kuali/kc-rice,jwillia/kc-rice1,bsmith83/rice-1,sonamuthu/rice-1,ewestfal/rice-svn2git-test,smith750/rice,UniversityOfHawaiiORS/rice,geothomasp/kualico-rice-kc,bhutchinson/rice,rojlarge/rice-kc,cniesen/rice,smith750/rice,bsmith83/rice-1,smith750/rice,bsmith83/rice-1,geothomasp/kualico-rice-kc,smith750/rice,cniesen/rice,cniesen/rice,rojlarge/rice-kc,ewestfal/rice-svn2git-test,shahess/rice,bhutchinson/rice,UniversityOfHawaiiORS/rice,shahess/rice,UniversityOfHawaiiORS/rice,smith750/rice,bsmith83/rice-1,UniversityOfHawaiiORS/rice,sonamuthu/rice-1,ewestfal/rice-svn2git-test,gathreya/rice-kc | package org.kuali.rice.kew.api.document.lookup;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
import org.kuali.rice.core.api.mo.ModelBuilder;
import org.kuali.rice.kew.api.document.Document;
import org.kuali.rice.kew.api.document.attribute.DocumentAttribute;
import org.kuali.rice.kew.api.document.attribute.DocumentAttributeContract;
import org.kuali.rice.kew.api.document.attribute.DocumentAttributeFactory;
import org.w3c.dom.Element;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* An immutable data transfer object implementation of the {@link DocumentLookupResultContract}. Instances of this
* class should be constructed using the nested {@link Builder} class.
*
* @author Kuali Rice Team ([email protected])
*/
@XmlRootElement(name = DocumentLookupResult.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = DocumentLookupResult.Constants.TYPE_NAME, propOrder = {
DocumentLookupResult.Elements.DOCUMENT,
DocumentLookupResult.Elements.DOCUMENT_ATTRIBUTES,
CoreConstants.CommonElements.FUTURE_ELEMENTS
})
public final class DocumentLookupResult extends AbstractDataTransferObject implements DocumentLookupResultContract {
@XmlElement(name = Elements.DOCUMENT, required = false)
private final Document document;
@XmlElementWrapper(name = Elements.DOCUMENT_ATTRIBUTES, required = true)
@XmlElement(name = Elements.DOCUMENT_ATTRIBUTE, required = false)
private final List<DocumentAttribute> documentAttributes;
@SuppressWarnings("unused")
@XmlAnyElement
private final Collection<Element> _futureElements = null;
/**
* Private constructor used only by JAXB.
*/
@SuppressWarnings("unused")
private DocumentLookupResult() {
this.document = null;
this.documentAttributes = null;
}
private DocumentLookupResult(Builder builder) {
this.document = builder.getDocument().build();
List<DocumentAttribute> documentAttributes = new ArrayList<DocumentAttribute>();
for (DocumentAttribute.AbstractBuilder<?> documentAttribute : builder.getDocumentAttributes()) {
documentAttributes.add(documentAttribute.build());
}
this.documentAttributes = Collections.unmodifiableList(documentAttributes);
}
@Override
public Document getDocument() {
return this.document;
}
@Override
public List<DocumentAttribute> getDocumentAttributes() {
return this.documentAttributes;
}
/**
* Returns an unmodifiable list of all document attributes on this result which have the given name. It is legal
* for a result to contain more than one attribute of the same name. In these cases, this represents a document
* attribute which has more than one value.
*
* @param attributeName the attribute name of document attributes to retrieve
* @return an unmodifiable list of document attributes with the given name, will never be null but may be empty
*/
public List<DocumentAttribute> getDocumentAttributeByName(String attributeName) {
List<DocumentAttribute> namedAttributes = new ArrayList<DocumentAttribute>();
for (DocumentAttribute attribute : getDocumentAttributes()) {
if (attribute.getName().equals(attributeName)) {
namedAttributes.add(attribute);
}
}
return Collections.unmodifiableList(namedAttributes);
}
/**
* Returns a single document attribute from this result which has the given name. If there is more than one
* document attribute on this result with the given name, only a single one will be returned (though it is
* undeterministic which one will this will be). If there are no attributes on this result with the given name
* then this method will return null.
*
* @param attributeName the attribute name of the document attribute to retrieve
* @return a single document attribute with the given name, or null if one does not exist
*/
public DocumentAttribute getSingleDocumentAttributeByName(String attributeName) {
List<DocumentAttribute> namedAttributes = getDocumentAttributeByName(attributeName);
if (namedAttributes.isEmpty()) {
return null;
}
return namedAttributes.get(0);
}
/**
* A builder which can be used to construct {@link DocumentLookupResult} instances. Enforces the constraints of the
* {@link DocumentLookupResultContract}.
*/
public final static class Builder implements Serializable, ModelBuilder, DocumentLookupResultContract {
private Document.Builder document;
private List<DocumentAttribute.AbstractBuilder<?>> documentAttributes;
private Builder(Document.Builder document) {
setDocument(document);
setDocumentAttributes(new ArrayList<DocumentAttribute.AbstractBuilder<?>>());
}
/**
* Create a builder for the document lookup result and initialize it with the given document builder.
* Additionally initializes the list of document attribute builders on the new instance to an empty list.
*
* @param document the document builder with which to initialize the returned builder instance
*
* @return a builder instance initialized with the given document builder
*
* @throws IllegalArgumentException if the given document builder is null
*/
public static Builder create(Document.Builder document) {
return new Builder(document);
}
/**
* Creates a new builder instance initialized with copies of the properties from the given contract.
*
* @param contract the contract from which to copy properties
*
* @return a builder instance initialized with properties from the given contract
*
* @throws IllegalArgumentException if the given contract is null
*/
public static Builder create(DocumentLookupResultContract contract) {
if (contract == null) {
throw new IllegalArgumentException("contract was null");
}
Document.Builder documentBuilder = Document.Builder.create(contract.getDocument());
Builder builder = create(documentBuilder);
List<DocumentAttribute.AbstractBuilder<?>> documentAttributes = new ArrayList<DocumentAttribute.AbstractBuilder<?>>();
for (DocumentAttributeContract documentAttributeContract : contract.getDocumentAttributes()) {
documentAttributes.add(DocumentAttributeFactory.loadContractIntoBuilder(documentAttributeContract));
}
builder.setDocumentAttributes(documentAttributes);
return builder;
}
public DocumentLookupResult build() {
return new DocumentLookupResult(this);
}
@Override
public Document.Builder getDocument() {
return this.document;
}
@Override
public List<DocumentAttribute.AbstractBuilder<?>> getDocumentAttributes() {
return this.documentAttributes;
}
public void setDocument(Document.Builder document) {
if (document == null) {
throw new IllegalArgumentException("document was null");
}
this.document = document;
}
public void setDocumentAttributes(List<DocumentAttribute.AbstractBuilder<?>> documentAttributes) {
this.documentAttributes = documentAttributes;
}
}
/**
* Defines some internal constants used on this class.
*/
static class Constants {
final static String ROOT_ELEMENT_NAME = "documentLookupResult";
final static String TYPE_NAME = "DocumentLookupResultType";
}
/**
* A private class which exposes constants which define the XML element names to use when this object is marshalled to XML.
*/
static class Elements {
final static String DOCUMENT = "document";
final static String DOCUMENT_ATTRIBUTES = "documentAttributes";
final static String DOCUMENT_ATTRIBUTE = "documentAttribute";
}
}
| kew/api/src/main/java/org/kuali/rice/kew/api/document/lookup/DocumentLookupResult.java | package org.kuali.rice.kew.api.document.lookup;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
import org.kuali.rice.core.api.mo.ModelBuilder;
import org.kuali.rice.kew.api.document.Document;
import org.kuali.rice.kew.api.document.DocumentContract;
import org.kuali.rice.kew.api.document.attribute.DocumentAttribute;
import org.kuali.rice.kew.api.document.attribute.DocumentAttributeContract;
import org.kuali.rice.kew.api.document.attribute.DocumentAttributeFactory;
import org.w3c.dom.Element;
/**
* An immutable data transfer object implementation of the {@link DocumentLookupResultContract}. Instances of this
* class should be constructed using the nested {@link Builder} class.
*
* @author Kuali Rice Team ([email protected])
*/
@XmlRootElement(name = DocumentLookupResult.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = DocumentLookupResult.Constants.TYPE_NAME, propOrder = {
DocumentLookupResult.Elements.DOCUMENT,
DocumentLookupResult.Elements.DOCUMENT_ATTRIBUTES,
CoreConstants.CommonElements.FUTURE_ELEMENTS
})
public final class DocumentLookupResult extends AbstractDataTransferObject implements DocumentLookupResultContract {
@XmlElement(name = Elements.DOCUMENT, required = false)
private final Document document;
@XmlElementWrapper(name = Elements.DOCUMENT_ATTRIBUTES, required = true)
@XmlElement(name = Elements.DOCUMENT_ATTRIBUTE, required = false)
private final List<DocumentAttribute> documentAttributes;
@SuppressWarnings("unused")
@XmlAnyElement
private final Collection<Element> _futureElements = null;
/**
* Private constructor used only by JAXB.
*/
private DocumentLookupResult() {
this.document = null;
this.documentAttributes = null;
}
private DocumentLookupResult(Builder builder) {
this.document = builder.getDocument().build();
List<DocumentAttribute> documentAttributes = new ArrayList<DocumentAttribute>();
for (DocumentAttribute.AbstractBuilder<?> documentAttribute : builder.getDocumentAttributes()) {
documentAttributes.add(documentAttribute.build());
}
this.documentAttributes = Collections.unmodifiableList(documentAttributes);
}
@Override
public Document getDocument() {
return this.document;
}
@Override
public List<DocumentAttribute> getDocumentAttributes() {
return this.documentAttributes;
}
/**
* Returns an unmodifiable list of all document attributes on this result which have the given name. It is legal
* for a result to contain more than one attribute of the same name. In these cases, this represents a document
* attribute which has more than one value.
*
* @param attributeName the attribute name of document attributes to retrieve
* @return an unmodifiable list of document attributes with the given name, will never be null but may be empty
*/
public List<DocumentAttribute> getDocumentAttributeByName(String attributeName) {
List<DocumentAttribute> namedAttributes = new ArrayList<DocumentAttribute>();
for (DocumentAttribute attribute : getDocumentAttributes()) {
if (attribute.getName().equals(attributeName)) {
namedAttributes.add(attribute);
}
}
return Collections.unmodifiableList(namedAttributes);
}
/**
* Returns a single document attribute from this result which has the given name. If there is more than one
* document attribute on this result with the given name, only a single one will be returned (though it is
* undeterministic which one will this will be). If there are no attributes on this result with the given name
* then this method will return null.
*
* @param attributeName the attribute name of the document attribute to retrieve
* @return a single document attribute with the given name, or null if one does not exist
*/
public DocumentAttribute getSingleDocumentAttributeByName(String attributeName) {
List<DocumentAttribute> namedAttributes = getDocumentAttributeByName(attributeName);
if (namedAttributes.isEmpty()) {
return null;
}
return namedAttributes.get(0);
}
/**
* A builder which can be used to construct {@link DocumentLookupResult} instances. Enforces the constraints of the
* {@link DocumentLookupResultContract}.
*/
public final static class Builder implements Serializable, ModelBuilder, DocumentLookupResultContract {
private Document.Builder document;
private List<DocumentAttribute.AbstractBuilder<?>> documentAttributes;
private Builder(Document.Builder document) {
setDocument(document);
setDocumentAttributes(new ArrayList<DocumentAttribute.AbstractBuilder<?>>());
}
/**
* Create a builder for the document lookup result and initialize it with the given document builder.
* Additionally initializes the list of document attribute builders on the new instance to an empty list.
*
* @param document the document builder with which to initialize the returned builder instance
*
* @return a builder instance initialized with the given document builder
*
* @throws IllegalArgumentException if the given document builder is null
*/
public static Builder create(Document.Builder document) {
return new Builder(document);
}
/**
* Creates a new builder instance initialized with copies of the properties from the given contract.
*
* @param contract the contract from which to copy properties
*
* @return a builder instance initialized with properties from the given contract
*
* @throws IllegalArgumentException if the given contract is null
*/
public static Builder create(DocumentLookupResultContract contract) {
if (contract == null) {
throw new IllegalArgumentException("contract was null");
}
Document.Builder documentBuilder = Document.Builder.create(contract.getDocument());
Builder builder = create(documentBuilder);
List<DocumentAttribute.AbstractBuilder<?>> documentAttributes = new ArrayList<DocumentAttribute.AbstractBuilder<?>>();
for (DocumentAttributeContract documentAttributeContract : contract.getDocumentAttributes()) {
documentAttributes.add(DocumentAttributeFactory.loadContractIntoBuilder(documentAttributeContract));
}
builder.setDocumentAttributes(documentAttributes);
return builder;
}
public DocumentLookupResult build() {
return new DocumentLookupResult(this);
}
@Override
public Document.Builder getDocument() {
return this.document;
}
@Override
public List<DocumentAttribute.AbstractBuilder<?>> getDocumentAttributes() {
return this.documentAttributes;
}
public void setDocument(Document.Builder document) {
if (document == null) {
throw new IllegalArgumentException("document was null");
}
this.document = document;
}
public void setDocumentAttributes(List<DocumentAttribute.AbstractBuilder<?>> documentAttributes) {
this.documentAttributes = documentAttributes;
}
}
/**
* Defines some internal constants used on this class.
*/
static class Constants {
final static String ROOT_ELEMENT_NAME = "documentLookupResult";
final static String TYPE_NAME = "DocumentLookupResultType";
}
/**
* A private class which exposes constants which define the XML element names to use when this object is marshalled to XML.
*/
static class Elements {
final static String DOCUMENT = "document";
final static String DOCUMENT_ATTRIBUTES = "documentAttributes";
final static String DOCUMENT_ATTRIBUTE = "documentAttribute";
}
}
| KULRICE-5056 - simple code cleanup
| kew/api/src/main/java/org/kuali/rice/kew/api/document/lookup/DocumentLookupResult.java | KULRICE-5056 - simple code cleanup | <ide><path>ew/api/src/main/java/org/kuali/rice/kew/api/document/lookup/DocumentLookupResult.java
<ide> package org.kuali.rice.kew.api.document.lookup;
<ide>
<del>import java.io.Serializable;
<del>import java.util.ArrayList;
<del>import java.util.Collection;
<del>import java.util.Collections;
<del>import java.util.List;
<del>import java.util.Map;
<add>import org.kuali.rice.core.api.CoreConstants;
<add>import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
<add>import org.kuali.rice.core.api.mo.ModelBuilder;
<add>import org.kuali.rice.kew.api.document.Document;
<add>import org.kuali.rice.kew.api.document.attribute.DocumentAttribute;
<add>import org.kuali.rice.kew.api.document.attribute.DocumentAttributeContract;
<add>import org.kuali.rice.kew.api.document.attribute.DocumentAttributeFactory;
<add>import org.w3c.dom.Element;
<add>
<ide> import javax.xml.bind.annotation.XmlAccessType;
<ide> import javax.xml.bind.annotation.XmlAccessorType;
<ide> import javax.xml.bind.annotation.XmlAnyElement;
<ide> import javax.xml.bind.annotation.XmlElementWrapper;
<ide> import javax.xml.bind.annotation.XmlRootElement;
<ide> import javax.xml.bind.annotation.XmlType;
<del>import org.kuali.rice.core.api.CoreConstants;
<del>import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
<del>import org.kuali.rice.core.api.mo.ModelBuilder;
<del>import org.kuali.rice.kew.api.document.Document;
<del>import org.kuali.rice.kew.api.document.DocumentContract;
<del>import org.kuali.rice.kew.api.document.attribute.DocumentAttribute;
<del>import org.kuali.rice.kew.api.document.attribute.DocumentAttributeContract;
<del>import org.kuali.rice.kew.api.document.attribute.DocumentAttributeFactory;
<del>import org.w3c.dom.Element;
<add>import java.io.Serializable;
<add>import java.util.ArrayList;
<add>import java.util.Collection;
<add>import java.util.Collections;
<add>import java.util.List;
<ide>
<ide> /**
<ide> * An immutable data transfer object implementation of the {@link DocumentLookupResultContract}. Instances of this
<ide> /**
<ide> * Private constructor used only by JAXB.
<ide> */
<add> @SuppressWarnings("unused")
<ide> private DocumentLookupResult() {
<ide> this.document = null;
<ide> this.documentAttributes = null; |
|
Java | apache-2.0 | f193aac4053e0ccd4487bb5f784bd44f3e7f072f | 0 | jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2012 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.jaamsim.controllers;
import java.awt.Frame;
import java.awt.Image;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import com.jaamsim.DisplayModels.DisplayModel;
import com.jaamsim.DisplayModels.ImageModel;
import com.jaamsim.font.TessFont;
import com.jaamsim.input.InputAgent;
import com.jaamsim.math.AABB;
import com.jaamsim.math.Mat4d;
import com.jaamsim.math.MathUtils;
import com.jaamsim.math.Plane;
import com.jaamsim.math.Quaternion;
import com.jaamsim.math.Ray;
import com.jaamsim.math.Transform;
import com.jaamsim.math.Vec3d;
import com.jaamsim.math.Vec4d;
import com.jaamsim.render.Action;
import com.jaamsim.render.CameraInfo;
import com.jaamsim.render.DisplayModelBinding;
import com.jaamsim.render.Future;
import com.jaamsim.render.HasScreenPoints;
import com.jaamsim.render.MeshDataCache;
import com.jaamsim.render.MeshProtoKey;
import com.jaamsim.render.OffscreenTarget;
import com.jaamsim.render.PreviewCache;
import com.jaamsim.render.RenderProxy;
import com.jaamsim.render.RenderUtils;
import com.jaamsim.render.Renderer;
import com.jaamsim.render.TessFontKey;
import com.jaamsim.render.WindowInteractionListener;
import com.jaamsim.render.util.ExceptionLogger;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.ui.View;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.IntegerVector;
import com.sandwell.JavaSimulation.ObjectType;
import com.sandwell.JavaSimulation.StringVector;
import com.sandwell.JavaSimulation3D.DisplayEntity;
import com.sandwell.JavaSimulation3D.DisplayModelCompat;
import com.sandwell.JavaSimulation3D.GUIFrame;
import com.sandwell.JavaSimulation3D.Graph;
import com.sandwell.JavaSimulation3D.ObjectSelector;
import com.sandwell.JavaSimulation3D.Region;
/**
* Top level owner of the JaamSim renderer. This class both owns and drives the Renderer object, but is also
* responsible for gathering rendering data every frame.
* @author Matt Chudleigh
*
*/
public class RenderManager implements DragSourceListener {
private static RenderManager s_instance = null;
/**
* Basic singleton pattern
*/
public static void initialize(boolean safeGraphics) {
s_instance = new RenderManager(safeGraphics);
}
public static RenderManager inst() { return s_instance; }
private final Thread _managerThread;
private final Renderer _renderer;
private final AtomicBoolean _finished = new AtomicBoolean(false);
private final AtomicBoolean _fatalError = new AtomicBoolean(false);
private final AtomicBoolean _redraw = new AtomicBoolean(false);
private final AtomicBoolean _screenshot = new AtomicBoolean(false);
// These values are used to limit redraw rate, the stored values are time in milliseconds
// returned by System.currentTimeMillis()
private final AtomicLong _lastDraw = new AtomicLong(0);
private final AtomicLong _scheduledDraw = new AtomicLong(0);
private final ExceptionLogger _exceptionLogger;
private final static double FPS = 60;
private final Timer _timer;
private final HashMap<Integer, CameraControl> _windowControls = new HashMap<Integer, CameraControl>();
private final HashMap<Integer, View> _windowToViewMap= new HashMap<Integer, View>();
private int _activeWindowID = -1;
private final Object _popupLock;
private JPopupMenu _lastPopup;
/**
* The last scene rendered
*/
private ArrayList<RenderProxy> _cachedScene;
private DisplayEntity _selectedEntity = null;
private double _simTime = 0.0d;
private boolean _isDragging = false;
private long _dragHandleID = 0;
// The object type for drag-and-drop operation, if this is null, the user is not dragging
private ObjectType _dndObjectType;
private long _dndDropTime = 0;
// The video recorder to sample
private VideoRecorder _recorder;
private PreviewCache _previewCache = new PreviewCache();
// Below are special PickingIDs for resizing and dragging handles
public static final long MOVE_PICK_ID = -1;
// For now this order is implicitly the same as the handle order in RenderObserver, don't re arrange it without touching
// the handle list
public static final long RESIZE_POSX_PICK_ID = -2;
public static final long RESIZE_NEGX_PICK_ID = -3;
public static final long RESIZE_POSY_PICK_ID = -4;
public static final long RESIZE_NEGY_PICK_ID = -5;
public static final long RESIZE_PXPY_PICK_ID = -6;
public static final long RESIZE_PXNY_PICK_ID = -7;
public static final long RESIZE_NXPY_PICK_ID = -8;
public static final long RESIZE_NXNY_PICK_ID = -9;
public static final long ROTATE_PICK_ID = -10;
public static final long LINEDRAG_PICK_ID = -11;
// Line nodes start at this constant and proceed into the negative range, therefore this should be the lowest defined constant
public static final long LINENODE_PICK_ID = -12;
private RenderManager(boolean safeGraphics) {
_renderer = new Renderer(safeGraphics);
_exceptionLogger = new ExceptionLogger();
_managerThread = new Thread(new Runnable() {
@Override
public void run() {
renderManagerLoop();
}
}, "RenderManagerThread");
_managerThread.start();
// Start the display timer
_timer = new Timer("RedrawThread");
TimerTask displayTask = new TimerTask() {
@Override
public void run() {
// Is a redraw scheduled
long currentTime = System.currentTimeMillis();
long scheduledTime = _scheduledDraw.get();
long lastRedraw = _lastDraw.get();
// Only draw if the scheduled time is before now and after the last redraw
if (scheduledTime < lastRedraw || currentTime < scheduledTime) {
return;
}
synchronized(_redraw) {
if (_renderer.getNumOpenWindows() == 0 && !_screenshot.get()) {
return; // Do not queue a redraw if there are no open windows
}
_redraw.set(true);
_redraw.notifyAll();
}
}
};
_timer.scheduleAtFixedRate(displayTask, 0, (long) (1000 / (FPS*2)));
_popupLock = new Object();
}
public static final void updateTime(double simTime) {
if (!RenderManager.isGood())
return;
RenderManager.inst()._simTime = simTime;
RenderManager.inst().queueRedraw();
}
public void queueRedraw() {
long scheduledTime = _scheduledDraw.get();
long lastRedraw = _lastDraw.get();
if (scheduledTime > lastRedraw) {
// A draw is scheduled
return;
}
long newDraw = System.currentTimeMillis();
long frameTime = (long)(1000.0/FPS);
if (newDraw - lastRedraw < frameTime) {
// This would be scheduled too soon
newDraw = lastRedraw + frameTime;
}
_scheduledDraw.set(newDraw);
}
public void createWindow(View view) {
// First see if this window has already been opened
for (Map.Entry<Integer, CameraControl> entry : _windowControls.entrySet()) {
if (entry.getValue().getView() == view) {
// This view has a window, just reshow that one
focusWindow(entry.getKey());
return;
}
}
IntegerVector windSize = (IntegerVector)view.getInput("WindowSize").getValue();
IntegerVector windPos = (IntegerVector)view.getInput("WindowPosition").getValue();
Image icon = GUIFrame.getWindowIcon();
CameraControl control = new CameraControl(_renderer, view);
int windowID = _renderer.createWindow(windPos.get(0), windPos.get(1),
windSize.get(0), windSize.get(1),
view.getID(),
view.getTitle(), view.getInputName(),
icon, control);
_windowControls.put(windowID, control);
_windowToViewMap.put(windowID, view);
dirtyAllEntities();
queueRedraw();
}
public void closeAllWindows() {
ArrayList<Integer> windIDs = _renderer.getOpenWindowIDs();
for (int id : windIDs) {
_renderer.closeWindow(id);
}
}
public void windowClosed(int windowID) {
_windowControls.remove(windowID);
_windowToViewMap.remove(windowID);
}
public void setActiveWindow(int windowID) {
_activeWindowID = windowID;
}
public static boolean isGood() {
return (s_instance != null && !s_instance._finished.get() && !s_instance._fatalError.get());
}
/**
* Ideally, this states that it is safe to call initialize() (assuming isGood() returned false)
* @return
*/
public static boolean canInitialize() {
return s_instance == null;
}
private void dirtyAllEntities() {
for (int i = 0; i < DisplayEntity.getAll().size(); ++i) {
DisplayEntity.getAll().get(i).setGraphicsDataDirty();
}
}
private void renderManagerLoop() {
while (!_finished.get() && !_fatalError.get()) {
try {
if (_renderer.hasFatalError()) {
// Well, something went horribly wrong
_fatalError.set(true);
System.out.printf("Renderer failed with error: %s\n", _renderer.getErrorString());
// Do some basic cleanup
_windowControls.clear();
_previewCache.clear();
_timer.cancel();
break;
}
_lastDraw.set(System.currentTimeMillis());
if (!_renderer.isInitialized()) {
// Give the renderer a chance to initialize
try {
Thread.sleep(100);
} catch(InterruptedException e) {}
continue;
}
for (CameraControl cc : _windowControls.values()) {
cc.checkForUpdate();
}
_cachedScene = new ArrayList<RenderProxy>();
DisplayModelBinding.clearCacheCounters();
DisplayModelBinding.clearCacheMissData();
double renderTime = _simTime;
long startNanos = System.nanoTime();
for (int i = 0; i < View.getAll().size(); i++) {
View v = View.getAll().get(i);
v.update(renderTime);
}
ArrayList<DisplayModelBinding> selectedBindings = new ArrayList<DisplayModelBinding>();
// Update all graphical entities in the simulation
for (int i = 0; i < DisplayEntity.getAll().size(); i++) {
DisplayEntity de;
try {
de = DisplayEntity.getAll().get(i);
}
catch (IndexOutOfBoundsException e) {
break;
}
try {
de.updateGraphics(renderTime);
}
// Catch everything so we don't screw up the behavior handling
catch (Throwable e) {
logException(e);
}
}
long updateNanos = System.nanoTime();
int totalBindings = 0;
for (int i = 0; i < DisplayEntity.getAll().size(); i++) {
DisplayEntity de;
try {
de = DisplayEntity.getAll().get(i);
} catch (IndexOutOfBoundsException ex) {
// This is probably the end of the list, so just move on
break;
}
for (DisplayModelBinding binding : de.getDisplayBindings()) {
try {
totalBindings++;
binding.collectProxies(renderTime, _cachedScene);
if (binding.isBoundTo(_selectedEntity)) {
selectedBindings.add(binding);
}
} catch (Throwable t) {
// Log the exception in the exception list
logException(t);
}
}
}
// Collect selection proxies second so they always appear on top
for (DisplayModelBinding binding : selectedBindings) {
try {
binding.collectSelectionProxies(renderTime, _cachedScene);
} catch (Throwable t) {
// Log the exception in the exception list
logException(t);
}
}
long endNanos = System.nanoTime();
_renderer.setScene(_cachedScene);
String cacheString = " Hits: " + DisplayModelBinding.getCacheHits() + " Misses: " + DisplayModelBinding.getCacheMisses() +
" Total: " + totalBindings;
double gatherMS = (endNanos - updateNanos) / 1000000.0;
double updateMS = (updateNanos - startNanos) / 1000000.0;
String timeString = "Gather time (ms): " + gatherMS + " Update time (ms): " + updateMS;
// Do some picking debug
ArrayList<Integer> windowIDs = _renderer.getOpenWindowIDs();
for (int id : windowIDs) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(id);
if (mouseInfo == null || !mouseInfo.mouseInWindow) {
// Not currently picking for this window
_renderer.setWindowDebugInfo(id, cacheString + " Not picking. " + timeString, new ArrayList<Long>());
continue;
}
List<PickData> picks = pickForMouse(id, false);
ArrayList<Long> debugIDs = new ArrayList<Long>(picks.size());
StringBuilder dbgMsg = new StringBuilder(cacheString);
dbgMsg.append(" Picked ").append(picks.size());
dbgMsg.append(" entities at (").append(mouseInfo.x);
dbgMsg.append(", ").append(mouseInfo.y).append("): ");
for (PickData pd : picks) {
Entity ent = Entity.idToEntity(pd.id);
if (ent != null)
dbgMsg.append(ent.getInputName());
dbgMsg.append(", ");
debugIDs.add(pd.id);
}
dbgMsg.append(timeString);
_renderer.setWindowDebugInfo(id, dbgMsg.toString(), debugIDs);
}
if (GUIFrame.getShuttingDownFlag()) {
shutdown();
}
_renderer.queueRedraw();
_redraw.set(false);
if (_screenshot.get()) {
takeScreenShot();
}
} catch (Throwable t) {
// Make a note of it, but try to keep going
logException(t);
}
// Wait for a redraw request
synchronized(_redraw) {
while (!_redraw.get()) {
try {
_redraw.wait(30);
} catch (InterruptedException e) {}
}
}
}
_exceptionLogger.printExceptionLog();
}
// Temporary dumping ground until I find a better place for this
public void popupMenu(int windowID) {
synchronized (_popupLock) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
if (mouseInfo == null) {
// Somehow this window was closed along the way, just ignore this click
return;
}
final Frame awtFrame = _renderer.getAWTFrame(windowID);
if (awtFrame == null) {
return;
}
List<PickData> picks = pickForMouse(windowID, false);
ArrayList<DisplayEntity> ents = new ArrayList<DisplayEntity>();
for (PickData pd : picks) {
if (!pd.isEntity) { continue; }
Entity ent = Entity.idToEntity(pd.id);
if (ent == null) { continue; }
if (!(ent instanceof DisplayEntity)) { continue; }
DisplayEntity de = (DisplayEntity)ent;
ents.add(de);
}
if (!mouseInfo.mouseInWindow) {
// Somehow this window does not currently have the mouse over it.... ignore?
return;
}
final JPopupMenu menu = new JPopupMenu();
_lastPopup = menu;
menu.setLightWeightPopupEnabled(false);
final int menuX = mouseInfo.x + awtFrame.getInsets().left;
final int menuY = mouseInfo.y + awtFrame.getInsets().top;
if (ents.size() == 0) { return; } // Nothing to show
if (ents.size() == 1) {
ObjectSelector.populateMenu(menu, ents.get(0), menuX, menuY);
}
else {
// Several entities, let the user pick the interesting entity first
for (final DisplayEntity de : ents) {
JMenuItem thisItem = new JMenuItem(de.getInputName());
thisItem.addActionListener( new ActionListener() {
@Override
public void actionPerformed( ActionEvent event ) {
menu.removeAll();
ObjectSelector.populateMenu(menu, de, menuX, menuY);
menu.show(awtFrame, menuX, menuY);
}
} );
menu.add( thisItem );
}
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
menu.show(awtFrame, menuX, menuY);
menu.repaint();
}
});
} // synchronized (_popupLock)
}
public void handleSelection(int windowID) {
List<PickData> picks = pickForMouse(windowID, false);
Collections.sort(picks, new SelectionSorter());
for (PickData pd : picks) {
// Select the first entity after sorting
if (pd.isEntity) {
DisplayEntity ent = (DisplayEntity)Entity.idToEntity(pd.id);
if (!ent.isMovable()) {
continue;
}
FrameBox.setSelectedEntity(ent);
queueRedraw();
return;
}
}
FrameBox.setSelectedEntity(null);
queueRedraw();
}
/**
* Utility, convert a window and mouse coordinate into a list of picking IDs for that pixel
* @param windowID
* @param mouseX
* @param mouseY
* @return
*/
private List<PickData> pickForMouse(int windowID, boolean precise) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
View view = _windowToViewMap.get(windowID);
if (mouseInfo == null || view == null || !mouseInfo.mouseInWindow) {
// The mouse is not actually in the window, or the window was closed along the way
return new ArrayList<PickData>(); // empty set
}
Ray pickRay = RenderUtils.getPickRay(mouseInfo);
return pickForRay(pickRay, view.getID(), precise);
}
/**
* PickData represents enough information to sort a list of picks based on a picking preference
* metric. For now it holds the object size and distance from pick point to object center
*
*/
private static class PickData {
public long id;
public double size;
boolean isEntity;
/**
* This pick does not correspond to an entity, and is a handle or other UI element
* @param id
*/
public PickData(long id) {
this.id = id;
size = 0;
isEntity = false;
}
/**
* This pick was an entity
* @param id - the id
* @param ent - the entity
*/
public PickData(long id, DisplayEntity ent) {
this.id = id;
size = ent.getSize().mag3();
isEntity = true;
}
}
/**
* This Comparator sorts based on entity selection preference
*/
private class SelectionSorter implements Comparator<PickData> {
@Override
public int compare(PickData p0, PickData p1) {
if (p0.isEntity && !p1.isEntity) {
return -1;
}
if (!p0.isEntity && p1.isEntity) {
return 1;
}
if (p0.size == p1.size) {
return 0;
}
return (p0.size < p1.size) ? -1 : 1;
}
}
/**
* This Comparator sorts based on interaction handle priority
*/
private class HandleSorter implements Comparator<PickData> {
@Override
public int compare(PickData p0, PickData p1) {
int p0priority = getHandlePriority(p0.id);
int p1priority = getHandlePriority(p1.id);
if (p0priority == p1priority)
return 0;
return (p0priority < p1priority) ? 1 : -1;
}
}
/**
* This determines the priority for interaction handles if several are selectable at drag time
* @param handleID
* @return
*/
private static int getHandlePriority(long handleID) {
if (handleID == MOVE_PICK_ID) return 1;
if (handleID == LINEDRAG_PICK_ID) return 1;
if (handleID <= LINENODE_PICK_ID) return 2;
if (handleID == ROTATE_PICK_ID) return 3;
if (handleID == RESIZE_POSX_PICK_ID) return 4;
if (handleID == RESIZE_NEGX_PICK_ID) return 4;
if (handleID == RESIZE_POSY_PICK_ID) return 4;
if (handleID == RESIZE_NEGY_PICK_ID) return 4;
if (handleID == RESIZE_PXPY_PICK_ID) return 5;
if (handleID == RESIZE_PXNY_PICK_ID) return 5;
if (handleID == RESIZE_NXPY_PICK_ID) return 5;
if (handleID == RESIZE_NXNY_PICK_ID) return 5;
return 0;
}
public Vec3d getNearestPick(int windowID) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
View view = _windowToViewMap.get(windowID);
if (mouseInfo == null || view == null || !mouseInfo.mouseInWindow) {
// The mouse is not actually in the window, or the window was closed along the way
return null;
}
Ray pickRay = RenderUtils.getPickRay(mouseInfo);
List<Renderer.PickResult> picks = _renderer.pick(pickRay, view.getID(), true);
if (picks.size() == 0) {
return null;
}
double pickDist = Double.POSITIVE_INFINITY;
for (Renderer.PickResult pick : picks) {
if (pick.dist < pickDist && pick.pickingID >= 0) {
// Negative pickingIDs are reserved for interaction handles and are therefore not
// part of the content
pickDist = pick.dist;
}
}
if (pickDist == Double.POSITIVE_INFINITY) {
return null;
}
return pickRay.getPointAtDist(pickDist);
}
/**
* Perform a pick from this world space ray
* @param pickRay - the ray
* @return
*/
private List<PickData> pickForRay(Ray pickRay, int viewID, boolean precise) {
List<Renderer.PickResult> picks = _renderer.pick(pickRay, viewID, precise);
List<PickData> uniquePicks = new ArrayList<PickData>();
// IDs that have already been added
Set<Long> knownIDs = new HashSet<Long>();
for (Renderer.PickResult pick : picks) {
if (knownIDs.contains(pick.pickingID)) {
continue;
}
knownIDs.add(pick.pickingID);
DisplayEntity ent = (DisplayEntity)Entity.idToEntity(pick.pickingID);
if (ent == null) {
// This object is not an entity, but may be a picking handle
uniquePicks.add(new PickData(pick.pickingID));
} else {
uniquePicks.add(new PickData(pick.pickingID, ent));
}
}
return uniquePicks;
}
/**
* Pick on a window at a position other than the current mouse position
* @param windowID
* @param x
* @param y
* @return
*/
private Ray getRayForMouse(int windowID, int x, int y) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
if (mouseInfo == null) {
return new Ray();
}
return RenderUtils.getPickRayForPosition(mouseInfo.cameraInfo, x, y, mouseInfo.width, mouseInfo.height);
}
public Vec3d getRenderedStringSize(TessFontKey fontKey, double textHeight, String string) {
TessFont font = _renderer.getTessFont(fontKey);
return font.getStringSize(textHeight, string);
}
private void logException(Throwable t) {
_exceptionLogger.logException(t);
// And print the output
printExceptionLog();
}
private void printExceptionLog() {
System.out.println("Recoverable Exceptions from RenderManager: ");
_exceptionLogger.printExceptionLog();
System.out.println("");
}
public static void setSelection(Entity ent) {
if (!RenderManager.isGood())
return;
RenderManager.inst().setSelectEntity(ent);
}
private void setSelectEntity(Entity ent) {
if (ent instanceof DisplayEntity)
_selectedEntity = (DisplayEntity)ent;
else
_selectedEntity = null;
_isDragging = false;
queueRedraw();
}
/**
* This method gives the RenderManager a chance to handle mouse drags before the CameraControl
* gets to handle it (note: this may need to be refactored into a proper event handling heirarchy)
* @param dragInfo
* @return
*/
public boolean handleDrag(WindowInteractionListener.DragInfo dragInfo) {
if (!_isDragging) {
// We have not cached a drag handle ID, so don't claim this and let CameraControl have control back
return false;
}
// We should have a selected entity
assert(_selectedEntity != null);
// Any quick outs go here
if (!_selectedEntity.isMovable()) {
return false;
}
// For now, experimental controls requires control to be down to drag or resize
if (getExperimentalControls() != dragInfo.controlDown()) {
return false;
}
// Find the start and current world space positions
Ray currentRay = getRayForMouse(dragInfo.windowID, dragInfo.x, dragInfo.y);
Ray lastRay = getRayForMouse(dragInfo.windowID,
dragInfo.x - dragInfo.dx,
dragInfo.y - dragInfo.dy);
Transform trans = _selectedEntity.getGlobalTrans(_simTime);
Vec3d size = _selectedEntity.getSize();
Mat4d transMat = _selectedEntity.getTransMatrix(_simTime);
Mat4d invTransMat = _selectedEntity.getInvTransMatrix(_simTime);
Plane entityPlane = new Plane(); // Defaults to XY
entityPlane.transform(trans, entityPlane, new Vec3d()); // Transform the plane to world space
double currentDist = entityPlane.collisionDist(currentRay);
double lastDist = entityPlane.collisionDist(lastRay);
if (currentDist < 0 || currentDist == Double.POSITIVE_INFINITY ||
lastDist < 0 || lastDist == Double.POSITIVE_INFINITY)
{
// The plane is parallel or behind one of the rays...
return true; // Just ignore it for now...
}
// The points where the previous pick ended and current position. Collision is with the entity's XY plane
Vec3d currentPoint = currentRay.getPointAtDist(currentDist);
Vec3d lastPoint = lastRay.getPointAtDist(lastDist);
Vec3d entSpaceCurrent = new Vec3d(); // entSpacePoint is the current point in model space
entSpaceCurrent.multAndTrans3(invTransMat, currentPoint);
Vec3d entSpaceLast = new Vec3d(); // entSpaceLast is the last point in model space
entSpaceLast.multAndTrans3(invTransMat, lastPoint);
Vec3d delta = new Vec3d();
delta.sub3(currentPoint, lastPoint);
Vec3d entSpaceDelta = new Vec3d();
entSpaceDelta.sub3(entSpaceCurrent, entSpaceLast);
// Handle each handle by type...
if (_dragHandleID == MOVE_PICK_ID) {
// We are dragging
if (dragInfo.shiftDown()) {
Vec4d entPos = _selectedEntity.getGlobalPosition();
double zDiff = RenderUtils.getZDiff(entPos, currentRay, lastRay);
entPos.z += zDiff;
_selectedEntity.setGlobalPosition(entPos);
return true;
}
Vec4d pos = new Vec4d(_selectedEntity.getGlobalPosition());
pos.add3(delta);
_selectedEntity.setGlobalPosition(pos);
return true;
}
// Handle resize
if (_dragHandleID <= RESIZE_POSX_PICK_ID &&
_dragHandleID >= RESIZE_NXNY_PICK_ID) {
Vec4d pos = new Vec4d(_selectedEntity.getGlobalPosition());
Vec3d scale = _selectedEntity.getSize();
Vec4d fixedPoint = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
if (_dragHandleID == RESIZE_POSX_PICK_ID) {
//scale.x = 2*entSpaceCurrent.x() * size.x();
scale.x += entSpaceDelta.x * size.x;
fixedPoint = new Vec4d(-0.5, 0.0, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_POSY_PICK_ID) {
scale.y += entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.0, -0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NEGX_PICK_ID) {
scale.x -= entSpaceDelta.x * size.x;
fixedPoint = new Vec4d( 0.5, 0.0, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NEGY_PICK_ID) {
scale.y -= entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.0, 0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_PXPY_PICK_ID) {
scale.x += entSpaceDelta.x * size.x;
scale.y += entSpaceDelta.y * size.y;
fixedPoint = new Vec4d(-0.5, -0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_PXNY_PICK_ID) {
scale.x += entSpaceDelta.x * size.x;
scale.y -= entSpaceDelta.y * size.y;
fixedPoint = new Vec4d(-0.5, 0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NXPY_PICK_ID) {
scale.x -= entSpaceDelta.x * size.x;
scale.y += entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.5, -0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NXNY_PICK_ID) {
scale.x -= entSpaceDelta.x * size.x;
scale.y -= entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.5, 0.5, 0.0, 1.0d);
}
// Handle the case where the scale is pulled through itself. Fix the scale,
// and swap the currently selected handle
if (scale.x <= 0.00005) {
scale.x = 0.0001;
if (_dragHandleID == RESIZE_POSX_PICK_ID) { _dragHandleID = RESIZE_NEGX_PICK_ID; }
else if (_dragHandleID == RESIZE_NEGX_PICK_ID) { _dragHandleID = RESIZE_POSX_PICK_ID; }
else if (_dragHandleID == RESIZE_PXPY_PICK_ID) { _dragHandleID = RESIZE_NXPY_PICK_ID; }
else if (_dragHandleID == RESIZE_PXNY_PICK_ID) { _dragHandleID = RESIZE_NXNY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXPY_PICK_ID) { _dragHandleID = RESIZE_PXPY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXNY_PICK_ID) { _dragHandleID = RESIZE_PXNY_PICK_ID; }
}
if (scale.y <= 0.00005) {
scale.y = 0.0001;
if (_dragHandleID == RESIZE_POSY_PICK_ID) { _dragHandleID = RESIZE_NEGY_PICK_ID; }
else if (_dragHandleID == RESIZE_NEGY_PICK_ID) { _dragHandleID = RESIZE_POSY_PICK_ID; }
else if (_dragHandleID == RESIZE_PXPY_PICK_ID) { _dragHandleID = RESIZE_PXNY_PICK_ID; }
else if (_dragHandleID == RESIZE_PXNY_PICK_ID) { _dragHandleID = RESIZE_PXPY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXPY_PICK_ID) { _dragHandleID = RESIZE_NXNY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXNY_PICK_ID) { _dragHandleID = RESIZE_NXPY_PICK_ID; }
}
Vec4d oldFixed = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
oldFixed.mult4(transMat, fixedPoint);
_selectedEntity.setSize(scale);
transMat = _selectedEntity.getTransMatrix(_simTime); // Get the new matrix
Vec4d newFixed = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
newFixed.mult4(transMat, fixedPoint);
Vec4d posAdjust = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
posAdjust.sub3(oldFixed, newFixed);
pos.add3(posAdjust);
_selectedEntity.setGlobalPosition(pos);
Vec3d vec = _selectedEntity.getSize();
InputAgent.processEntity_Keyword_Value(_selectedEntity, "Size", String.format( "%.6f %.6f %.6f %s", vec.x, vec.y, vec.z, "m" ));
FrameBox.valueUpdate();
return true;
}
if (_dragHandleID == ROTATE_PICK_ID) {
Vec3d align = _selectedEntity.getAlignment();
Vec4d rotateCenter = new Vec4d(align.x, align.y, align.z, 1.0d);
rotateCenter.mult4(transMat, rotateCenter);
Vec4d a = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
a.sub3(lastPoint, rotateCenter);
Vec4d b = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
b.sub3(currentPoint, rotateCenter);
Vec4d aCrossB = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
aCrossB.cross3(a, b);
double sinTheta = aCrossB.z / a.mag3() / b.mag3();
double theta = Math.asin(sinTheta);
Vec3d orient = _selectedEntity.getOrientation();
orient.z += theta;
InputAgent.processEntity_Keyword_Value(_selectedEntity, "Orientation", String.format("%f %f %f rad", orient.x, orient.y, orient.z));
FrameBox.valueUpdate();
return true;
}
if (_dragHandleID == LINEDRAG_PICK_ID) {
// Dragging a line object
if (dragInfo.shiftDown()) {
ArrayList<Vec3d> screenPoints = null;
if (_selectedEntity instanceof HasScreenPoints)
screenPoints = ((HasScreenPoints)_selectedEntity).getScreenPoints();
if (screenPoints == null || screenPoints.size() == 0) return true; // just ignore this
// Find the geometric median of the points
Vec4d medPoint = RenderUtils.getGeometricMedian(screenPoints);
double zDiff = RenderUtils.getZDiff(medPoint, currentRay, lastRay);
_selectedEntity.dragged(new Vec3d(0, 0, zDiff));
return true;
}
Region reg = _selectedEntity.getCurrentRegion();
Transform regionInvTrans = new Transform();
if (reg != null) {
regionInvTrans = reg.getRegionTrans(0.0d);
regionInvTrans.inverse(regionInvTrans);
}
Vec4d localDelta = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
regionInvTrans.apply(delta, localDelta);
_selectedEntity.dragged(localDelta);
return true;
}
if (_dragHandleID <= LINENODE_PICK_ID) {
int nodeIndex = (int)(-1*(_dragHandleID - LINENODE_PICK_ID));
ArrayList<Vec3d> screenPoints = null;
if (_selectedEntity instanceof HasScreenPoints)
screenPoints = ((HasScreenPoints)_selectedEntity).getScreenPoints();
// Note: screenPoints is not a defensive copy, but we'll put it back into itself
// in a second so everything should be safe
if (screenPoints == null || nodeIndex >= screenPoints.size()) {
// huh?
return false;
}
Vec3d point = screenPoints.get(nodeIndex);
if (dragInfo.shiftDown()) {
double zDiff = RenderUtils.getZDiff(point, currentRay, lastRay);
point.z += zDiff;
} else {
Plane pointPlane = new Plane(Vec4d.Z_AXIS, point.z);
Vec3d diff = RenderUtils.getPlaneCollisionDiff(pointPlane, currentRay, lastRay);
point.x += diff.x;
point.y += diff.y;
point.z += 0;
}
Input<?> pointsInput = _selectedEntity.getInput("Points");
assert(pointsInput != null);
if (pointsInput == null) {
_selectedEntity.setGraphicsDataDirty();
return true;
}
StringBuilder sb = new StringBuilder();
String pointFormatter = " { %.3f %.3f %.3f m }";
for(Vec3d pt : screenPoints) {
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
InputAgent.processEntity_Keyword_Value(_selectedEntity, pointsInput, sb.toString());
FrameBox.valueUpdate();
_selectedEntity.setGraphicsDataDirty();
return true;
}
return false;
}
private void splitLineEntity(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
Mat4d rayMatrix = MathUtils.RaySpace(currentRay);
HasScreenPoints hsp = (HasScreenPoints)_selectedEntity;
assert(hsp != null);
ArrayList<Vec3d> points = hsp.getScreenPoints();
int splitInd = 0;
Vec4d nearPoint = null;
// Find a line segment we are near
for (;splitInd < points.size() - 1; ++splitInd) {
Vec4d a = new Vec4d(points.get(splitInd ).x, points.get(splitInd ).y, points.get(splitInd ).z, 1.0d);
Vec4d b = new Vec4d(points.get(splitInd+1).x, points.get(splitInd+1).y, points.get(splitInd+1).z, 1.0d);
nearPoint = RenderUtils.rayClosePoint(rayMatrix, a, b);
double rayAngle = RenderUtils.angleToRay(rayMatrix, nearPoint);
if (rayAngle > 0 && rayAngle < 0.01309) { // 0.75 degrees in radians
break;
}
}
if (splitInd == points.size() - 1) {
// No appropriate point was found
return;
}
// If we are here, we have a segment to split, at index i
StringBuilder sb = new StringBuilder();
String pointFormatter = " { %.3f %.3f %.3f m }";
for(int i = 0; i <= splitInd; ++i) {
Vec3d pt = points.get(i);
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
sb.append(String.format(pointFormatter, nearPoint.x, nearPoint.y, nearPoint.z));
for (int i = splitInd+1; i < points.size(); ++i) {
Vec3d pt = points.get(i);
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
Input<?> pointsInput = _selectedEntity.getInput("Points");
InputAgent.processEntity_Keyword_Value(_selectedEntity, pointsInput, sb.toString());
FrameBox.valueUpdate();
_selectedEntity.setGraphicsDataDirty();
}
private void removeLineNode(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
Mat4d rayMatrix = MathUtils.RaySpace(currentRay);
HasScreenPoints hsp = (HasScreenPoints)_selectedEntity;
assert(hsp != null);
ArrayList<Vec3d> points = hsp.getScreenPoints();
// Find a point that is within the threshold
if (points.size() <= 2) {
return;
}
int removeInd = 0;
// Find a line segment we are near
for ( ;removeInd < points.size(); ++removeInd) {
Vec4d p = new Vec4d(points.get(removeInd).x, points.get(removeInd).y, points.get(removeInd).z, 1.0d);
double rayAngle = RenderUtils.angleToRay(rayMatrix, p);
if (rayAngle > 0 && rayAngle < 0.01309) { // 0.75 degrees in radians
break;
}
if (removeInd == points.size()) {
// No appropriate point was found
return;
}
}
StringBuilder sb = new StringBuilder();
String pointFormatter = " { %.3f %.3f %.3f m }";
for(int i = 0; i < points.size(); ++i) {
if (i == removeInd) {
continue;
}
Vec3d pt = points.get(i);
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
Input<?> pointsInput = _selectedEntity.getInput("Points");
InputAgent.processEntity_Keyword_Value(_selectedEntity, pointsInput, sb.toString());
FrameBox.valueUpdate();
_selectedEntity.setGraphicsDataDirty();
}
private boolean isMouseHandleID(long id) {
return (id < 0); // For now all negative IDs are mouse handles, this may change
}
public boolean handleMouseButton(int windowID, int x, int y, int button, boolean isDown, int modifiers) {
if (button != 1) { return false; }
if (!isDown) {
// Click released
_isDragging = false;
return true; // handled
}
boolean controlDown = (modifiers & WindowInteractionListener.MOD_CTRL) != 0;
if (controlDown) {
// Check if we can split a line segment
if (_selectedEntity != null && _selectedEntity instanceof HasScreenPoints) {
if ((modifiers & WindowInteractionListener.MOD_SHIFT) != 0) {
removeLineNode(windowID, x, y);
} else {
splitLineEntity(windowID, x, y);
}
return true;
}
}
if (controlDown != getExperimentalControls()) {
_isDragging = false;
return false;
}
Ray pickRay = getRayForMouse(windowID, x, y);
View view = _windowToViewMap.get(windowID);
if (view == null) {
return false;
}
List<PickData> picks = pickForRay(pickRay, view.getID(), false);
Collections.sort(picks, new HandleSorter());
if (picks.size() == 0) {
return false;
}
// See if we are hovering over any interaction handles
for (PickData pd : picks) {
if (isMouseHandleID(pd.id)) {
// this is a mouse handle, remember the handle for future drag events
_isDragging = true;
_dragHandleID = pd.id;
return true;
}
}
return false;
}
public void clearSelection() {
_selectedEntity = null;
_isDragging = false;
}
public void hideExistingPopups() {
synchronized (_popupLock) {
if (_lastPopup == null) {
return;
}
_lastPopup.setVisible(false);
_lastPopup = null;
}
}
public boolean isDragAndDropping() {
// This is such a brutal hack to work around newt's lack of drag and drop support
// Claim we are still dragging for up to 10ms after the last drop failed...
long currTime = System.nanoTime();
return _dndObjectType != null &&
((currTime - _dndDropTime) < 100000000); // Did the last 'drop' happen less than 100 ms ago?
}
public void startDragAndDrop(ObjectType ot) {
_dndObjectType = ot;
}
public void mouseMoved(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
double dist = Plane.XY_PLANE.collisionDist(currentRay);
if (dist == Double.POSITIVE_INFINITY) {
// I dunno...
return;
}
Vec3d xyPlanePoint = currentRay.getPointAtDist(dist);
GUIFrame.instance().showLocatorPosition(xyPlanePoint);
queueRedraw();
}
public void createDNDObject(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
double dist = Plane.XY_PLANE.collisionDist(currentRay);
if (dist == Double.POSITIVE_INFINITY) {
// Unfortunate...
return;
}
Vec3d creationPoint = currentRay.getPointAtDist(dist);
// Create a new instance
Class<? extends Entity> proto = _dndObjectType.getJavaClass();
String name = proto.getSimpleName();
Entity ent = InputAgent.defineEntityWithUniqueName(proto, name, true);
// We are no longer drag-and-dropping
_dndObjectType = null;
FrameBox.setSelectedEntity(ent);
if (!(ent instanceof DisplayEntity)) {
// This object is not a display entity, so the rest of this method does not apply
return;
}
DisplayEntity dEntity = (DisplayEntity) ent;
try {
dEntity.dragged(creationPoint);
}
catch (InputErrorException e) {}
boolean isFlat = false;
// Shudder....
ArrayList<DisplayModel> displayModels = dEntity.getDisplayModelList();
if (displayModels != null && displayModels.size() > 0) {
DisplayModel dm0 = displayModels.get(0);
if (dm0 instanceof DisplayModelCompat || dm0 instanceof ImageModel)
isFlat = true;
}
if (dEntity instanceof HasScreenPoints) {
isFlat = true;
}
if (dEntity instanceof Graph) {
isFlat = true;
}
if (isFlat) {
Vec3d size = dEntity.getSize();
Input<?> in = dEntity.getInput("Size");
StringVector args = new StringVector(4);
args.add(String.format("%.3f", size.x));
args.add(String.format("%.3f", size.y));
args.add("0.0");
args.add("m");
InputAgent.apply(dEntity, in, args);
InputAgent.updateInput(dEntity, in, args);
} else {
Input<?> in = dEntity.getInput("Alignment");
StringVector args = new StringVector(3);
args.add("0.0");
args.add("0.0");
args.add("-0.5");
InputAgent.apply(dEntity, in, args);
InputAgent.updateInput(dEntity, in, args);
}
FrameBox.valueUpdate();
}
@Override
public void dragDropEnd(DragSourceDropEvent arg0) {
// Clear the dragging flag
_dndDropTime = System.nanoTime();
}
@Override
public void dragEnter(DragSourceDragEvent arg0) {}
@Override
public void dragExit(DragSourceEvent arg0) {}
@Override
public void dragOver(DragSourceDragEvent arg0) {}
@Override
public void dropActionChanged(DragSourceDragEvent arg0) {}
public AABB getMeshBounds(MeshProtoKey key, boolean block) {
if (block || MeshDataCache.isMeshLoaded(key)) {
return MeshDataCache.getMeshData(key).getDefaultBounds();
}
// The mesh is not loaded and we are non-blocking, so trigger a mesh load and return
MeshDataCache.loadMesh(key, new AtomicBoolean());
return null;
}
public ArrayList<Action.Description> getMeshActions(MeshProtoKey key, boolean block) {
if (block || MeshDataCache.isMeshLoaded(key)) {
return MeshDataCache.getMeshData(key).getActionDescriptions();
}
// The mesh is not loaded and we are non-blocking, so trigger a mesh load and return
MeshDataCache.loadMesh(key, new AtomicBoolean());
return null;
}
/**
* Set the current windows camera to an isometric view
*/
public void setIsometricView() {
CameraControl control = _windowControls.get(_activeWindowID);
if (control == null) return;
// The constant is acos(1/sqrt(3))
control.setRotationAngles(0.955316, Math.PI/4);
}
/**
* Set the current windows camera to an XY plane view
*/
public void setXYPlaneView() {
CameraControl control = _windowControls.get(_activeWindowID);
if (control == null) return;
// Do not look straight down the Z axis as that is actually a degenerate state
control.setRotationAngles(0.0000001, 0.0);
}
public View getActiveView() {
return _windowToViewMap.get(_activeWindowID);
}
public ArrayList<Integer> getOpenWindowIDs() {
return _renderer.getOpenWindowIDs();
}
public String getWindowName(int windowID) {
return _renderer.getWindowName(windowID);
}
public void focusWindow(int windowID) {
_renderer.focusWindow(windowID);
}
public boolean getExperimentalControls() {
return GUIFrame.instance().getExperimentalControls();
}
/**
* Queue up an off screen rendering, this simply passes the call directly to the renderer
* @param scene
* @param camInfo
* @param width
* @param height
* @return
*/
public Future<BufferedImage> renderOffscreen(ArrayList<RenderProxy> scene, CameraInfo camInfo, int viewID,
int width, int height, Runnable runWhenDone) {
return _renderer.renderOffscreen(scene, viewID, camInfo, width, height, runWhenDone, null);
}
/**
* Return a FutureImage of the equivalent screen renderer from the given position looking at the given center
* @param cameraPos
* @param viewCenter
* @param width - width of returned image
* @param height - height of returned image
* @param target - optional target to prevent re-allocating GPU resources
* @return
*/
public Future<BufferedImage> renderScreenShot(Vec3d cameraPos, Vec3d viewCenter, int viewID,
int width, int height, OffscreenTarget target) {
Vec3d viewDiff = new Vec3d();
viewDiff.sub3(cameraPos, viewCenter);
double rotZ = Math.atan2(viewDiff.x, -viewDiff.y);
double xyDist = Math.hypot(viewDiff.x, viewDiff.y);
double rotX = Math.atan2(xyDist, viewDiff.z);
if (Math.abs(rotX) < 0.005) {
rotZ = 0; // Don't rotate if we are looking straight up or down
}
double viewDist = viewDiff.mag3();
Quaternion rot = new Quaternion();
rot.setRotZAxis(rotZ);
Quaternion tmp = new Quaternion();
tmp.setRotXAxis(rotX);
rot.mult(rot, tmp);
Transform trans = new Transform(cameraPos, rot, 1);
CameraInfo camInfo = new CameraInfo(Math.PI/3, viewDist*0.1, viewDist*10, trans);
return _renderer.renderOffscreen(_cachedScene, viewID, camInfo, width, height, null, target);
}
public Future<BufferedImage> getPreviewForDisplayModel(DisplayModel dm, Runnable notifier) {
return _previewCache.getPreview(dm, notifier);
}
public OffscreenTarget createOffscreenTarget(int width, int height) {
return _renderer.createOffscreenTarget(width, height);
}
public void freeOffscreenTarget(OffscreenTarget target) {
_renderer.freeOffscreenTarget(target);
}
private void takeScreenShot() {
if (_recorder != null)
_recorder.sample();
synchronized(_screenshot) {
_screenshot.set(false);
_recorder = null;
_screenshot.notifyAll();
}
}
public void blockOnScreenShot(VideoRecorder recorder) {
assert(!_screenshot.get());
synchronized (_screenshot) {
_screenshot.set(true);
_recorder = recorder;
queueRedraw();
while (_screenshot.get()) {
try {
_screenshot.wait();
} catch (InterruptedException ex) {}
}
}
}
public void shutdown() {
_finished.set(true);
if (_renderer != null) {
_renderer.shutdown();
}
}
}
| src/main/java/com/jaamsim/controllers/RenderManager.java | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2012 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.jaamsim.controllers;
import java.awt.Frame;
import java.awt.Image;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import com.jaamsim.DisplayModels.DisplayModel;
import com.jaamsim.DisplayModels.ImageModel;
import com.jaamsim.font.TessFont;
import com.jaamsim.input.InputAgent;
import com.jaamsim.math.AABB;
import com.jaamsim.math.Mat4d;
import com.jaamsim.math.MathUtils;
import com.jaamsim.math.Plane;
import com.jaamsim.math.Quaternion;
import com.jaamsim.math.Ray;
import com.jaamsim.math.Transform;
import com.jaamsim.math.Vec3d;
import com.jaamsim.math.Vec4d;
import com.jaamsim.render.Action;
import com.jaamsim.render.CameraInfo;
import com.jaamsim.render.DisplayModelBinding;
import com.jaamsim.render.Future;
import com.jaamsim.render.HasScreenPoints;
import com.jaamsim.render.MeshDataCache;
import com.jaamsim.render.MeshProtoKey;
import com.jaamsim.render.OffscreenTarget;
import com.jaamsim.render.PreviewCache;
import com.jaamsim.render.RenderProxy;
import com.jaamsim.render.RenderUtils;
import com.jaamsim.render.Renderer;
import com.jaamsim.render.TessFontKey;
import com.jaamsim.render.WindowInteractionListener;
import com.jaamsim.render.util.ExceptionLogger;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.ui.View;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.IntegerVector;
import com.sandwell.JavaSimulation.ObjectType;
import com.sandwell.JavaSimulation.StringVector;
import com.sandwell.JavaSimulation3D.DisplayEntity;
import com.sandwell.JavaSimulation3D.DisplayModelCompat;
import com.sandwell.JavaSimulation3D.GUIFrame;
import com.sandwell.JavaSimulation3D.Graph;
import com.sandwell.JavaSimulation3D.ObjectSelector;
import com.sandwell.JavaSimulation3D.Region;
/**
* Top level owner of the JaamSim renderer. This class both owns and drives the Renderer object, but is also
* responsible for gathering rendering data every frame.
* @author Matt Chudleigh
*
*/
public class RenderManager implements DragSourceListener {
private static RenderManager s_instance = null;
/**
* Basic singleton pattern
*/
public static void initialize(boolean safeGraphics) {
s_instance = new RenderManager(safeGraphics);
}
public static RenderManager inst() { return s_instance; }
private final Thread _managerThread;
private final Renderer _renderer;
private final AtomicBoolean _finished = new AtomicBoolean(false);
private final AtomicBoolean _fatalError = new AtomicBoolean(false);
private final AtomicBoolean _redraw = new AtomicBoolean(false);
private final AtomicBoolean _screenshot = new AtomicBoolean(false);
// These values are used to limit redraw rate, the stored values are time in milliseconds
// returned by System.currentTimeMillis()
private final AtomicLong _lastDraw = new AtomicLong(0);
private final AtomicLong _scheduledDraw = new AtomicLong(0);
private final ExceptionLogger _exceptionLogger;
private final static double FPS = 60;
private final Timer _timer;
private final HashMap<Integer, CameraControl> _windowControls = new HashMap<Integer, CameraControl>();
private final HashMap<Integer, View> _windowToViewMap= new HashMap<Integer, View>();
private int _activeWindowID = -1;
private final Object _popupLock;
private JPopupMenu _lastPopup;
/**
* The last scene rendered
*/
private ArrayList<RenderProxy> _cachedScene;
private DisplayEntity _selectedEntity = null;
private double _simTime = 0.0d;
private boolean _isDragging = false;
private long _dragHandleID = 0;
// The object type for drag-and-drop operation, if this is null, the user is not dragging
private ObjectType _dndObjectType;
private long _dndDropTime = 0;
// The video recorder to sample
private VideoRecorder _recorder;
private PreviewCache _previewCache = new PreviewCache();
// Below are special PickingIDs for resizing and dragging handles
public static final long MOVE_PICK_ID = -1;
// For now this order is implicitly the same as the handle order in RenderObserver, don't re arrange it without touching
// the handle list
public static final long RESIZE_POSX_PICK_ID = -2;
public static final long RESIZE_NEGX_PICK_ID = -3;
public static final long RESIZE_POSY_PICK_ID = -4;
public static final long RESIZE_NEGY_PICK_ID = -5;
public static final long RESIZE_PXPY_PICK_ID = -6;
public static final long RESIZE_PXNY_PICK_ID = -7;
public static final long RESIZE_NXPY_PICK_ID = -8;
public static final long RESIZE_NXNY_PICK_ID = -9;
public static final long ROTATE_PICK_ID = -10;
public static final long LINEDRAG_PICK_ID = -11;
// Line nodes start at this constant and proceed into the negative range, therefore this should be the lowest defined constant
public static final long LINENODE_PICK_ID = -12;
private RenderManager(boolean safeGraphics) {
_renderer = new Renderer(safeGraphics);
_exceptionLogger = new ExceptionLogger();
_managerThread = new Thread(new Runnable() {
@Override
public void run() {
renderManagerLoop();
}
}, "RenderManagerThread");
_managerThread.start();
// Start the display timer
_timer = new Timer("RedrawThread");
TimerTask displayTask = new TimerTask() {
@Override
public void run() {
// Is a redraw scheduled
long currentTime = System.currentTimeMillis();
long scheduledTime = _scheduledDraw.get();
long lastRedraw = _lastDraw.get();
// Only draw if the scheduled time is before now and after the last redraw
if (scheduledTime < lastRedraw || currentTime < scheduledTime) {
return;
}
synchronized(_redraw) {
if (_renderer.getNumOpenWindows() == 0 && !_screenshot.get()) {
return; // Do not queue a redraw if there are no open windows
}
_redraw.set(true);
_redraw.notifyAll();
}
}
};
_timer.scheduleAtFixedRate(displayTask, 0, (long) (1000 / (FPS*2)));
_popupLock = new Object();
}
public static final void updateTime(double simTime) {
if (!RenderManager.isGood())
return;
RenderManager.inst()._simTime = simTime;
RenderManager.inst().queueRedraw();
}
public void queueRedraw() {
long scheduledTime = _scheduledDraw.get();
long lastRedraw = _lastDraw.get();
if (scheduledTime > lastRedraw) {
// A draw is scheduled
return;
}
long newDraw = System.currentTimeMillis();
long frameTime = (long)(1000.0/FPS);
if (newDraw - lastRedraw < frameTime) {
// This would be scheduled too soon
newDraw = lastRedraw + frameTime;
}
_scheduledDraw.set(newDraw);
}
public void createWindow(View view) {
// First see if this window has already been opened
for (Map.Entry<Integer, CameraControl> entry : _windowControls.entrySet()) {
if (entry.getValue().getView() == view) {
// This view has a window, just reshow that one
focusWindow(entry.getKey());
return;
}
}
IntegerVector windSize = (IntegerVector)view.getInput("WindowSize").getValue();
IntegerVector windPos = (IntegerVector)view.getInput("WindowPosition").getValue();
Image icon = GUIFrame.getWindowIcon();
CameraControl control = new CameraControl(_renderer, view);
int windowID = _renderer.createWindow(windPos.get(0), windPos.get(1),
windSize.get(0), windSize.get(1),
view.getID(),
view.getTitle(), view.getInputName(),
icon, control);
_windowControls.put(windowID, control);
_windowToViewMap.put(windowID, view);
dirtyAllEntities();
queueRedraw();
}
public void closeAllWindows() {
ArrayList<Integer> windIDs = _renderer.getOpenWindowIDs();
for (int id : windIDs) {
_renderer.closeWindow(id);
}
}
public void windowClosed(int windowID) {
_windowControls.remove(windowID);
_windowToViewMap.remove(windowID);
}
public void setActiveWindow(int windowID) {
_activeWindowID = windowID;
}
public static boolean isGood() {
return (s_instance != null && !s_instance._finished.get() && !s_instance._fatalError.get());
}
/**
* Ideally, this states that it is safe to call initialize() (assuming isGood() returned false)
* @return
*/
public static boolean canInitialize() {
return s_instance == null;
}
private void dirtyAllEntities() {
for (int i = 0; i < DisplayEntity.getAll().size(); ++i) {
DisplayEntity.getAll().get(i).setGraphicsDataDirty();
}
}
private void renderManagerLoop() {
while (!_finished.get() && !_fatalError.get()) {
try {
if (_renderer.hasFatalError()) {
// Well, something went horribly wrong
_fatalError.set(true);
System.out.printf("Renderer failed with error: %s\n", _renderer.getErrorString());
// Do some basic cleanup
_windowControls.clear();
_previewCache.clear();
_timer.cancel();
break;
}
_lastDraw.set(System.currentTimeMillis());
if (!_renderer.isInitialized()) {
// Give the renderer a chance to initialize
try {
Thread.sleep(100);
} catch(InterruptedException e) {}
continue;
}
for (CameraControl cc : _windowControls.values()) {
cc.checkForUpdate();
}
_cachedScene = new ArrayList<RenderProxy>();
DisplayModelBinding.clearCacheCounters();
DisplayModelBinding.clearCacheMissData();
double renderTime = _simTime;
long startNanos = System.nanoTime();
for (int i = 0; i < View.getAll().size(); i++) {
View v = View.getAll().get(i);
v.update(renderTime);
}
ArrayList<DisplayModelBinding> selectedBindings = new ArrayList<DisplayModelBinding>();
// Update all graphical entities in the simulation
for (int i = 0; i < DisplayEntity.getAll().size(); i++) {
DisplayEntity de;
try {
de = DisplayEntity.getAll().get(i);
}
catch (IndexOutOfBoundsException e) {
break;
}
try {
de.updateGraphics(renderTime);
}
// Catch everything so we don't screw up the behavior handling
catch (Throwable e) {
logException(e);
}
}
long updateNanos = System.nanoTime();
int totalBindings = 0;
for (int i = 0; i < DisplayEntity.getAll().size(); i++) {
DisplayEntity de;
try {
de = DisplayEntity.getAll().get(i);
} catch (IndexOutOfBoundsException ex) {
// This is probably the end of the list, so just move on
break;
}
for (DisplayModelBinding binding : de.getDisplayBindings()) {
try {
totalBindings++;
binding.collectProxies(renderTime, _cachedScene);
if (binding.isBoundTo(_selectedEntity)) {
selectedBindings.add(binding);
}
} catch (Throwable t) {
// Log the exception in the exception list
logException(t);
}
}
}
// Collect selection proxies second so they always appear on top
for (DisplayModelBinding binding : selectedBindings) {
try {
binding.collectSelectionProxies(renderTime, _cachedScene);
} catch (Throwable t) {
// Log the exception in the exception list
logException(t);
}
}
long endNanos = System.nanoTime();
_renderer.setScene(_cachedScene);
String cacheString = " Hits: " + DisplayModelBinding.getCacheHits() + " Misses: " + DisplayModelBinding.getCacheMisses() +
" Total: " + totalBindings;
double gatherMS = (endNanos - updateNanos) / 1000000.0;
double updateMS = (updateNanos - startNanos) / 1000000.0;
String timeString = "Gather time (ms): " + gatherMS + " Update time (ms): " + updateMS;
// Do some picking debug
ArrayList<Integer> windowIDs = _renderer.getOpenWindowIDs();
for (int id : windowIDs) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(id);
if (mouseInfo == null || !mouseInfo.mouseInWindow) {
// Not currently picking for this window
_renderer.setWindowDebugInfo(id, cacheString + " Not picking. " + timeString, new ArrayList<Long>());
continue;
}
List<PickData> picks = pickForMouse(id, false);
ArrayList<Long> debugIDs = new ArrayList<Long>(picks.size());
StringBuilder dbgMsg = new StringBuilder(cacheString);
dbgMsg.append(" Picked ").append(picks.size());
dbgMsg.append(" entities at (").append(mouseInfo.x);
dbgMsg.append(", ").append(mouseInfo.y).append("): ");
for (PickData pd : picks) {
Entity ent = Entity.idToEntity(pd.id);
if (ent != null)
dbgMsg.append(ent.getInputName());
dbgMsg.append(", ");
debugIDs.add(pd.id);
}
dbgMsg.append(timeString);
_renderer.setWindowDebugInfo(id, dbgMsg.toString(), debugIDs);
}
if (GUIFrame.getShuttingDownFlag()) {
shutdown();
}
_renderer.queueRedraw();
_redraw.set(false);
if (_screenshot.get()) {
takeScreenShot();
}
} catch (Throwable t) {
// Make a note of it, but try to keep going
logException(t);
}
// Wait for a redraw request
synchronized(_redraw) {
while (!_redraw.get()) {
try {
_redraw.wait(30);
} catch (InterruptedException e) {}
}
}
}
_exceptionLogger.printExceptionLog();
}
// Temporary dumping ground until I find a better place for this
public void popupMenu(int windowID) {
synchronized (_popupLock) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
if (mouseInfo == null) {
// Somehow this window was closed along the way, just ignore this click
return;
}
final Frame awtFrame = _renderer.getAWTFrame(windowID);
if (awtFrame == null) {
return;
}
List<PickData> picks = pickForMouse(windowID, false);
ArrayList<DisplayEntity> ents = new ArrayList<DisplayEntity>();
for (PickData pd : picks) {
if (!pd.isEntity) { continue; }
Entity ent = Entity.idToEntity(pd.id);
if (ent == null) { continue; }
if (!(ent instanceof DisplayEntity)) { continue; }
DisplayEntity de = (DisplayEntity)ent;
ents.add(de);
}
if (!mouseInfo.mouseInWindow) {
// Somehow this window does not currently have the mouse over it.... ignore?
return;
}
final JPopupMenu menu = new JPopupMenu();
_lastPopup = menu;
menu.setLightWeightPopupEnabled(false);
final int menuX = mouseInfo.x + awtFrame.getInsets().left;
final int menuY = mouseInfo.y + awtFrame.getInsets().top;
if (ents.size() == 0) { return; } // Nothing to show
if (ents.size() == 1) {
ObjectSelector.populateMenu(menu, ents.get(0), menuX, menuY);
}
else {
// Several entities, let the user pick the interesting entity first
for (final DisplayEntity de : ents) {
JMenuItem thisItem = new JMenuItem(de.getInputName());
thisItem.addActionListener( new ActionListener() {
@Override
public void actionPerformed( ActionEvent event ) {
menu.removeAll();
ObjectSelector.populateMenu(menu, de, menuX, menuY);
menu.show(awtFrame, menuX, menuY);
}
} );
menu.add( thisItem );
}
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
menu.show(awtFrame, menuX, menuY);
menu.repaint();
}
});
} // synchronized (_popupLock)
}
public void handleSelection(int windowID) {
List<PickData> picks = pickForMouse(windowID, false);
Collections.sort(picks, new SelectionSorter());
for (PickData pd : picks) {
// Select the first entity after sorting
if (pd.isEntity) {
DisplayEntity ent = (DisplayEntity)Entity.idToEntity(pd.id);
if (!ent.isMovable()) {
continue;
}
FrameBox.setSelectedEntity(ent);
queueRedraw();
return;
}
}
FrameBox.setSelectedEntity(null);
queueRedraw();
}
/**
* Utility, convert a window and mouse coordinate into a list of picking IDs for that pixel
* @param windowID
* @param mouseX
* @param mouseY
* @return
*/
private List<PickData> pickForMouse(int windowID, boolean precise) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
View view = _windowToViewMap.get(windowID);
if (mouseInfo == null || view == null || !mouseInfo.mouseInWindow) {
// The mouse is not actually in the window, or the window was closed along the way
return new ArrayList<PickData>(); // empty set
}
Ray pickRay = RenderUtils.getPickRay(mouseInfo);
return pickForRay(pickRay, view.getID(), precise);
}
/**
* PickData represents enough information to sort a list of picks based on a picking preference
* metric. For now it holds the object size and distance from pick point to object center
*
*/
private static class PickData {
public long id;
public double size;
boolean isEntity;
/**
* This pick does not correspond to an entity, and is a handle or other UI element
* @param id
*/
public PickData(long id) {
this.id = id;
size = 0;
isEntity = false;
}
/**
* This pick was an entity
* @param id - the id
* @param ent - the entity
*/
public PickData(long id, DisplayEntity ent) {
this.id = id;
size = ent.getSize().mag3();
isEntity = true;
}
}
/**
* This Comparator sorts based on entity selection preference
*/
private class SelectionSorter implements Comparator<PickData> {
@Override
public int compare(PickData p0, PickData p1) {
if (p0.isEntity && !p1.isEntity) {
return -1;
}
if (!p0.isEntity && p1.isEntity) {
return 1;
}
if (p0.size == p1.size) {
return 0;
}
return (p0.size < p1.size) ? -1 : 1;
}
}
/**
* This Comparator sorts based on interaction handle priority
*/
private class HandleSorter implements Comparator<PickData> {
@Override
public int compare(PickData p0, PickData p1) {
int p0priority = getHandlePriority(p0.id);
int p1priority = getHandlePriority(p1.id);
if (p0priority == p1priority)
return 0;
return (p0priority < p1priority) ? 1 : -1;
}
}
/**
* This determines the priority for interaction handles if several are selectable at drag time
* @param handleID
* @return
*/
private static int getHandlePriority(long handleID) {
if (handleID == MOVE_PICK_ID) return 1;
if (handleID == LINEDRAG_PICK_ID) return 1;
if (handleID <= LINENODE_PICK_ID) return 2;
if (handleID == ROTATE_PICK_ID) return 3;
if (handleID == RESIZE_POSX_PICK_ID) return 4;
if (handleID == RESIZE_NEGX_PICK_ID) return 4;
if (handleID == RESIZE_POSY_PICK_ID) return 4;
if (handleID == RESIZE_NEGY_PICK_ID) return 4;
if (handleID == RESIZE_PXPY_PICK_ID) return 5;
if (handleID == RESIZE_PXNY_PICK_ID) return 5;
if (handleID == RESIZE_NXPY_PICK_ID) return 5;
if (handleID == RESIZE_NXNY_PICK_ID) return 5;
return 0;
}
public Vec3d getNearestPick(int windowID) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
View view = _windowToViewMap.get(windowID);
if (mouseInfo == null || view == null || !mouseInfo.mouseInWindow) {
// The mouse is not actually in the window, or the window was closed along the way
return null;
}
Ray pickRay = RenderUtils.getPickRay(mouseInfo);
List<Renderer.PickResult> picks = _renderer.pick(pickRay, view.getID(), true);
if (picks.size() == 0) {
return null;
}
double pickDist = Double.POSITIVE_INFINITY;
for (Renderer.PickResult pick : picks) {
if (pick.dist < pickDist && pick.pickingID >= 0) {
// Negative pickingIDs are reserved for interaction handles and are therefore not
// part of the content
pickDist = pick.dist;
}
}
if (pickDist == Double.POSITIVE_INFINITY) {
return null;
}
return pickRay.getPointAtDist(pickDist);
}
/**
* Perform a pick from this world space ray
* @param pickRay - the ray
* @return
*/
private List<PickData> pickForRay(Ray pickRay, int viewID, boolean precise) {
List<Renderer.PickResult> picks = _renderer.pick(pickRay, viewID, precise);
List<PickData> uniquePicks = new ArrayList<PickData>();
// IDs that have already been added
Set<Long> knownIDs = new HashSet<Long>();
for (Renderer.PickResult pick : picks) {
if (knownIDs.contains(pick.pickingID)) {
continue;
}
knownIDs.add(pick.pickingID);
DisplayEntity ent = (DisplayEntity)Entity.idToEntity(pick.pickingID);
if (ent == null) {
// This object is not an entity, but may be a picking handle
uniquePicks.add(new PickData(pick.pickingID));
} else {
uniquePicks.add(new PickData(pick.pickingID, ent));
}
}
return uniquePicks;
}
/**
* Pick on a window at a position other than the current mouse position
* @param windowID
* @param x
* @param y
* @return
*/
private Ray getRayForMouse(int windowID, int x, int y) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
if (mouseInfo == null) {
return new Ray();
}
return RenderUtils.getPickRayForPosition(mouseInfo.cameraInfo, x, y, mouseInfo.width, mouseInfo.height);
}
public Vec3d getRenderedStringSize(TessFontKey fontKey, double textHeight, String string) {
TessFont font = _renderer.getTessFont(fontKey);
return font.getStringSize(textHeight, string);
}
private void logException(Throwable t) {
_exceptionLogger.logException(t);
// And print the output
printExceptionLog();
}
private void printExceptionLog() {
System.out.println("Recoverable Exceptions from RenderManager: ");
_exceptionLogger.printExceptionLog();
System.out.println("");
}
public static void setSelection(Entity ent) {
if (!RenderManager.isGood())
return;
RenderManager.inst().setSelectEntity(ent);
}
private void setSelectEntity(Entity ent) {
if (ent instanceof DisplayEntity)
_selectedEntity = (DisplayEntity)ent;
else
_selectedEntity = null;
_isDragging = false;
queueRedraw();
}
/**
* This method gives the RenderManager a chance to handle mouse drags before the CameraControl
* gets to handle it (note: this may need to be refactored into a proper event handling heirarchy)
* @param dragInfo
* @return
*/
public boolean handleDrag(WindowInteractionListener.DragInfo dragInfo) {
if (!_isDragging) {
// We have not cached a drag handle ID, so don't claim this and let CameraControl have control back
return false;
}
// We should have a selected entity
assert(_selectedEntity != null);
// Any quick outs go here
if (!_selectedEntity.isMovable()) {
return false;
}
// For now, experimental controls requires control to be down to drag or resize
if (getExperimentalControls() != dragInfo.controlDown()) {
return false;
}
// Find the start and current world space positions
Ray currentRay = getRayForMouse(dragInfo.windowID, dragInfo.x, dragInfo.y);
Ray lastRay = getRayForMouse(dragInfo.windowID,
dragInfo.x - dragInfo.dx,
dragInfo.y - dragInfo.dy);
Transform trans = _selectedEntity.getGlobalTrans(_simTime);
Vec3d size = _selectedEntity.getSize();
Mat4d transMat = _selectedEntity.getTransMatrix(_simTime);
Mat4d invTransMat = _selectedEntity.getInvTransMatrix(_simTime);
Plane entityPlane = new Plane(); // Defaults to XY
entityPlane.transform(trans, entityPlane, new Vec3d()); // Transform the plane to world space
double currentDist = entityPlane.collisionDist(currentRay);
double lastDist = entityPlane.collisionDist(lastRay);
if (currentDist < 0 || currentDist == Double.POSITIVE_INFINITY ||
lastDist < 0 || lastDist == Double.POSITIVE_INFINITY)
{
// The plane is parallel or behind one of the rays...
return true; // Just ignore it for now...
}
// The points where the previous pick ended and current position. Collision is with the entity's XY plane
Vec3d currentPoint = currentRay.getPointAtDist(currentDist);
Vec3d lastPoint = lastRay.getPointAtDist(lastDist);
Vec3d entSpaceCurrent = new Vec3d(); // entSpacePoint is the current point in model space
entSpaceCurrent.multAndTrans3(invTransMat, currentPoint);
Vec3d entSpaceLast = new Vec3d(); // entSpaceLast is the last point in model space
entSpaceLast.multAndTrans3(invTransMat, lastPoint);
Vec3d delta = new Vec3d();
delta.sub3(currentPoint, lastPoint);
Vec3d entSpaceDelta = new Vec3d();
entSpaceDelta.sub3(entSpaceCurrent, entSpaceLast);
// Handle each handle by type...
if (_dragHandleID == MOVE_PICK_ID) {
// We are dragging
if (dragInfo.shiftDown()) {
Vec4d entPos = _selectedEntity.getGlobalPosition();
double zDiff = RenderUtils.getZDiff(entPos, currentRay, lastRay);
entPos.z += zDiff;
_selectedEntity.setGlobalPosition(entPos);
return true;
}
Vec4d pos = new Vec4d(_selectedEntity.getGlobalPosition());
pos.add3(delta);
_selectedEntity.setGlobalPosition(pos);
return true;
}
// Handle resize
if (_dragHandleID <= RESIZE_POSX_PICK_ID &&
_dragHandleID >= RESIZE_NXNY_PICK_ID) {
Vec4d pos = new Vec4d(_selectedEntity.getGlobalPosition());
Vec3d scale = _selectedEntity.getSize();
Vec4d fixedPoint = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
if (_dragHandleID == RESIZE_POSX_PICK_ID) {
//scale.x = 2*entSpaceCurrent.x() * size.x();
scale.x += entSpaceDelta.x * size.x;
fixedPoint = new Vec4d(-0.5, 0.0, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_POSY_PICK_ID) {
scale.y += entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.0, -0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NEGX_PICK_ID) {
scale.x -= entSpaceDelta.x * size.x;
fixedPoint = new Vec4d( 0.5, 0.0, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NEGY_PICK_ID) {
scale.y -= entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.0, 0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_PXPY_PICK_ID) {
scale.x += entSpaceDelta.x * size.x;
scale.y += entSpaceDelta.y * size.y;
fixedPoint = new Vec4d(-0.5, -0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_PXNY_PICK_ID) {
scale.x += entSpaceDelta.x * size.x;
scale.y -= entSpaceDelta.y * size.y;
fixedPoint = new Vec4d(-0.5, 0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NXPY_PICK_ID) {
scale.x -= entSpaceDelta.x * size.x;
scale.y += entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.5, -0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NXNY_PICK_ID) {
scale.x -= entSpaceDelta.x * size.x;
scale.y -= entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.5, 0.5, 0.0, 1.0d);
}
// Handle the case where the scale is pulled through itself. Fix the scale,
// and swap the currently selected handle
if (scale.x <= 0.00005) {
scale.x = 0.0001;
if (_dragHandleID == RESIZE_POSX_PICK_ID) { _dragHandleID = RESIZE_NEGX_PICK_ID; }
else if (_dragHandleID == RESIZE_NEGX_PICK_ID) { _dragHandleID = RESIZE_POSX_PICK_ID; }
else if (_dragHandleID == RESIZE_PXPY_PICK_ID) { _dragHandleID = RESIZE_NXPY_PICK_ID; }
else if (_dragHandleID == RESIZE_PXNY_PICK_ID) { _dragHandleID = RESIZE_NXNY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXPY_PICK_ID) { _dragHandleID = RESIZE_PXPY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXNY_PICK_ID) { _dragHandleID = RESIZE_PXNY_PICK_ID; }
}
if (scale.y <= 0.00005) {
scale.y = 0.0001;
if (_dragHandleID == RESIZE_POSY_PICK_ID) { _dragHandleID = RESIZE_NEGY_PICK_ID; }
else if (_dragHandleID == RESIZE_NEGY_PICK_ID) { _dragHandleID = RESIZE_POSY_PICK_ID; }
else if (_dragHandleID == RESIZE_PXPY_PICK_ID) { _dragHandleID = RESIZE_PXNY_PICK_ID; }
else if (_dragHandleID == RESIZE_PXNY_PICK_ID) { _dragHandleID = RESIZE_PXPY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXPY_PICK_ID) { _dragHandleID = RESIZE_NXNY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXNY_PICK_ID) { _dragHandleID = RESIZE_NXPY_PICK_ID; }
}
Vec4d oldFixed = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
oldFixed.mult4(transMat, fixedPoint);
_selectedEntity.setSize(scale);
transMat = _selectedEntity.getTransMatrix(_simTime); // Get the new matrix
Vec4d newFixed = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
newFixed.mult4(transMat, fixedPoint);
Vec4d posAdjust = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
posAdjust.sub3(oldFixed, newFixed);
pos.add3(posAdjust);
_selectedEntity.setGlobalPosition(pos);
Vec3d vec = _selectedEntity.getSize();
InputAgent.processEntity_Keyword_Value(_selectedEntity, "Size", String.format( "%.6f %.6f %.6f %s", vec.x, vec.y, vec.z, "m" ));
FrameBox.valueUpdate();
return true;
}
if (_dragHandleID == ROTATE_PICK_ID) {
Vec3d align = _selectedEntity.getAlignment();
Vec4d rotateCenter = new Vec4d(align.x, align.y, align.z, 1.0d);
rotateCenter.mult4(transMat, rotateCenter);
Vec4d a = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
a.sub3(lastPoint, rotateCenter);
Vec4d b = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
b.sub3(currentPoint, rotateCenter);
Vec4d aCrossB = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
aCrossB.cross3(a, b);
double sinTheta = aCrossB.z / a.mag3() / b.mag3();
double theta = Math.asin(sinTheta);
Vec3d orient = _selectedEntity.getOrientation();
orient.z += theta;
InputAgent.processEntity_Keyword_Value(_selectedEntity, "Orientation", String.format("%f %f %f rad", orient.x, orient.y, orient.z));
FrameBox.valueUpdate();
return true;
}
if (_dragHandleID == LINEDRAG_PICK_ID) {
// Dragging a line object
if (dragInfo.shiftDown()) {
ArrayList<Vec3d> screenPoints = null;
if (_selectedEntity instanceof HasScreenPoints)
screenPoints = ((HasScreenPoints)_selectedEntity).getScreenPoints();
if (screenPoints == null || screenPoints.size() == 0) return true; // just ignore this
// Find the geometric median of the points
Vec4d medPoint = RenderUtils.getGeometricMedian(screenPoints);
double zDiff = RenderUtils.getZDiff(medPoint, currentRay, lastRay);
_selectedEntity.dragged(new Vec3d(0, 0, zDiff));
return true;
}
Region reg = _selectedEntity.getCurrentRegion();
Transform regionInvTrans = new Transform();
if (reg != null) {
regionInvTrans = reg.getRegionTrans(0.0d);
regionInvTrans.inverse(regionInvTrans);
}
Vec4d localDelta = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
regionInvTrans.apply(delta, localDelta);
_selectedEntity.dragged(localDelta);
return true;
}
if (_dragHandleID <= LINENODE_PICK_ID) {
int nodeIndex = (int)(-1*(_dragHandleID - LINENODE_PICK_ID));
ArrayList<Vec3d> screenPoints = null;
if (_selectedEntity instanceof HasScreenPoints)
screenPoints = ((HasScreenPoints)_selectedEntity).getScreenPoints();
// Note: screenPoints is not a defensive copy, but we'll put it back into itself
// in a second so everything should be safe
if (screenPoints == null || nodeIndex >= screenPoints.size()) {
// huh?
return false;
}
Vec3d point = screenPoints.get(nodeIndex);
if (dragInfo.shiftDown()) {
double zDiff = RenderUtils.getZDiff(point, currentRay, lastRay);
point.z += zDiff;
} else {
Plane pointPlane = new Plane(Vec4d.Z_AXIS, point.z);
Vec3d diff = RenderUtils.getPlaneCollisionDiff(pointPlane, currentRay, lastRay);
point.x += diff.x;
point.y += diff.y;
point.z += 0;
}
Input<?> pointsInput = _selectedEntity.getInput("Points");
assert(pointsInput != null);
if (pointsInput == null) {
_selectedEntity.setGraphicsDataDirty();
return true;
}
StringBuilder sb = new StringBuilder();
String pointFormatter = " { %.3f %.3f %.3f m }";
for(Vec3d pt : screenPoints) {
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
InputAgent.processEntity_Keyword_Value(_selectedEntity, pointsInput, sb.toString());
FrameBox.valueUpdate();
_selectedEntity.setGraphicsDataDirty();
return true;
}
return false;
}
private void splitLineEntity(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
Mat4d rayMatrix = MathUtils.RaySpace(currentRay);
HasScreenPoints hsp = (HasScreenPoints)_selectedEntity;
assert(hsp != null);
ArrayList<Vec3d> points = hsp.getScreenPoints();
int splitInd = 0;
Vec4d nearPoint = null;
// Find a line segment we are near
for (;splitInd < points.size() - 1; ++splitInd) {
Vec4d a = new Vec4d(points.get(splitInd ).x, points.get(splitInd ).y, points.get(splitInd ).z, 1.0d);
Vec4d b = new Vec4d(points.get(splitInd+1).x, points.get(splitInd+1).y, points.get(splitInd+1).z, 1.0d);
nearPoint = RenderUtils.rayClosePoint(rayMatrix, a, b);
double rayAngle = RenderUtils.angleToRay(rayMatrix, nearPoint);
if (rayAngle > 0 && rayAngle < 0.01309) { // 0.75 degrees in radians
break;
}
}
if (splitInd == points.size() - 1) {
// No appropriate point was found
return;
}
// If we are here, we have a segment to split, at index i
StringBuilder sb = new StringBuilder();
String pointFormatter = " { %.3f %.3f %.3f m }";
for(int i = 0; i <= splitInd; ++i) {
Vec3d pt = points.get(i);
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
sb.append(String.format(pointFormatter, nearPoint.x, nearPoint.y, nearPoint.z));
for (int i = splitInd+1; i < points.size(); ++i) {
Vec3d pt = points.get(i);
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
Input<?> pointsInput = _selectedEntity.getInput("Points");
InputAgent.processEntity_Keyword_Value(_selectedEntity, pointsInput, sb.toString());
FrameBox.valueUpdate();
_selectedEntity.setGraphicsDataDirty();
}
private void removeLineNode(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
Mat4d rayMatrix = MathUtils.RaySpace(currentRay);
HasScreenPoints hsp = (HasScreenPoints)_selectedEntity;
assert(hsp != null);
ArrayList<Vec3d> points = hsp.getScreenPoints();
// Find a point that is within the threshold
if (points.size() <= 2) {
return;
}
int removeInd = 0;
// Find a line segment we are near
for ( ;removeInd < points.size(); ++removeInd) {
Vec4d p = new Vec4d(points.get(removeInd).x, points.get(removeInd).y, points.get(removeInd).z, 1.0d);
double rayAngle = RenderUtils.angleToRay(rayMatrix, p);
if (rayAngle > 0 && rayAngle < 0.01309) { // 0.75 degrees in radians
break;
}
if (removeInd == points.size()) {
// No appropriate point was found
return;
}
}
StringBuilder sb = new StringBuilder();
String pointFormatter = " { %.3f %.3f %.3f m }";
for(int i = 0; i < points.size(); ++i) {
if (i == removeInd) {
continue;
}
Vec3d pt = points.get(i);
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
Input<?> pointsInput = _selectedEntity.getInput("Points");
InputAgent.processEntity_Keyword_Value(_selectedEntity, pointsInput, sb.toString());
FrameBox.valueUpdate();
_selectedEntity.setGraphicsDataDirty();
}
private boolean isMouseHandleID(long id) {
return (id < 0); // For now all negative IDs are mouse handles, this may change
}
public boolean handleMouseButton(int windowID, int x, int y, int button, boolean isDown, int modifiers) {
if (button != 1) { return false; }
if (!isDown) {
// Click released
_isDragging = false;
return true; // handled
}
boolean controlDown = (modifiers & WindowInteractionListener.MOD_CTRL) != 0;
if (controlDown) {
// Check if we can split a line segment
if (_selectedEntity != null && _selectedEntity instanceof HasScreenPoints) {
if ((modifiers & WindowInteractionListener.MOD_SHIFT) != 0) {
removeLineNode(windowID, x, y);
} else {
splitLineEntity(windowID, x, y);
}
return true;
}
}
if (controlDown != getExperimentalControls()) {
_isDragging = false;
return false;
}
Ray pickRay = getRayForMouse(windowID, x, y);
View view = _windowToViewMap.get(windowID);
if (view == null) {
return false;
}
List<PickData> picks = pickForRay(pickRay, view.getID(), false);
Collections.sort(picks, new HandleSorter());
if (picks.size() == 0) {
return false;
}
// See if we are hovering over any interaction handles
for (PickData pd : picks) {
if (isMouseHandleID(pd.id)) {
// this is a mouse handle, remember the handle for future drag events
_isDragging = true;
_dragHandleID = pd.id;
return true;
}
}
return false;
}
public void clearSelection() {
_selectedEntity = null;
_isDragging = false;
}
public void hideExistingPopups() {
synchronized (_popupLock) {
if (_lastPopup == null) {
return;
}
_lastPopup.setVisible(false);
_lastPopup = null;
}
}
public boolean isDragAndDropping() {
// This is such a brutal hack to work around newt's lack of drag and drop support
// Claim we are still dragging for up to 10ms after the last drop failed...
long currTime = System.nanoTime();
return _dndObjectType != null &&
((currTime - _dndDropTime) < 100000000); // Did the last 'drop' happen less than 100 ms ago?
}
public void startDragAndDrop(ObjectType ot) {
_dndObjectType = ot;
}
public void mouseMoved(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
double dist = Plane.XY_PLANE.collisionDist(currentRay);
if (dist == Double.POSITIVE_INFINITY) {
// I dunno...
return;
}
Vec3d xyPlanePoint = currentRay.getPointAtDist(dist);
GUIFrame.instance().showLocatorPosition(xyPlanePoint);
queueRedraw();
}
public void createDNDObject(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
double dist = Plane.XY_PLANE.collisionDist(currentRay);
if (dist == Double.POSITIVE_INFINITY) {
// Unfortunate...
return;
}
Vec3d creationPoint = currentRay.getPointAtDist(dist);
// Create a new instance
Class<? extends Entity> proto = _dndObjectType.getJavaClass();
String name = proto.getSimpleName();
Entity ent = InputAgent.defineEntityWithUniqueName(proto, name, true);
// We are no longer drag-and-dropping
_dndObjectType = null;
FrameBox.setSelectedEntity(ent);
if (!(ent instanceof DisplayEntity)) {
// This object is not a display entity, so the rest of this method does not apply
return;
}
DisplayEntity dEntity = (DisplayEntity) ent;
try {
dEntity.dragged(creationPoint);
}
catch (InputErrorException e) {}
boolean isFlat = false;
// Shudder....
ArrayList<DisplayModel> displayModels = dEntity.getDisplayModelList();
if (displayModels != null && displayModels.size() > 0) {
DisplayModel dm0 = displayModels.get(0);
if (dm0 instanceof DisplayModelCompat || dm0 instanceof ImageModel)
isFlat = true;
}
if (dEntity instanceof HasScreenPoints) {
isFlat = true;
}
if (dEntity instanceof Graph) {
isFlat = true;
}
if (isFlat) {
Vec3d size = dEntity.getSize();
Input<?> in = dEntity.getInput("Size");
StringVector args = new StringVector(4);
args.add(String.format("%.3f", size.x));
args.add(String.format("%.3f", size.y));
args.add("0.0");
args.add("m");
InputAgent.apply(dEntity, in, args);
InputAgent.updateInput(dEntity, in, args);
} else {
Input<?> in = dEntity.getInput("Alignment");
StringVector args = new StringVector(3);
args.add("0.0");
args.add("0.0");
args.add("-0.5");
InputAgent.apply(dEntity, in, args);
InputAgent.updateInput(dEntity, in, args);
}
FrameBox.valueUpdate();
}
@Override
public void dragDropEnd(DragSourceDropEvent arg0) {
// Clear the dragging flag
_dndDropTime = System.nanoTime();
}
@Override
public void dragEnter(DragSourceDragEvent arg0) {}
@Override
public void dragExit(DragSourceEvent arg0) {}
@Override
public void dragOver(DragSourceDragEvent arg0) {}
@Override
public void dropActionChanged(DragSourceDragEvent arg0) {}
public AABB getMeshBounds(MeshProtoKey key, boolean block) {
if (block || MeshDataCache.isMeshLoaded(key)) {
return MeshDataCache.getMeshData(key).getDefaultBounds();
}
// The mesh is not loaded and we are non-blocking, so trigger a mesh load and return
MeshDataCache.loadMesh(key, new AtomicBoolean());
return null;
}
public ArrayList<Action.Description> getMeshActions(MeshProtoKey key, boolean block) {
if (block || MeshDataCache.isMeshLoaded(key)) {
return MeshDataCache.getMeshData(key).getActionDescriptions();
}
// The mesh is not loaded and we are non-blocking, so trigger a mesh load and return
MeshDataCache.loadMesh(key, new AtomicBoolean());
return null;
}
/**
* Set the current windows camera to an isometric view
*/
public void setIsometricView() {
CameraControl control = _windowControls.get(_activeWindowID);
if (control == null) return;
// The constant is acos(1/sqrt(3))
control.setRotationAngles(0.955316, Math.PI/4);
}
/**
* Set the current windows camera to an XY plane view
*/
public void setXYPlaneView() {
CameraControl control = _windowControls.get(_activeWindowID);
if (control == null) return;
control.setRotationAngles(0.0, 0.0);
}
public View getActiveView() {
return _windowToViewMap.get(_activeWindowID);
}
public ArrayList<Integer> getOpenWindowIDs() {
return _renderer.getOpenWindowIDs();
}
public String getWindowName(int windowID) {
return _renderer.getWindowName(windowID);
}
public void focusWindow(int windowID) {
_renderer.focusWindow(windowID);
}
public boolean getExperimentalControls() {
return GUIFrame.instance().getExperimentalControls();
}
/**
* Queue up an off screen rendering, this simply passes the call directly to the renderer
* @param scene
* @param camInfo
* @param width
* @param height
* @return
*/
public Future<BufferedImage> renderOffscreen(ArrayList<RenderProxy> scene, CameraInfo camInfo, int viewID,
int width, int height, Runnable runWhenDone) {
return _renderer.renderOffscreen(scene, viewID, camInfo, width, height, runWhenDone, null);
}
/**
* Return a FutureImage of the equivalent screen renderer from the given position looking at the given center
* @param cameraPos
* @param viewCenter
* @param width - width of returned image
* @param height - height of returned image
* @param target - optional target to prevent re-allocating GPU resources
* @return
*/
public Future<BufferedImage> renderScreenShot(Vec3d cameraPos, Vec3d viewCenter, int viewID,
int width, int height, OffscreenTarget target) {
Vec3d viewDiff = new Vec3d();
viewDiff.sub3(cameraPos, viewCenter);
double rotZ = Math.atan2(viewDiff.x, -viewDiff.y);
double xyDist = Math.hypot(viewDiff.x, viewDiff.y);
double rotX = Math.atan2(xyDist, viewDiff.z);
if (Math.abs(rotX) < 0.005) {
rotZ = 0; // Don't rotate if we are looking straight up or down
}
double viewDist = viewDiff.mag3();
Quaternion rot = new Quaternion();
rot.setRotZAxis(rotZ);
Quaternion tmp = new Quaternion();
tmp.setRotXAxis(rotX);
rot.mult(rot, tmp);
Transform trans = new Transform(cameraPos, rot, 1);
CameraInfo camInfo = new CameraInfo(Math.PI/3, viewDist*0.1, viewDist*10, trans);
return _renderer.renderOffscreen(_cachedScene, viewID, camInfo, width, height, null, target);
}
public Future<BufferedImage> getPreviewForDisplayModel(DisplayModel dm, Runnable notifier) {
return _previewCache.getPreview(dm, notifier);
}
public OffscreenTarget createOffscreenTarget(int width, int height) {
return _renderer.createOffscreenTarget(width, height);
}
public void freeOffscreenTarget(OffscreenTarget target) {
_renderer.freeOffscreenTarget(target);
}
private void takeScreenShot() {
if (_recorder != null)
_recorder.sample();
synchronized(_screenshot) {
_screenshot.set(false);
_recorder = null;
_screenshot.notifyAll();
}
}
public void blockOnScreenShot(VideoRecorder recorder) {
assert(!_screenshot.get());
synchronized (_screenshot) {
_screenshot.set(true);
_recorder = recorder;
queueRedraw();
while (_screenshot.get()) {
try {
_screenshot.wait();
} catch (InterruptedException ex) {}
}
}
}
public void shutdown() {
_finished.set(true);
if (_renderer != null) {
_renderer.shutdown();
}
}
}
| JS: Fix for bug when using the XY-plane view button with new controls
Signed-off-by: Matt Chudleigh <[email protected]>
Signed-off-by: Harvey Harrison <[email protected]>
| src/main/java/com/jaamsim/controllers/RenderManager.java | JS: Fix for bug when using the XY-plane view button with new controls | <ide><path>rc/main/java/com/jaamsim/controllers/RenderManager.java
<ide> CameraControl control = _windowControls.get(_activeWindowID);
<ide> if (control == null) return;
<ide>
<del> control.setRotationAngles(0.0, 0.0);
<add> // Do not look straight down the Z axis as that is actually a degenerate state
<add> control.setRotationAngles(0.0000001, 0.0);
<ide> }
<ide>
<ide> public View getActiveView() { |
|
Java | apache-2.0 | 0bf804227ee298065e478dd3900e91e40a72df71 | 0 | luisfdeandrade/client,viniciusboson/client,christianrafael/client,projectbuendia/client,christianrafael/client,viniciusboson/client,llvasconcellos/client,projectbuendia/client,projectbuendia/client,fcruz/client,luisfdeandrade/client,llvasconcellos/client,viniciusboson/client,G1DR4/client,pedromarins/client,jvanz/client,projectbuendia/client,christianrafael/client,luisfdeandrade/client,projectbuendia/client,llvasconcellos/client | package org.msf.records.ui;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.SearchView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.crashlytics.android.Crashlytics;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.listeners.ActionClickListener;
import com.squareup.otto.Subscribe;
import org.msf.records.App;
import org.msf.records.R;
import org.msf.records.events.UpdateAvailableEvent;
import org.msf.records.events.UpdateDownloadedEvent;
import org.msf.records.net.OdkXformSyncTask;
import org.msf.records.net.OpenMrsXformIndexEntry;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.provider.FormsProviderAPI;
import org.odk.collect.android.tasks.DiskSyncTask;
import java.io.File;
import java.util.List;
/**
* An activity representing a list of Patients. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {@link PatientDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
* <p>
* The activity makes heavy use of fragments. The list of items is a
* {@link PatientListFragment} and the item details
* (if present) is a {@link PatientDetailFragment}.
* <p>
* This activity also implements the required
* {@link PatientListFragment.Callbacks} interface
* to listen for item selections.
*/
public class PatientListActivity extends FragmentActivity
implements PatientListFragment.Callbacks {
private static final String TAG = PatientListActivity.class.getSimpleName();
private SearchView mSearchView;
private View mScanBtn, mAddPatientBtn, mSettingsBtn;
private OnSearchListener mSearchListerner;
private Snackbar updateAvailableSnackbar, updateDownloadedSnackbar;
interface OnSearchListener {
void setQuerySubmited(String q);
}
public void setOnSearchListener(OnSearchListener onSearchListener){
this.mSearchListerner = onSearchListener;
}
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Crashlytics.start(this);
setContentView(R.layout.activity_patient_list);
getActionBar().setDisplayShowHomeEnabled(false);
if (findViewById(R.id.patient_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-large and
// res/values-sw600dp). If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// In two-pane mode, list items should be given the
// 'activated' state when touched.
((PatientListFragment) getSupportFragmentManager()
.findFragmentById(R.id.patient_list))
.setActivateOnItemClick(true);
setupCustomActionBar();
}
updateAvailableSnackbar = Snackbar.with(this)
.text("Application update available")
.actionLabel("Download")
.swipeToDismiss(true)
.animation(false)
.duration(Snackbar.SnackbarDuration.LENGTH_FOREVER);
updateDownloadedSnackbar = Snackbar.with(this)
.text("Application update downloaded")
.actionLabel("Install")
.swipeToDismiss(true)
.animation(false)
.duration(Snackbar.SnackbarDuration.LENGTH_FOREVER);
// TODO: If exposing deep links into your app, handle intents here.
}
@Override
protected void onResume() {
super.onResume();
App.getMainThreadBus().register(this);
App.getUpdateManager().checkForUpdate(App.getMainThreadBus());
}
@Override
protected void onPause() {
App.getMainThreadBus().unregister(this);
updateAvailableSnackbar.dismiss();
updateDownloadedSnackbar.dismiss();
super.onPause();
}
/**
* Displays a {@link Snackbar} indicating that an update is available upon receiving an
* {@link UpdateAvailableEvent}.
*/
@Subscribe
public void onUpdateAvailableEvent(final UpdateAvailableEvent event) {
updateAvailableSnackbar
.actionListener(new ActionClickListener() {
@Override
public void onActionClicked() {
App.getUpdateManager()
.downloadUpdate(App.getMainThreadBus(), event.mUpdateInfo);
}
});
if (updateAvailableSnackbar.isDismissed()) {
updateAvailableSnackbar.show(this);
}
}
/**
* Displays a {@link Snackbar} indicating that an update has been downloaded upon receiving an
* {@link UpdateDownloadedEvent}.
*/
@Subscribe
public void onUpdateDownloadedEvent(final UpdateDownloadedEvent event) {
updateAvailableSnackbar.dismiss();
updateDownloadedSnackbar
.actionListener(new ActionClickListener() {
@Override
public void onActionClicked() {
App.getUpdateManager().installUpdate(event.mUpdateInfo);
}
});
if (updateDownloadedSnackbar.isDismissed()) {
updateDownloadedSnackbar.show(this);
}
}
private void setupCustomActionBar(){
final LayoutInflater inflater = (LayoutInflater) getActionBar().getThemedContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(
ActionBar.DISPLAY_SHOW_CUSTOM,
ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_TITLE);
final View customActionBarView = inflater.inflate(
R.layout.actionbar_custom_main, null);
mAddPatientBtn = customActionBarView.findViewById(R.id.actionbar_add_patient);
mScanBtn = customActionBarView.findViewById(R.id.actionbar_scan);
mSettingsBtn = customActionBarView.findViewById(R.id.actionbar_settings);
mSearchView = (SearchView) customActionBarView.findViewById(R.id.actionbar_custom_main_search);
mSearchView.setIconifiedByDefault(false);
actionBar.setCustomView(customActionBarView, new ActionBar.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
/**
* Callback method from {@link PatientListFragment.Callbacks}
* indicating that the item with the given ID was selected.
*/
@Override
public void onItemSelected(String id) {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(PatientDetailFragment.PATIENT_ID_KEY, id);
PatientDetailFragment fragment = new PatientDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.patient_detail_container, fragment)
.commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent detailIntent = new Intent(this, PatientDetailActivity.class);
detailIntent.putExtra(PatientDetailFragment.PATIENT_ID_KEY, id);
startActivity(detailIntent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
if(!mTwoPane) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
menu.findItem(R.id.action_add).setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
startActivity(PatientAddActivity.class);
return false;
}
});
menu.findItem(R.id.action_settings).setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
startActivity(SettingsActivity.class);
return false;
}
});
menu.findItem(R.id.action_scan).setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
startScanBracelet();
return false;
}
});
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchMenuItem.getActionView();
mSearchView.setIconifiedByDefault(false);
searchMenuItem.expandActionView();
} else {
mAddPatientBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(PatientAddActivity.class);
}
});
mSettingsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(SettingsActivity.class);
}
});
mScanBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startScanBracelet();
}
});
}
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
InputMethodManager mgr = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if (mSearchListerner != null)
mSearchListerner.setQuerySubmited(newText);
return true;
}
});
return true;
}
private enum ScanAction {
PLAY_WITH_ODK,
FETCH_XFORMS,
FAKE_SCAN,
}
private void startScanBracelet() {
ScanAction scanAction = ScanAction.FAKE_SCAN;
switch (scanAction) {
case PLAY_WITH_ODK:
showFirstFormFromSdcard();
break;
case FAKE_SCAN:
showFakeScanProgress();
break;
case FETCH_XFORMS:
fetchXforms();
break;
}
}
private void fetchXforms() {
final String tag = "fetchXforms";
final Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(tag, error.toString());
}
};
App.getmOpenMrsXformsConnection().listXforms(
new Response.Listener<List<OpenMrsXformIndexEntry>>() {
@Override
public void onResponse(final List<OpenMrsXformIndexEntry> response) {
if (response.isEmpty()) {
return;
}
// Cache all the forms into the ODK form cache
new OdkXformSyncTask(new OdkXformSyncTask.FormWrittenListener() {
boolean displayed;
@Override
public void formWritten(File path) {
Log.i(TAG, "wrote form " + path);
// Just display one form.
synchronized (this) {
if (displayed) {
return;
} else {
displayed = true;
}
}
// TODO(nfortescue): factor out this ODK database stuff to somewhere
// common
// Fetch it from the ODK database
Cursor cursor = OdkXformSyncTask.getCursorForFormFile(
path, new String[]{
FormsProviderAPI.FormsColumns.JR_FORM_ID
});
long formId = cursor.getLong(0);
showOdkCollect(formId);
}
}).execute(response.toArray(new OpenMrsXformIndexEntry[response.size()]));
}
}, errorListener);
}
private void showFirstFormFromSdcard() {
// Sync the local sdcard forms into the database
new DiskSyncTask().execute((Void[]) null);
showOdkCollect(1L);
}
private void showOdkCollect(long formId) {
Intent intent = new Intent(this, FormEntryActivity.class);
Uri formUri = ContentUris.withAppendedId(FormsProviderAPI.FormsColumns.CONTENT_URI, formId);
intent.setData(formUri);
startActivity(intent);
}
private void showFakeScanProgress() {
final ProgressDialog progressDialog = ProgressDialog
.show(PatientListActivity.this, null, "Scanning for near by bracelets ...", true);
progressDialog.setCancelable(true);
progressDialog.show();
}
private void startActivity(Class<?> activityClass) {
Intent intent = new Intent(PatientListActivity.this, activityClass);
startActivity(intent);
}
}
| app/src/main/java/org/msf/records/ui/PatientListActivity.java | package org.msf.records.ui;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.SearchView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.crashlytics.android.Crashlytics;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.listeners.ActionClickListener;
import com.squareup.otto.Subscribe;
import org.msf.records.App;
import org.msf.records.R;
import org.msf.records.events.UpdateAvailableEvent;
import org.msf.records.events.UpdateDownloadedEvent;
import org.msf.records.net.OdkXformSyncTask;
import org.msf.records.net.OpenMrsXformIndexEntry;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.provider.FormsProviderAPI;
import org.odk.collect.android.tasks.DiskSyncTask;
import java.io.File;
import java.util.List;
/**
* An activity representing a list of Patients. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {@link PatientDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
* <p>
* The activity makes heavy use of fragments. The list of items is a
* {@link PatientListFragment} and the item details
* (if present) is a {@link PatientDetailFragment}.
* <p>
* This activity also implements the required
* {@link PatientListFragment.Callbacks} interface
* to listen for item selections.
*/
public class PatientListActivity extends FragmentActivity
implements PatientListFragment.Callbacks {
private static final String TAG = PatientListActivity.class.getSimpleName();
private SearchView mSearchView;
private View mScanBtn, mAddPatientBtn, mSettingsBtn;
private OnSearchListener mSearchListerner;
private Snackbar updateAvailableSnackbar, updateDownloadedSnackbar;
interface OnSearchListener {
void setQuerySubmited(String q);
}
public void setOnSearchListener(OnSearchListener onSearchListener){
this.mSearchListerner = onSearchListener;
}
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Crashlytics.start(this);
setContentView(R.layout.activity_patient_list);
getActionBar().setDisplayShowHomeEnabled(false);
if (findViewById(R.id.patient_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-large and
// res/values-sw600dp). If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// In two-pane mode, list items should be given the
// 'activated' state when touched.
((PatientListFragment) getSupportFragmentManager()
.findFragmentById(R.id.patient_list))
.setActivateOnItemClick(true);
setupCustomActionBar();
}
updateAvailableSnackbar = Snackbar.with(this)
.text("Application update available")
.actionLabel("Download")
.swipeToDismiss(false)
.duration(Snackbar.SnackbarDuration.LENGTH_FOREVER);
updateDownloadedSnackbar = Snackbar.with(this)
.text("Application update downloaded")
.actionLabel("Install")
.swipeToDismiss(false)
.duration(Snackbar.SnackbarDuration.LENGTH_FOREVER);
// TODO: If exposing deep links into your app, handle intents here.
}
@Override
protected void onResume() {
super.onResume();
App.getMainThreadBus().register(this);
App.getUpdateManager().checkForUpdate(App.getMainThreadBus());
}
@Override
protected void onPause() {
App.getMainThreadBus().unregister(this);
super.onPause();
}
/**
* Displays a {@link Snackbar} indicating that an update is available upon receiving an
* {@link UpdateAvailableEvent}.
*/
@Subscribe
public void onUpdateAvailableEvent(final UpdateAvailableEvent event) {
updateDownloadedSnackbar.dismiss();
updateAvailableSnackbar
.actionListener(new ActionClickListener() {
@Override
public void onActionClicked() {
App.getUpdateManager()
.downloadUpdate(App.getMainThreadBus(), event.mUpdateInfo);
}
});
if (updateAvailableSnackbar.isDismissed()) {
updateAvailableSnackbar.show(this);
}
}
/**
* Displays a {@link Snackbar} indicating that an update has been downloaded upon receiving an
* {@link UpdateDownloadedEvent}.
*/
@Subscribe
public void onUpdateDownloadedEvent(final UpdateDownloadedEvent event) {
updateAvailableSnackbar.dismiss();
updateDownloadedSnackbar
.actionListener(new ActionClickListener() {
@Override
public void onActionClicked() {
App.getUpdateManager().installUpdate(event.mUpdateInfo);
}
});
if (updateDownloadedSnackbar.isDismissed()) {
updateDownloadedSnackbar.show(this);
}
}
private void setupCustomActionBar(){
final LayoutInflater inflater = (LayoutInflater) getActionBar().getThemedContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(
ActionBar.DISPLAY_SHOW_CUSTOM,
ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_TITLE);
final View customActionBarView = inflater.inflate(
R.layout.actionbar_custom_main, null);
mAddPatientBtn = customActionBarView.findViewById(R.id.actionbar_add_patient);
mScanBtn = customActionBarView.findViewById(R.id.actionbar_scan);
mSettingsBtn = customActionBarView.findViewById(R.id.actionbar_settings);
mSearchView = (SearchView) customActionBarView.findViewById(R.id.actionbar_custom_main_search);
mSearchView.setIconifiedByDefault(false);
actionBar.setCustomView(customActionBarView, new ActionBar.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
/**
* Callback method from {@link PatientListFragment.Callbacks}
* indicating that the item with the given ID was selected.
*/
@Override
public void onItemSelected(String id) {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(PatientDetailFragment.PATIENT_ID_KEY, id);
PatientDetailFragment fragment = new PatientDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.patient_detail_container, fragment)
.commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent detailIntent = new Intent(this, PatientDetailActivity.class);
detailIntent.putExtra(PatientDetailFragment.PATIENT_ID_KEY, id);
startActivity(detailIntent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
if(!mTwoPane) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
menu.findItem(R.id.action_add).setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
startActivity(PatientAddActivity.class);
return false;
}
});
menu.findItem(R.id.action_settings).setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
startActivity(SettingsActivity.class);
return false;
}
});
menu.findItem(R.id.action_scan).setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
startScanBracelet();
return false;
}
});
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchMenuItem.getActionView();
mSearchView.setIconifiedByDefault(false);
searchMenuItem.expandActionView();
} else {
mAddPatientBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(PatientAddActivity.class);
}
});
mSettingsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(SettingsActivity.class);
}
});
mScanBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startScanBracelet();
}
});
}
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
InputMethodManager mgr = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if (mSearchListerner != null)
mSearchListerner.setQuerySubmited(newText);
return true;
}
});
return true;
}
private enum ScanAction {
PLAY_WITH_ODK,
FETCH_XFORMS,
FAKE_SCAN,
}
private void startScanBracelet() {
ScanAction scanAction = ScanAction.FAKE_SCAN;
switch (scanAction) {
case PLAY_WITH_ODK:
showFirstFormFromSdcard();
break;
case FAKE_SCAN:
showFakeScanProgress();
break;
case FETCH_XFORMS:
fetchXforms();
break;
}
}
private void fetchXforms() {
final String tag = "fetchXforms";
final Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(tag, error.toString());
}
};
App.getmOpenMrsXformsConnection().listXforms(
new Response.Listener<List<OpenMrsXformIndexEntry>>() {
@Override
public void onResponse(final List<OpenMrsXformIndexEntry> response) {
if (response.isEmpty()) {
return;
}
// Cache all the forms into the ODK form cache
new OdkXformSyncTask(new OdkXformSyncTask.FormWrittenListener() {
boolean displayed;
@Override
public void formWritten(File path) {
Log.i(TAG, "wrote form " + path);
// Just display one form.
synchronized (this) {
if (displayed) {
return;
} else {
displayed = true;
}
}
// TODO(nfortescue): factor out this ODK database stuff to somewhere
// common
// Fetch it from the ODK database
Cursor cursor = OdkXformSyncTask.getCursorForFormFile(
path, new String[]{
FormsProviderAPI.FormsColumns.JR_FORM_ID
});
long formId = cursor.getLong(0);
showOdkCollect(formId);
}
}).execute(response.toArray(new OpenMrsXformIndexEntry[response.size()]));
}
}, errorListener);
}
private void showFirstFormFromSdcard() {
// Sync the local sdcard forms into the database
new DiskSyncTask().execute((Void[]) null);
showOdkCollect(1L);
}
private void showOdkCollect(long formId) {
Intent intent = new Intent(this, FormEntryActivity.class);
Uri formUri = ContentUris.withAppendedId(FormsProviderAPI.FormsColumns.CONTENT_URI, formId);
intent.setData(formUri);
startActivity(intent);
}
private void showFakeScanProgress() {
final ProgressDialog progressDialog = ProgressDialog
.show(PatientListActivity.this, null, "Scanning for near by bracelets ...", true);
progressDialog.setCancelable(true);
progressDialog.show();
}
private void startActivity(Class<?> activityClass) {
Intent intent = new Intent(PatientListActivity.this, activityClass);
startActivity(intent);
}
}
| Removed animations due to a UI race condition.
| app/src/main/java/org/msf/records/ui/PatientListActivity.java | Removed animations due to a UI race condition. | <ide><path>pp/src/main/java/org/msf/records/ui/PatientListActivity.java
<ide> updateAvailableSnackbar = Snackbar.with(this)
<ide> .text("Application update available")
<ide> .actionLabel("Download")
<del> .swipeToDismiss(false)
<add> .swipeToDismiss(true)
<add> .animation(false)
<ide> .duration(Snackbar.SnackbarDuration.LENGTH_FOREVER);
<ide> updateDownloadedSnackbar = Snackbar.with(this)
<ide> .text("Application update downloaded")
<ide> .actionLabel("Install")
<del> .swipeToDismiss(false)
<add> .swipeToDismiss(true)
<add> .animation(false)
<ide> .duration(Snackbar.SnackbarDuration.LENGTH_FOREVER);
<ide>
<ide> // TODO: If exposing deep links into your app, handle intents here.
<ide> @Override
<ide> protected void onPause() {
<ide> App.getMainThreadBus().unregister(this);
<add>
<add> updateAvailableSnackbar.dismiss();
<add> updateDownloadedSnackbar.dismiss();
<ide>
<ide> super.onPause();
<ide> }
<ide> */
<ide> @Subscribe
<ide> public void onUpdateAvailableEvent(final UpdateAvailableEvent event) {
<del> updateDownloadedSnackbar.dismiss();
<ide> updateAvailableSnackbar
<ide> .actionListener(new ActionClickListener() {
<ide> |
|
Java | apache-2.0 | cfd45b30e8f5045e3e96a67762dac3ec9e14e67f | 0 | wschaeferB/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,esaunders/autopsy,rcordovano/autopsy,wschaeferB/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,wschaeferB/autopsy,rcordovano/autopsy,esaunders/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy | /*
* Autopsy
*
* Copyright 2019 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.filequery;
import com.google.common.eventbus.Subscribe;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.stream.Collectors;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDb;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbException;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.filequery.FileSearch.GroupingAttributeType;
import org.sleuthkit.autopsy.filequery.FileSearchData.FileType;
import org.sleuthkit.autopsy.filequery.FileSearchData.FileSize;
import org.sleuthkit.autopsy.filequery.FileSearchData.Frequency;
import org.sleuthkit.autopsy.filequery.FileSearchData.Score;
import org.sleuthkit.autopsy.filequery.FileSearchFiltering.ParentSearchTerm;
import org.sleuthkit.autopsy.filequery.FileSorter.SortingMethod;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.DataSource;
import org.sleuthkit.datamodel.TagName;
/**
* Dialog to allow the user to choose filtering and grouping options.
*/
final class FileSearchPanel extends javax.swing.JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private static final String[] DEFAULT_IGNORED_PATHS = {"Windows", "Program Files"};
private final static Logger logger = Logger.getLogger(FileSearchPanel.class.getName());
private FileType fileType = FileType.IMAGE;
private DefaultListModel<FileSearchFiltering.ParentSearchTerm> parentListModel;
private SearchWorker searchWorker = null;
/**
* Creates new form FileSearchDialog
*/
@NbBundle.Messages({"FileSearchPanel.dialogTitle.text=Test file search"})
FileSearchPanel() {
initComponents();
parentListModel = (DefaultListModel<FileSearchFiltering.ParentSearchTerm>) parentList.getModel();
for (String ignorePath : DEFAULT_IGNORED_PATHS) {
parentListModel.add(parentListModel.size(), new ParentSearchTerm(ignorePath, false, false));
}
}
/**
* Setup the data source filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void dataSourceFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
dataSourceCheckbox.setVisible(visible);
dataSourceScrollPane.setVisible(visible);
dataSourceList.setVisible(visible);
dataSourceCheckbox.setEnabled(enabled);
dataSourceCheckbox.setSelected(selected);
if (dataSourceCheckbox.isEnabled() && dataSourceCheckbox.isSelected()) {
dataSourceScrollPane.setEnabled(true);
dataSourceList.setEnabled(true);
if (indicesSelected != null) {
dataSourceList.setSelectedIndices(indicesSelected);
}
} else {
dataSourceScrollPane.setEnabled(false);
dataSourceList.setEnabled(false);
}
}
/**
* Setup the file size filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void sizeFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
sizeCheckbox.setVisible(visible);
sizeScrollPane.setVisible(visible);
sizeList.setVisible(visible);
sizeCheckbox.setEnabled(enabled);
sizeCheckbox.setSelected(selected);
if (sizeCheckbox.isEnabled() && sizeCheckbox.isSelected()) {
sizeScrollPane.setEnabled(true);
sizeList.setEnabled(true);
if (indicesSelected != null) {
sizeList.setSelectedIndices(indicesSelected);
}
} else {
sizeScrollPane.setEnabled(false);
sizeList.setEnabled(false);
}
}
/**
* Setup the central repository frequency filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void crFrequencyFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
crFrequencyCheckbox.setVisible(visible);
crFrequencyScrollPane.setVisible(visible);
crFrequencyList.setVisible(visible);
crFrequencyCheckbox.setEnabled(enabled);
crFrequencyCheckbox.setSelected(selected);
if (crFrequencyCheckbox.isEnabled() && crFrequencyCheckbox.isSelected()) {
crFrequencyScrollPane.setEnabled(true);
crFrequencyList.setEnabled(true);
if (indicesSelected != null) {
crFrequencyList.setSelectedIndices(indicesSelected);
}
} else {
crFrequencyScrollPane.setEnabled(false);
crFrequencyList.setEnabled(false);
}
}
/**
* Setup the objects filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void objectsFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
objectsCheckbox.setVisible(visible);
objectsScrollPane.setVisible(visible);
objectsList.setVisible(visible);
objectsCheckbox.setEnabled(enabled);
objectsCheckbox.setSelected(selected);
if (objectsCheckbox.isEnabled() && objectsCheckbox.isSelected()) {
objectsScrollPane.setEnabled(true);
objectsList.setEnabled(true);
if (indicesSelected != null) {
objectsList.setSelectedIndices(indicesSelected);
}
} else {
objectsScrollPane.setEnabled(false);
objectsList.setEnabled(false);
}
}
/**
* Setup the hash set filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void hashSetFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
hashSetCheckbox.setVisible(visible);
hashSetScrollPane.setVisible(visible);
hashSetList.setVisible(visible);
hashSetCheckbox.setEnabled(enabled);
hashSetCheckbox.setSelected(selected);
if (hashSetCheckbox.isEnabled() && hashSetCheckbox.isSelected()) {
hashSetScrollPane.setEnabled(true);
hashSetList.setEnabled(true);
if (indicesSelected != null) {
hashSetList.setSelectedIndices(indicesSelected);
}
} else {
hashSetScrollPane.setEnabled(false);
hashSetList.setEnabled(false);
}
}
/**
* Setup the interesting items filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void interestingItemsFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
interestingItemsCheckbox.setVisible(visible);
interestingItemsScrollPane.setVisible(visible);
interestingItemsList.setVisible(visible);
interestingItemsCheckbox.setEnabled(enabled);
interestingItemsCheckbox.setSelected(selected);
if (interestingItemsCheckbox.isEnabled() && interestingItemsCheckbox.isSelected()) {
interestingItemsScrollPane.setEnabled(true);
interestingItemsList.setEnabled(true);
if (indicesSelected != null) {
interestingItemsList.setSelectedIndices(indicesSelected);
}
} else {
interestingItemsScrollPane.setEnabled(false);
interestingItemsList.setEnabled(false);
}
}
/**
* Setup the score filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void scoreFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
scoreCheckbox.setVisible(visible);
scoreScrollPane.setVisible(visible);
scoreList.setVisible(visible);
scoreCheckbox.setEnabled(enabled);
scoreCheckbox.setSelected(selected);
if (scoreCheckbox.isEnabled() && scoreCheckbox.isSelected()) {
scoreScrollPane.setEnabled(true);
scoreList.setEnabled(true);
if (indicesSelected != null) {
scoreList.setSelectedIndices(indicesSelected);
}
} else {
scoreScrollPane.setEnabled(false);
scoreList.setEnabled(false);
}
}
/**
* Setup the parent path filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void parentFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
parentCheckbox.setVisible(visible);
parentScrollPane.setVisible(visible);
parentList.setVisible(visible);
parentCheckbox.setEnabled(enabled);
parentCheckbox.setSelected(selected);
if (parentCheckbox.isEnabled() && parentCheckbox.isSelected()) {
parentScrollPane.setEnabled(true);
includeRadioButton.setEnabled(true);
excludeRadioButton.setEnabled(true);
fullRadioButton.setEnabled(true);
substringRadioButton.setEnabled(true);
addButton.setEnabled(true);
deleteButton.setEnabled(!parentListModel.isEmpty());
parentList.setEnabled(true);
if (indicesSelected != null) {
parentList.setSelectedIndices(indicesSelected);
}
} else {
parentScrollPane.setEnabled(false);
parentList.setEnabled(false);
includeRadioButton.setEnabled(false);
excludeRadioButton.setEnabled(false);
fullRadioButton.setEnabled(false);
substringRadioButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
}
}
/**
* Setup the tags filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void tagsFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
tagsCheckbox.setVisible(visible);
tagsScrollPane.setVisible(visible);
tagsList.setVisible(visible);
tagsCheckbox.setEnabled(enabled);
tagsCheckbox.setSelected(selected);
if (tagsCheckbox.isEnabled() && tagsCheckbox.isSelected()) {
tagsScrollPane.setEnabled(true);
tagsList.setEnabled(true);
if (indicesSelected != null) {
tagsList.setSelectedIndices(indicesSelected);
}
} else {
tagsScrollPane.setEnabled(false);
tagsList.setEnabled(false);
}
}
/**
* Setup the keyword filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void keywordFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
keywordCheckbox.setVisible(visible);
keywordScrollPane.setVisible(visible);
keywordList.setVisible(visible);
keywordCheckbox.setEnabled(enabled);
keywordCheckbox.setSelected(selected);
if (keywordCheckbox.isEnabled() && keywordCheckbox.isSelected()) {
keywordScrollPane.setEnabled(true);
keywordList.setEnabled(true);
if (indicesSelected != null) {
keywordList.setSelectedIndices(indicesSelected);
}
} else {
keywordScrollPane.setEnabled(false);
keywordList.setEnabled(false);
}
}
/**
* Setup the exif filter settings.
*
* @param visible Boolean indicating if the filter should be visible.
* @param enabled Boolean indicating if the filter should be enabled.
* @param selected Boolean indicating if the filter should be selected.
*/
private void exifFilterSettings(boolean visible, boolean enabled, boolean selected) {
exifCheckbox.setVisible(visible);
exifCheckbox.setEnabled(enabled);
exifCheckbox.setSelected(selected);
}
/**
* Setup the known status filter settings.
*
* @param visible Boolean indicating if the filter should be visible.
* @param enabled Boolean indicating if the filter should be enabled.
* @param selected Boolean indicating if the filter should be selected.
*/
private void knownFilesFilterSettings(boolean visible, boolean enabled, boolean selected) {
knownFilesCheckbox.setVisible(visible);
knownFilesCheckbox.setEnabled(enabled);
knownFilesCheckbox.setSelected(selected);
}
/**
* Setup the notable filter settings.
*
* @param visible Boolean indicating if the filter should be visible.
* @param enabled Boolean indicating if the filter should be enabled.
* @param selected Boolean indicating if the filter should be selected.
*/
private void notableFilterSettings(boolean visible, boolean enabled, boolean selected) {
notableCheckbox.setVisible(visible);
notableCheckbox.setEnabled(enabled);
notableCheckbox.setSelected(selected);
}
/**
* Set the UI elements available to be the set of UI elements available when
* an Image search is being performed.
*
* @param enabled Boolean indicating if the filters present for images
* should be enabled.
* @param resetSelected Boolean indicating if selection of the filters
* present for images should be reset to their default
* status.
*/
private void imagesSelected(boolean enabled, boolean resetSelected) {
dataSourceFilterSettings(true, enabled, !resetSelected && dataSourceCheckbox.isSelected(), null);
int[] selectedSizeIndices = {1, 2, 3, 4, 5, 6};
sizeFilterSettings(true, enabled, resetSelected || sizeCheckbox.isSelected(), resetSelected == true ? selectedSizeIndices : null);
int[] selectedFrequencyIndices;
if (!EamDb.isEnabled()) {
selectedFrequencyIndices = new int[]{0};
} else {
selectedFrequencyIndices = new int[]{1, 2, 3, 4, 5, 6, 7};
}
crFrequencyFilterSettings(true, enabled, resetSelected || crFrequencyCheckbox.isSelected(), resetSelected == true ? selectedFrequencyIndices : null);
exifFilterSettings(true, enabled, !resetSelected && exifCheckbox.isSelected());
objectsFilterSettings(true, enabled, !resetSelected && objectsCheckbox.isSelected(), null);
hashSetFilterSettings(true, enabled, !resetSelected && hashSetCheckbox.isSelected(), null);
interestingItemsFilterSettings(true, enabled, !resetSelected && interestingItemsCheckbox.isSelected(), null);
parentFilterSettings(true, true, false, null);
scoreFilterSettings(false, false, false, null);
tagsFilterSettings(false, false, false, null);
keywordFilterSettings(false, false, false, null);
knownFilesFilterSettings(false, false, false);
notableFilterSettings(false, false, false);
}
/**
* Set the UI elements available to be the set of UI elements available when
* a Video search is being performed.
*
* @param enabled Boolean indicating if the filters present for videos
* should be enabled.
* @param resetSelected Boolean indicating if selection of the filters
* present for videos should be reset to their default
* status.
*/
private void videosSelected(boolean enabled, boolean resetSelected) {
dataSourceFilterSettings(true, enabled, !resetSelected && dataSourceCheckbox.isSelected(), null);
sizeFilterSettings(true, enabled, !resetSelected && sizeCheckbox.isSelected(), null);
int[] selectedFrequencyIndices;
if (!EamDb.isEnabled()) {
selectedFrequencyIndices = new int[]{0};
} else {
selectedFrequencyIndices = new int[]{1, 2, 3, 4, 5, 6, 7};
}
crFrequencyFilterSettings(true, enabled, resetSelected || crFrequencyCheckbox.isSelected(), resetSelected == true ? selectedFrequencyIndices : null);
exifFilterSettings(true, enabled, !resetSelected && exifCheckbox.isSelected());
objectsFilterSettings(true, enabled, !resetSelected && objectsCheckbox.isSelected(), null);
hashSetFilterSettings(true, enabled, !resetSelected && hashSetCheckbox.isSelected(), null);
interestingItemsFilterSettings(true, enabled, !resetSelected && interestingItemsCheckbox.isSelected(), null);
parentFilterSettings(true, true, false, null);
scoreFilterSettings(false, false, false, null);
tagsFilterSettings(false, false, false, null);
keywordFilterSettings(false, false, false, null);
knownFilesFilterSettings(false, false, false);
notableFilterSettings(false, false, false);
}
/**
* Set the type of search to perform.
*
* @param type The type of File to be found by the search.
*/
void setSelectedType(FileType type) {
if (type.equals(fileType)) {
//change the size filter if the type changed
setUpSizeFilter();
}
fileType = type;
if (fileType == FileType.IMAGE) {
imagesSelected(true, true);
} else if (fileType == FileType.VIDEO) {
videosSelected(true, true);
}
validateFields();
}
/**
* Reset the panel to its initial configuration.
*/
void resetPanel() {
searchButton.setEnabled(false);
// Set up the filters
setUpDataSourceFilter();
setUpFrequencyFilter();
setUpSizeFilter();
setUpKWFilter();
setUpParentPathFilter();
setUpHashFilter();
setUpInterestingItemsFilter();
setUpTagsFilter();
setUpObjectFilter();
setUpScoreFilter();
groupByCombobox.removeAllItems();
// Set up the grouping attributes
for (FileSearch.GroupingAttributeType type : FileSearch.GroupingAttributeType.getOptionsForGrouping()) {
if (type != GroupingAttributeType.FREQUENCY || EamDb.isEnabled()) {
groupByCombobox.addItem(type);
}
}
orderByCombobox.removeAllItems();
// Set up the file order list
for (FileSorter.SortingMethod method : FileSorter.SortingMethod.getOptionsForOrdering()) {
if (method != SortingMethod.BY_FREQUENCY || EamDb.isEnabled()) {
orderByCombobox.addItem(method);
}
}
setSelectedType(FileType.IMAGE);
validateFields();
}
/**
* Add listeners to the checkbox/list set if listeners have not already been
* added. Either can be null.
*
* @param checkBox
* @param list
*/
private void addListeners(JCheckBox checkBox, JList<?> list) {
if (checkBox != null && checkBox.getActionListeners().length == 0) {
checkBox.addActionListener(this);
}
if (list != null && list.getListSelectionListeners().length == 0) {
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent evt) {
if (!evt.getValueIsAdjusting()) {
validateFields();
}
}
});
}
}
/**
* Initialize the data source filter
*/
private void setUpDataSourceFilter() {
int count = 0;
try {
DefaultListModel<DataSourceItem> dsListModel = (DefaultListModel<DataSourceItem>) dataSourceList.getModel();
dsListModel.removeAllElements();
for (DataSource ds : Case.getCurrentCase().getSleuthkitCase().getDataSources()) {
dsListModel.add(count, new DataSourceItem(ds));
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading data sources", ex);
dataSourceCheckbox.setEnabled(false);
dataSourceList.setEnabled(false);
}
addListeners(dataSourceCheckbox, dataSourceList);
}
/**
* Initialize the frequency filter
*/
private void setUpFrequencyFilter() {
int count = 0;
DefaultListModel<FileSearchData.Frequency> frequencyListModel = (DefaultListModel<FileSearchData.Frequency>) crFrequencyList.getModel();
frequencyListModel.removeAllElements();
if (!EamDb.isEnabled()) {
for (FileSearchData.Frequency freq : FileSearchData.Frequency.getOptionsForFilteringWithoutCr()) {
frequencyListModel.add(count, freq);
}
} else {
for (FileSearchData.Frequency freq : FileSearchData.Frequency.getOptionsForFilteringWithCr()) {
frequencyListModel.add(count, freq);
}
}
addListeners(crFrequencyCheckbox, crFrequencyList);
}
/**
* Initialize the file size filter
*/
private void setUpSizeFilter() {
int count = 0;
DefaultListModel<FileSearchData.FileSize> sizeListModel = (DefaultListModel<FileSearchData.FileSize>) sizeList.getModel();
sizeListModel.removeAllElements();
if (null == fileType) {
for (FileSearchData.FileSize size : FileSearchData.FileSize.values()) {
sizeListModel.add(count, size);
}
} else {
List<FileSearchData.FileSize> sizes;
switch (fileType) {
case VIDEO:
sizes = FileSearchData.FileSize.getOptionsForVideos();
break;
case IMAGE:
sizes = FileSearchData.FileSize.getOptionsForImages();
break;
default:
sizes = new ArrayList<>();
break;
}
for (FileSearchData.FileSize size : sizes) {
sizeListModel.add(count, size);
}
}
addListeners(sizeCheckbox, sizeList);
}
/**
* Initialize the keyword list names filter
*/
private void setUpKWFilter() {
int count = 0;
try {
DefaultListModel<String> kwListModel = (DefaultListModel<String>) keywordList.getModel();
kwListModel.removeAllElements();
List<String> setNames = getSetNames(BlackboardArtifact.ARTIFACT_TYPE.TSK_KEYWORD_HIT,
BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME);
for (String name : setNames) {
kwListModel.add(count, name);
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading keyword list names", ex);
keywordCheckbox.setEnabled(false);
keywordList.setEnabled(false);
}
addListeners(keywordCheckbox, keywordList);
}
/**
* Initialize the hash filter.
*/
private void setUpHashFilter() {
int count = 0;
try {
DefaultListModel<String> hashListModel = (DefaultListModel<String>) hashSetList.getModel();
hashListModel.removeAllElements();
List<String> setNames = getSetNames(BlackboardArtifact.ARTIFACT_TYPE.TSK_HASHSET_HIT,
BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME);
for (String name : setNames) {
hashListModel.add(count, name);
count++;
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading hash set names", ex);
hashSetCheckbox.setEnabled(false);
hashSetList.setEnabled(false);
}
addListeners(hashSetCheckbox, hashSetList);
}
/**
* Initialize the interesting items filter.
*/
private void setUpInterestingItemsFilter() {
int count = 0;
try {
DefaultListModel<String> intListModel = (DefaultListModel<String>) interestingItemsList.getModel();
intListModel.removeAllElements();
List<String> setNames = getSetNames(BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT,
BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME);
for (String name : setNames) {
intListModel.add(count, name);
count++;
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading interesting file set names", ex);
interestingItemsCheckbox.setEnabled(false);
interestingItemsList.setEnabled(false);
}
addListeners(interestingItemsCheckbox, interestingItemsList);
}
/**
* Initialize the tags filter.
*/
private void setUpTagsFilter() {
int count = 0;
try {
DefaultListModel<TagName> tagsListModel = (DefaultListModel<TagName>) tagsList.getModel();
tagsListModel.removeAllElements();
List<TagName> tagNames = Case.getCurrentCase().getSleuthkitCase().getTagNamesInUse();
for (TagName name : tagNames) {
tagsListModel.add(count, name);
count++;
}
tagsList.setCellRenderer(new TagsListCellRenderer());
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading tag names", ex);
tagsCheckbox.setEnabled(false);
tagsList.setEnabled(false);
}
addListeners(tagsCheckbox, tagsList);
}
/**
* TagsListCellRenderer
*/
private class TagsListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
@Override
public java.awt.Component getListCellRendererComponent(
JList<?> list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Object newValue = value;
if (value instanceof TagName) {
newValue = ((TagName) value).getDisplayName();
}
super.getListCellRendererComponent(list, newValue, index, isSelected, cellHasFocus);
return this;
}
}
/**
* Initialize the object filter
*/
private void setUpObjectFilter() {
int count = 0;
try {
DefaultListModel<String> objListModel = (DefaultListModel<String>) objectsList.getModel();
objListModel.removeAllElements();
List<String> setNames = getSetNames(BlackboardArtifact.ARTIFACT_TYPE.TSK_OBJECT_DETECTED, BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DESCRIPTION);
for (String name : setNames) {
objListModel.add(count, name);
count++;
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading object detected set names", ex);
objectsCheckbox.setEnabled(false);
objectsList.setEnabled(false);
}
addListeners(objectsCheckbox, objectsList);
}
/**
* Initialize the score filter
*/
private void setUpScoreFilter() {
int count = 0;
DefaultListModel<Score> scoreListModel = (DefaultListModel<Score>) scoreList.getModel();
scoreListModel.removeAllElements();
for (Score score : Score.getOptionsForFiltering()) {
scoreListModel.add(count, score);
}
addListeners(scoreCheckbox, scoreList);
}
/**
* Get the names of the sets which exist in the case database for the
* specified artifact and attribute types.
*
* @param artifactType The artifact type to get the list of sets for.
* @param setNameAttribute The attribute type which contains the set names.
*
* @return A list of set names which exist in the case for the specified
* artifact and attribute types.
*
* @throws TskCoreException
*/
private List<String> getSetNames(BlackboardArtifact.ARTIFACT_TYPE artifactType, BlackboardAttribute.ATTRIBUTE_TYPE setNameAttribute) throws TskCoreException {
List<BlackboardArtifact> arts = Case.getCurrentCase().getSleuthkitCase().getBlackboardArtifacts(artifactType);
List<String> setNames = new ArrayList<>();
for (BlackboardArtifact art : arts) {
for (BlackboardAttribute attr : art.getAttributes()) {
if (attr.getAttributeType().getTypeID() == setNameAttribute.getTypeID()) {
String setName = attr.getValueString();
if (!setNames.contains(setName)) {
setNames.add(setName);
}
}
}
}
Collections.sort(setNames);
return setNames;
}
/**
* Initialize the parent path filter
*/
private void setUpParentPathFilter() {
fullRadioButton.setSelected(true);
includeRadioButton.setSelected(true);
parentListModel = (DefaultListModel<FileSearchFiltering.ParentSearchTerm>) parentList.getModel();
addListeners(parentCheckbox, parentList);
}
/**
* Get a list of all filters selected by the user.
*
* @return the list of filters
*/
List<FileSearchFiltering.FileFilter> getFilters() {
List<FileSearchFiltering.FileFilter> filters = new ArrayList<>();
filters.add(new FileSearchFiltering.FileTypeFilter(fileType));
if (parentCheckbox.isSelected()) {
// For the parent paths, everything in the box is used (not just the selected entries)
filters.add(new FileSearchFiltering.ParentFilter(getParentPaths()));
}
if (dataSourceCheckbox.isSelected()) {
List<DataSource> dataSources = dataSourceList.getSelectedValuesList().stream().map(t -> t.getDataSource()).collect(Collectors.toList());
filters.add(new FileSearchFiltering.DataSourceFilter(dataSources));
}
if (crFrequencyCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.FrequencyFilter(crFrequencyList.getSelectedValuesList()));
}
if (sizeCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.SizeFilter(sizeList.getSelectedValuesList()));
}
if (keywordCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.KeywordListFilter(keywordList.getSelectedValuesList()));
}
if (hashSetCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.HashSetFilter(hashSetList.getSelectedValuesList()));
}
if (interestingItemsCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.InterestingFileSetFilter(interestingItemsList.getSelectedValuesList()));
}
if (objectsCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.ObjectDetectionFilter(objectsList.getSelectedValuesList()));
}
if (tagsCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.TagsFilter(tagsList.getSelectedValuesList()));
}
if (exifCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.ExifFilter());
}
if (notableCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.NotableFilter());
}
if (knownFilesCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.KnownFilter());
}
if (scoreCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.ScoreFilter(scoreList.getSelectedValuesList()));
}
return filters;
}
/**
* Utility method to get the parent path objects out of the JList.
*
* @return The list of entered ParentSearchTerm objects
*/
private List<FileSearchFiltering.ParentSearchTerm> getParentPaths() {
List<FileSearchFiltering.ParentSearchTerm> results = new ArrayList<>();
for (int i = 0; i < parentListModel.getSize(); i++) {
results.add(parentListModel.get(i));
}
return results;
}
/**
* Get the attribute to group by
*
* @return the grouping attribute
*/
FileSearch.AttributeType getGroupingAttribute() {
FileSearch.GroupingAttributeType groupingAttrType = (FileSearch.GroupingAttributeType) groupByCombobox.getSelectedItem();
return groupingAttrType.getAttributeType();
}
/**
* Get the sorting method for groups.
*
* @return the selected sorting method
*/
FileGroup.GroupSortingAlgorithm getGroupSortingMethod() {
if (attributeRadioButton.isSelected()) {
return FileGroup.GroupSortingAlgorithm.BY_GROUP_KEY;
}
return FileGroup.GroupSortingAlgorithm.BY_GROUP_SIZE;
}
/**
* Get the sorting method for files.
*
* @return the selected sorting method
*/
FileSorter.SortingMethod getFileSortingMethod() {
return (FileSorter.SortingMethod) orderByCombobox.getSelectedItem();
}
@Override
public void actionPerformed(ActionEvent e) {
validateFields();
}
/**
* Utility class to allow us to display the data source ID along with the
* name
*/
private class DataSourceItem {
private final DataSource ds;
DataSourceItem(DataSource ds) {
this.ds = ds;
}
DataSource getDataSource() {
return ds;
}
@Override
public String toString() {
return ds.getName() + " (ID: " + ds.getId() + ")";
}
}
/**
* Validate the form. If we use any of this in the final dialog we should
* use bundle messages.
*/
private void validateFields() {
// There will be a file type selected.
if (fileType == null) {
setInvalid("At least one file type must be selected");
return;
}
// For most enabled filters, there should be something selected
if (dataSourceCheckbox.isSelected() && dataSourceList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one data source must be selected");
return;
}
if (crFrequencyCheckbox.isSelected() && crFrequencyList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one CR frequency must be selected");
return;
}
if (sizeCheckbox.isSelected() && sizeList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one size must be selected");
return;
}
if (keywordCheckbox.isSelected() && keywordList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one keyword list name must be selected");
return;
}
// Parent uses everything in the box
if (parentCheckbox.isSelected() && getParentPaths().isEmpty()) {
setInvalid("At least one parent path must be entered");
return;
}
if (hashSetCheckbox.isSelected() && hashSetList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one hash set name must be selected");
return;
}
if (interestingItemsCheckbox.isSelected() && interestingItemsList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one interesting file set name must be selected");
return;
}
if (objectsCheckbox.isSelected() && objectsList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one object type name must be selected");
return;
}
if (tagsCheckbox.isSelected() && tagsList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one tag name must be selected");
return;
}
if (scoreCheckbox.isSelected() && scoreList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one score must be selected");
return;
}
setValid();
}
/**
* The settings are valid so enable the Search button
*/
private void setValid() {
errorLabel.setText("");
searchButton.setEnabled(true);
}
/**
* The settings are not valid so disable the search button and display the
* given error message.
*
* @param error
*/
private void setInvalid(String error) {
errorLabel.setText(error);
searchButton.setEnabled(false);
}
/**
* 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() {
java.awt.GridBagConstraints gridBagConstraints;
javax.swing.ButtonGroup parentPathButtonGroup = new javax.swing.ButtonGroup();
orderGroupsByButtonGroup = new javax.swing.ButtonGroup();
javax.swing.ButtonGroup parentIncludeButtonGroup = new javax.swing.ButtonGroup();
filtersScrollPane = new javax.swing.JScrollPane();
filtersPanel = new javax.swing.JPanel();
sizeCheckbox = new javax.swing.JCheckBox();
dataSourceCheckbox = new javax.swing.JCheckBox();
crFrequencyCheckbox = new javax.swing.JCheckBox();
keywordCheckbox = new javax.swing.JCheckBox();
parentCheckbox = new javax.swing.JCheckBox();
dataSourceScrollPane = new javax.swing.JScrollPane();
dataSourceList = new javax.swing.JList<>();
fullRadioButton = new javax.swing.JRadioButton();
substringRadioButton = new javax.swing.JRadioButton();
parentTextField = new javax.swing.JTextField();
addButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
sizeScrollPane = new javax.swing.JScrollPane();
sizeList = new javax.swing.JList<>();
crFrequencyScrollPane = new javax.swing.JScrollPane();
crFrequencyList = new javax.swing.JList<>();
keywordScrollPane = new javax.swing.JScrollPane();
keywordList = new javax.swing.JList<>();
parentLabel = new javax.swing.JLabel();
parentScrollPane = new javax.swing.JScrollPane();
parentList = new javax.swing.JList<>();
hashSetCheckbox = new javax.swing.JCheckBox();
hashSetScrollPane = new javax.swing.JScrollPane();
hashSetList = new javax.swing.JList<>();
objectsCheckbox = new javax.swing.JCheckBox();
tagsCheckbox = new javax.swing.JCheckBox();
interestingItemsCheckbox = new javax.swing.JCheckBox();
scoreCheckbox = new javax.swing.JCheckBox();
exifCheckbox = new javax.swing.JCheckBox();
notableCheckbox = new javax.swing.JCheckBox();
objectsScrollPane = new javax.swing.JScrollPane();
objectsList = new javax.swing.JList<>();
tagsScrollPane = new javax.swing.JScrollPane();
tagsList = new javax.swing.JList<>();
interestingItemsScrollPane = new javax.swing.JScrollPane();
interestingItemsList = new javax.swing.JList<>();
scoreScrollPane = new javax.swing.JScrollPane();
scoreList = new javax.swing.JList<>();
includeRadioButton = new javax.swing.JRadioButton();
excludeRadioButton = new javax.swing.JRadioButton();
knownFilesCheckbox = new javax.swing.JCheckBox();
searchButton = new javax.swing.JButton();
sortingPanel = new javax.swing.JPanel();
groupByCombobox = new javax.swing.JComboBox<>();
orderByCombobox = new javax.swing.JComboBox<>();
orderGroupsByLabel = new javax.swing.JLabel();
attributeRadioButton = new javax.swing.JRadioButton();
groupSizeRadioButton = new javax.swing.JRadioButton();
orderByLabel = new javax.swing.JLabel();
groupByLabel = new javax.swing.JLabel();
errorLabel = new javax.swing.JLabel();
cancelButton = new javax.swing.JButton();
setMinimumSize(new java.awt.Dimension(424, 0));
setPreferredSize(new java.awt.Dimension(424, 533));
filtersScrollPane.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.filtersScrollPane.border.title"))); // NOI18N
filtersScrollPane.setPreferredSize(new java.awt.Dimension(416, 338));
filtersPanel.setLayout(new java.awt.GridBagLayout());
org.openide.awt.Mnemonics.setLocalizedText(sizeCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.sizeCheckbox.text")); // NOI18N
sizeCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sizeCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 4, 0);
filtersPanel.add(sizeCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(dataSourceCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.dataSourceCheckbox.text")); // NOI18N
dataSourceCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dataSourceCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(dataSourceCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(crFrequencyCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.crFrequencyCheckbox.text")); // NOI18N
crFrequencyCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
crFrequencyCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(crFrequencyCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(keywordCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.keywordCheckbox.text")); // NOI18N
keywordCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
keywordCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 12;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(keywordCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(parentCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.parentCheckbox.text")); // NOI18N
parentCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
parentCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(parentCheckbox, gridBagConstraints);
dataSourceList.setModel(new DefaultListModel<DataSourceItem>());
dataSourceList.setEnabled(false);
dataSourceList.setVisibleRowCount(5);
dataSourceScrollPane.setViewportView(dataSourceList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(dataSourceScrollPane, gridBagConstraints);
parentPathButtonGroup.add(fullRadioButton);
fullRadioButton.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(fullRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.fullRadioButton.text")); // NOI18N
fullRadioButton.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
filtersPanel.add(fullRadioButton, gridBagConstraints);
parentPathButtonGroup.add(substringRadioButton);
org.openide.awt.Mnemonics.setLocalizedText(substringRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.substringRadioButton.text")); // NOI18N
substringRadioButton.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
filtersPanel.add(substringRadioButton, gridBagConstraints);
parentTextField.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 11;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 6, 0);
filtersPanel.add(parentTextField, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(addButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.addButton.text")); // NOI18N
addButton.setEnabled(false);
addButton.setMaximumSize(new java.awt.Dimension(70, 23));
addButton.setMinimumSize(new java.awt.Dimension(70, 23));
addButton.setPreferredSize(new java.awt.Dimension(70, 23));
addButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 11;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 6);
filtersPanel.add(addButton, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(deleteButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.deleteButton.text")); // NOI18N
deleteButton.setEnabled(false);
deleteButton.setMaximumSize(new java.awt.Dimension(70, 23));
deleteButton.setMinimumSize(new java.awt.Dimension(70, 23));
deleteButton.setPreferredSize(new java.awt.Dimension(70, 23));
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 4, 6);
filtersPanel.add(deleteButton, gridBagConstraints);
sizeList.setModel(new DefaultListModel<FileSize>());
sizeList.setEnabled(false);
sizeList.setVisibleRowCount(5);
sizeScrollPane.setViewportView(sizeList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(6, 4, 4, 6);
filtersPanel.add(sizeScrollPane, gridBagConstraints);
crFrequencyList.setModel(new DefaultListModel<Frequency>());
crFrequencyList.setEnabled(false);
crFrequencyList.setVisibleRowCount(3);
crFrequencyScrollPane.setViewportView(crFrequencyList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(crFrequencyScrollPane, gridBagConstraints);
keywordList.setModel(new DefaultListModel<String>());
keywordList.setEnabled(false);
keywordList.setVisibleRowCount(3);
keywordScrollPane.setViewportView(keywordList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 12;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(keywordScrollPane, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(parentLabel, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.parentLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(parentLabel, gridBagConstraints);
parentList.setModel(new DefaultListModel<ParentSearchTerm>());
parentList.setEnabled(false);
parentList.setVisibleRowCount(3);
parentList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
parentListValueChanged(evt);
}
});
parentScrollPane.setViewportView(parentList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(parentScrollPane, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(hashSetCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.hashSetCheckbox.text")); // NOI18N
hashSetCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
hashSetCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(hashSetCheckbox, gridBagConstraints);
hashSetList.setModel(new DefaultListModel<String>());
hashSetList.setEnabled(false);
hashSetList.setVisibleRowCount(3);
hashSetScrollPane.setViewportView(hashSetList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(hashSetScrollPane, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(objectsCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.objectsCheckbox.text")); // NOI18N
objectsCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
objectsCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(objectsCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(tagsCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.tagsCheckbox.text")); // NOI18N
tagsCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tagsCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 13;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(tagsCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(interestingItemsCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.interestingItemsCheckbox.text")); // NOI18N
interestingItemsCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
interestingItemsCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(interestingItemsCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(scoreCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.scoreCheckbox.text")); // NOI18N
scoreCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
scoreCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 14;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(scoreCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(exifCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.exifCheckbox.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 6);
filtersPanel.add(exifCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(notableCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.notableCheckbox.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 15;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 6);
filtersPanel.add(notableCheckbox, gridBagConstraints);
objectsList.setModel(new DefaultListModel<String>());
objectsList.setEnabled(false);
objectsList.setVisibleRowCount(3);
objectsScrollPane.setViewportView(objectsList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(objectsScrollPane, gridBagConstraints);
tagsList.setModel(new DefaultListModel<TagName>());
tagsList.setEnabled(false);
tagsList.setVisibleRowCount(3);
tagsScrollPane.setViewportView(tagsList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 13;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(tagsScrollPane, gridBagConstraints);
interestingItemsList.setModel(new DefaultListModel<String>());
interestingItemsList.setEnabled(false);
interestingItemsList.setVisibleRowCount(3);
interestingItemsScrollPane.setViewportView(interestingItemsList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(interestingItemsScrollPane, gridBagConstraints);
scoreList.setModel(new DefaultListModel<Score>());
scoreList.setEnabled(false);
scoreList.setVisibleRowCount(3);
scoreScrollPane.setViewportView(scoreList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 14;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(scoreScrollPane, gridBagConstraints);
parentIncludeButtonGroup.add(includeRadioButton);
includeRadioButton.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(includeRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.includeRadioButton.text")); // NOI18N
includeRadioButton.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
filtersPanel.add(includeRadioButton, gridBagConstraints);
parentIncludeButtonGroup.add(excludeRadioButton);
org.openide.awt.Mnemonics.setLocalizedText(excludeRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.excludeRadioButton.text")); // NOI18N
excludeRadioButton.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
filtersPanel.add(excludeRadioButton, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(knownFilesCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.knownFilesCheckbox.text")); // NOI18N
knownFilesCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.knownFilesCheckbox.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 16;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 6);
filtersPanel.add(knownFilesCheckbox, gridBagConstraints);
filtersScrollPane.setViewportView(filtersPanel);
org.openide.awt.Mnemonics.setLocalizedText(searchButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.searchButton.text")); // NOI18N
searchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchButtonActionPerformed(evt);
}
});
sortingPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.sortingPanel.border.title"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(orderGroupsByLabel, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.orderGroupsByLabel.text")); // NOI18N
orderGroupsByButtonGroup.add(attributeRadioButton);
attributeRadioButton.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(attributeRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.attributeRadioButton.text")); // NOI18N
orderGroupsByButtonGroup.add(groupSizeRadioButton);
org.openide.awt.Mnemonics.setLocalizedText(groupSizeRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.groupSizeRadioButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(orderByLabel, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.orderByLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(groupByLabel, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.groupByLabel.text")); // NOI18N
javax.swing.GroupLayout sortingPanelLayout = new javax.swing.GroupLayout(sortingPanel);
sortingPanel.setLayout(sortingPanelLayout);
sortingPanelLayout.setHorizontalGroup(
sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(attributeRadioButton))
.addGroup(sortingPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(orderByLabel))
.addGroup(sortingPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(groupByLabel)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(groupByCombobox, 0, 280, Short.MAX_VALUE)
.addComponent(orderByCombobox, 0, 1, Short.MAX_VALUE)))
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(orderGroupsByLabel))
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(groupSizeRadioButton)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
sortingPanelLayout.setVerticalGroup(
sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(orderByCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(orderByLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(groupByCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(groupByLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(orderGroupsByLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(attributeRadioButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(groupSizeRadioButton)
.addContainerGap())
);
errorLabel.setForeground(new java.awt.Color(255, 0, 0));
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.cancelButton.text")); // NOI18N
cancelButton.setEnabled(false);
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(searchButton))
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(filtersScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(sortingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(6, 6, 6))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, searchButton});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(filtersScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sortingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(errorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(searchButton)))
.addGap(6, 6, 6))
);
}// </editor-fold>//GEN-END:initComponents
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
// Get the selected filters
List<FileSearchFiltering.FileFilter> filters = getFilters();
enableSearch(false);
DiscoveryEvents.getDiscoveryEventBus().post(new DiscoveryEvents.SearchStartedEvent(fileType));
// Get the grouping attribute and group sorting method
FileSearch.AttributeType groupingAttr = getGroupingAttribute();
FileGroup.GroupSortingAlgorithm groupSortAlgorithm = getGroupSortingMethod();
// Get the file sorting method
FileSorter.SortingMethod fileSort = getFileSortingMethod();
EamDb centralRepoDb = null;
if (EamDb.isEnabled()) {
try {
centralRepoDb = EamDb.getInstance();
} catch (EamDbException ex) {
centralRepoDb = null;
logger.log(Level.SEVERE, "Error loading central repository database, no central repository options will be available for File Discovery", ex);
}
}
searchWorker = new SearchWorker(centralRepoDb, filters, groupingAttr, groupSortAlgorithm, fileSort);
searchWorker.execute();
}//GEN-LAST:event_searchButtonActionPerformed
/**
* Set the enabled status of the search controls.
*
* @param enabled Boolean which indicates if the search should be enabled.
* True if the search button and controls should be enabled,
* false otherwise.
*/
private void enableSearch(boolean enabled) {
if (enabled) {
DiscoveryTopComponent.getTopComponent().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
} else {
DiscoveryTopComponent.getTopComponent().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
if (fileType == FileType.IMAGE) {
imagesSelected(enabled, false);
} else if (fileType == FileType.VIDEO) {
videosSelected(enabled, false);
}
searchButton.setEnabled(enabled);
cancelButton.setEnabled(!enabled);
orderByCombobox.setEnabled(enabled);
groupByCombobox.setEnabled(enabled);
attributeRadioButton.setEnabled(enabled);
groupSizeRadioButton.setEnabled(enabled);
}
/**
* Update the user interface when a search has been cancelled.
*
* @param searchCancelledEvent The SearchCancelledEvent which was received.
*/
@Subscribe
void handleSearchCancelledEvent(DiscoveryEvents.SearchCancelledEvent searchCancelledEvent) {
SwingUtilities.invokeLater(() -> {
enableSearch(true);
});
}
/**
* Update the user interface when a search has been successfully completed.
*
* @param searchCompleteEvent The SearchCompleteEvent which was received.
*/
@Subscribe
void handleSearchCompleteEvent(DiscoveryEvents.SearchCompleteEvent searchCompleteEvent) {
SwingUtilities.invokeLater(() -> {
enableSearch(true);
});
}
private void parentCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_parentCheckboxActionPerformed
parentFilterSettings(true, true, parentCheckbox.isSelected(), null);
}//GEN-LAST:event_parentCheckboxActionPerformed
private void keywordCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_keywordCheckboxActionPerformed
keywordList.setEnabled(keywordCheckbox.isSelected());
}//GEN-LAST:event_keywordCheckboxActionPerformed
private void sizeCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sizeCheckboxActionPerformed
sizeList.setEnabled(sizeCheckbox.isSelected());
}//GEN-LAST:event_sizeCheckboxActionPerformed
private void crFrequencyCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_crFrequencyCheckboxActionPerformed
crFrequencyList.setEnabled(crFrequencyCheckbox.isSelected());
}//GEN-LAST:event_crFrequencyCheckboxActionPerformed
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
if (!parentTextField.getText().isEmpty()) {
ParentSearchTerm searchTerm;
searchTerm = new ParentSearchTerm(parentTextField.getText(), fullRadioButton.isSelected(), includeRadioButton.isSelected());
parentListModel.add(parentListModel.size(), searchTerm);
validateFields();
parentTextField.setText("");
}
}//GEN-LAST:event_addButtonActionPerformed
/**
* Cancel the current search.
*/
void cancelSearch() {
if (searchWorker != null) {
searchWorker.cancel(true);
}
}
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
int index = parentList.getSelectedIndex();
if (index >= 0) {
parentListModel.remove(index);
}
validateFields();
}//GEN-LAST:event_deleteButtonActionPerformed
private void parentListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_parentListValueChanged
if (parentList.getSelectedValuesList().isEmpty()) {
deleteButton.setEnabled(false);
} else {
deleteButton.setEnabled(true);
}
}//GEN-LAST:event_parentListValueChanged
private void dataSourceCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataSourceCheckboxActionPerformed
dataSourceList.setEnabled(dataSourceCheckbox.isSelected());
}//GEN-LAST:event_dataSourceCheckboxActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
cancelSearch();
}//GEN-LAST:event_cancelButtonActionPerformed
private void hashSetCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hashSetCheckboxActionPerformed
hashSetList.setEnabled(hashSetCheckbox.isSelected());
}//GEN-LAST:event_hashSetCheckboxActionPerformed
private void objectsCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_objectsCheckboxActionPerformed
objectsList.setEnabled(objectsCheckbox.isSelected());
}//GEN-LAST:event_objectsCheckboxActionPerformed
private void tagsCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tagsCheckboxActionPerformed
tagsList.setEnabled(tagsCheckbox.isSelected());
}//GEN-LAST:event_tagsCheckboxActionPerformed
private void interestingItemsCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_interestingItemsCheckboxActionPerformed
interestingItemsList.setEnabled(interestingItemsCheckbox.isSelected());
}//GEN-LAST:event_interestingItemsCheckboxActionPerformed
private void scoreCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scoreCheckboxActionPerformed
scoreList.setEnabled(scoreCheckbox.isSelected());
}//GEN-LAST:event_scoreCheckboxActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addButton;
private javax.swing.JRadioButton attributeRadioButton;
private javax.swing.JButton cancelButton;
private javax.swing.JCheckBox crFrequencyCheckbox;
private javax.swing.JList<Frequency> crFrequencyList;
private javax.swing.JScrollPane crFrequencyScrollPane;
private javax.swing.JCheckBox dataSourceCheckbox;
private javax.swing.JList<DataSourceItem> dataSourceList;
private javax.swing.JScrollPane dataSourceScrollPane;
private javax.swing.JButton deleteButton;
private javax.swing.JLabel errorLabel;
private javax.swing.JRadioButton excludeRadioButton;
private javax.swing.JCheckBox exifCheckbox;
private javax.swing.JPanel filtersPanel;
private javax.swing.JScrollPane filtersScrollPane;
private javax.swing.JRadioButton fullRadioButton;
private javax.swing.JComboBox<GroupingAttributeType> groupByCombobox;
private javax.swing.JLabel groupByLabel;
private javax.swing.JRadioButton groupSizeRadioButton;
private javax.swing.JCheckBox hashSetCheckbox;
private javax.swing.JList<String> hashSetList;
private javax.swing.JScrollPane hashSetScrollPane;
private javax.swing.JRadioButton includeRadioButton;
private javax.swing.JCheckBox interestingItemsCheckbox;
private javax.swing.JList<String> interestingItemsList;
private javax.swing.JScrollPane interestingItemsScrollPane;
private javax.swing.JCheckBox keywordCheckbox;
private javax.swing.JList<String> keywordList;
private javax.swing.JScrollPane keywordScrollPane;
private javax.swing.JCheckBox knownFilesCheckbox;
private javax.swing.JCheckBox notableCheckbox;
private javax.swing.JCheckBox objectsCheckbox;
private javax.swing.JList<String> objectsList;
private javax.swing.JScrollPane objectsScrollPane;
private javax.swing.JComboBox<SortingMethod> orderByCombobox;
private javax.swing.JLabel orderByLabel;
private javax.swing.ButtonGroup orderGroupsByButtonGroup;
private javax.swing.JLabel orderGroupsByLabel;
private javax.swing.JCheckBox parentCheckbox;
private javax.swing.JLabel parentLabel;
private javax.swing.JList<ParentSearchTerm> parentList;
private javax.swing.JScrollPane parentScrollPane;
private javax.swing.JTextField parentTextField;
private javax.swing.JCheckBox scoreCheckbox;
private javax.swing.JList<Score> scoreList;
private javax.swing.JScrollPane scoreScrollPane;
private javax.swing.JButton searchButton;
private javax.swing.JCheckBox sizeCheckbox;
private javax.swing.JList<FileSize> sizeList;
private javax.swing.JScrollPane sizeScrollPane;
private javax.swing.JPanel sortingPanel;
private javax.swing.JRadioButton substringRadioButton;
private javax.swing.JCheckBox tagsCheckbox;
private javax.swing.JList<TagName> tagsList;
private javax.swing.JScrollPane tagsScrollPane;
// End of variables declaration//GEN-END:variables
}
| Core/src/org/sleuthkit/autopsy/filequery/FileSearchPanel.java | /*
* Autopsy
*
* Copyright 2019 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.filequery;
import com.google.common.eventbus.Subscribe;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.stream.Collectors;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDb;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbException;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.filequery.FileSearch.GroupingAttributeType;
import org.sleuthkit.autopsy.filequery.FileSearchData.FileType;
import org.sleuthkit.autopsy.filequery.FileSearchData.FileSize;
import org.sleuthkit.autopsy.filequery.FileSearchData.Frequency;
import org.sleuthkit.autopsy.filequery.FileSearchData.Score;
import org.sleuthkit.autopsy.filequery.FileSearchFiltering.ParentSearchTerm;
import org.sleuthkit.autopsy.filequery.FileSorter.SortingMethod;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.DataSource;
import org.sleuthkit.datamodel.TagName;
/**
* Dialog to allow the user to choose filtering and grouping options.
*/
final class FileSearchPanel extends javax.swing.JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private static final String[] DEFAULT_IGNORED_PATHS = {"Windows", "Program Files"};
private final static Logger logger = Logger.getLogger(FileSearchPanel.class.getName());
private FileType fileType = FileType.IMAGE;
private DefaultListModel<FileSearchFiltering.ParentSearchTerm> parentListModel;
private SearchWorker searchWorker = null;
/**
* Creates new form FileSearchDialog
*/
@NbBundle.Messages({"FileSearchPanel.dialogTitle.text=Test file search"})
FileSearchPanel() {
initComponents();
parentListModel = (DefaultListModel<FileSearchFiltering.ParentSearchTerm>) parentList.getModel();
for (String ignorePath : DEFAULT_IGNORED_PATHS) {
parentListModel.add(parentListModel.size(), new ParentSearchTerm(ignorePath, false, false));
}
}
/**
* Setup the data source filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void dataSourceFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
dataSourceCheckbox.setVisible(visible);
dataSourceScrollPane.setVisible(visible);
dataSourceList.setVisible(visible);
dataSourceCheckbox.setEnabled(enabled);
dataSourceCheckbox.setSelected(selected);
if (dataSourceCheckbox.isEnabled() && dataSourceCheckbox.isSelected()) {
dataSourceScrollPane.setEnabled(true);
dataSourceList.setEnabled(true);
if (indicesSelected != null) {
dataSourceList.setSelectedIndices(indicesSelected);
}
} else {
dataSourceScrollPane.setEnabled(false);
dataSourceList.setEnabled(false);
}
}
/**
* Setup the file size filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void sizeFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
sizeCheckbox.setVisible(visible);
sizeScrollPane.setVisible(visible);
sizeList.setVisible(visible);
sizeCheckbox.setEnabled(enabled);
sizeCheckbox.setSelected(selected);
if (sizeCheckbox.isEnabled() && sizeCheckbox.isSelected()) {
sizeScrollPane.setEnabled(true);
sizeList.setEnabled(true);
if (indicesSelected != null) {
sizeList.setSelectedIndices(indicesSelected);
}
} else {
sizeScrollPane.setEnabled(false);
sizeList.setEnabled(false);
}
}
/**
* Setup the central repository frequency filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void crFrequencyFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
crFrequencyCheckbox.setVisible(visible);
crFrequencyScrollPane.setVisible(visible);
crFrequencyList.setVisible(visible);
crFrequencyCheckbox.setEnabled(enabled);
crFrequencyCheckbox.setSelected(selected);
if (crFrequencyCheckbox.isEnabled() && crFrequencyCheckbox.isSelected()) {
crFrequencyScrollPane.setEnabled(true);
crFrequencyList.setEnabled(true);
if (indicesSelected != null) {
crFrequencyList.setSelectedIndices(indicesSelected);
}
} else {
crFrequencyScrollPane.setEnabled(false);
crFrequencyList.setEnabled(false);
}
}
/**
* Setup the objects filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void objectsFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
objectsCheckbox.setVisible(visible);
objectsScrollPane.setVisible(visible);
objectsList.setVisible(visible);
objectsCheckbox.setEnabled(enabled);
objectsCheckbox.setSelected(selected);
if (objectsCheckbox.isEnabled() && objectsCheckbox.isSelected()) {
objectsScrollPane.setEnabled(true);
objectsList.setEnabled(true);
if (indicesSelected != null) {
objectsList.setSelectedIndices(indicesSelected);
}
} else {
objectsScrollPane.setEnabled(false);
objectsList.setEnabled(false);
}
}
/**
* Setup the hash set filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void hashSetFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
hashSetCheckbox.setVisible(visible);
hashSetScrollPane.setVisible(visible);
hashSetList.setVisible(visible);
hashSetCheckbox.setEnabled(enabled);
hashSetCheckbox.setSelected(selected);
if (hashSetCheckbox.isEnabled() && hashSetCheckbox.isSelected()) {
hashSetScrollPane.setEnabled(true);
hashSetList.setEnabled(true);
if (indicesSelected != null) {
hashSetList.setSelectedIndices(indicesSelected);
}
} else {
hashSetScrollPane.setEnabled(false);
hashSetList.setEnabled(false);
}
}
/**
* Setup the interesting items filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void interestingItemsFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
interestingItemsCheckbox.setVisible(visible);
interestingItemsScrollPane.setVisible(visible);
interestingItemsList.setVisible(visible);
interestingItemsCheckbox.setEnabled(enabled);
interestingItemsCheckbox.setSelected(selected);
if (interestingItemsCheckbox.isEnabled() && interestingItemsCheckbox.isSelected()) {
interestingItemsScrollPane.setEnabled(true);
interestingItemsList.setEnabled(true);
if (indicesSelected != null) {
interestingItemsList.setSelectedIndices(indicesSelected);
}
} else {
interestingItemsScrollPane.setEnabled(false);
interestingItemsList.setEnabled(false);
}
}
/**
* Setup the score filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void scoreFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
scoreCheckbox.setVisible(visible);
scoreScrollPane.setVisible(visible);
scoreList.setVisible(visible);
scoreCheckbox.setEnabled(enabled);
scoreCheckbox.setSelected(selected);
if (scoreCheckbox.isEnabled() && scoreCheckbox.isSelected()) {
scoreScrollPane.setEnabled(true);
scoreList.setEnabled(true);
if (indicesSelected != null) {
scoreList.setSelectedIndices(indicesSelected);
}
} else {
scoreScrollPane.setEnabled(false);
scoreList.setEnabled(false);
}
}
/**
* Setup the parent path filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void parentFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
parentCheckbox.setVisible(visible);
parentScrollPane.setVisible(visible);
parentList.setVisible(visible);
parentCheckbox.setEnabled(enabled);
parentCheckbox.setSelected(selected);
if (parentCheckbox.isEnabled() && parentCheckbox.isSelected()) {
parentScrollPane.setEnabled(true);
includeRadioButton.setEnabled(true);
excludeRadioButton.setEnabled(true);
fullRadioButton.setEnabled(true);
substringRadioButton.setEnabled(true);
addButton.setEnabled(true);
deleteButton.setEnabled(!parentListModel.isEmpty());
parentList.setEnabled(true);
if (indicesSelected != null) {
parentList.setSelectedIndices(indicesSelected);
}
} else {
parentScrollPane.setEnabled(false);
parentList.setEnabled(false);
includeRadioButton.setEnabled(false);
excludeRadioButton.setEnabled(false);
fullRadioButton.setEnabled(false);
substringRadioButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
}
}
/**
* Setup the tags filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void tagsFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
tagsCheckbox.setVisible(visible);
tagsScrollPane.setVisible(visible);
tagsList.setVisible(visible);
tagsCheckbox.setEnabled(enabled);
tagsCheckbox.setSelected(selected);
if (tagsCheckbox.isEnabled() && tagsCheckbox.isSelected()) {
tagsScrollPane.setEnabled(true);
tagsList.setEnabled(true);
if (indicesSelected != null) {
tagsList.setSelectedIndices(indicesSelected);
}
} else {
tagsScrollPane.setEnabled(false);
tagsList.setEnabled(false);
}
}
/**
* Setup the keyword filter settings.
*
* @param visible Boolean indicating if the filter should be
* visible.
* @param enabled Boolean indicating if the filter should be
* enabled.
* @param selected Boolean indicating if the filter should be
* selected.
* @param indicesSelected Array of integers indicating which list items are
* selected, null to indicate leaving selected items
* unchanged.
*/
private void keywordFilterSettings(boolean visible, boolean enabled, boolean selected, int[] indicesSelected) {
keywordCheckbox.setVisible(visible);
keywordScrollPane.setVisible(visible);
keywordList.setVisible(visible);
keywordCheckbox.setEnabled(enabled);
keywordCheckbox.setSelected(selected);
if (keywordCheckbox.isEnabled() && keywordCheckbox.isSelected()) {
keywordScrollPane.setEnabled(true);
keywordList.setEnabled(true);
if (indicesSelected != null) {
keywordList.setSelectedIndices(indicesSelected);
}
} else {
keywordScrollPane.setEnabled(false);
keywordList.setEnabled(false);
}
}
/**
* Setup the exif filter settings.
*
* @param visible Boolean indicating if the filter should be visible.
* @param enabled Boolean indicating if the filter should be enabled.
* @param selected Boolean indicating if the filter should be selected.
*/
private void exifFilterSettings(boolean visible, boolean enabled, boolean selected) {
exifCheckbox.setVisible(visible);
exifCheckbox.setEnabled(enabled);
exifCheckbox.setSelected(selected);
}
/**
* Setup the known status filter settings.
*
* @param visible Boolean indicating if the filter should be visible.
* @param enabled Boolean indicating if the filter should be enabled.
* @param selected Boolean indicating if the filter should be selected.
*/
private void knownFilesFilterSettings(boolean visible, boolean enabled, boolean selected) {
knownFilesCheckbox.setVisible(visible);
knownFilesCheckbox.setEnabled(enabled);
knownFilesCheckbox.setSelected(selected);
}
/**
* Setup the notable filter settings.
*
* @param visible Boolean indicating if the filter should be visible.
* @param enabled Boolean indicating if the filter should be enabled.
* @param selected Boolean indicating if the filter should be selected.
*/
private void notableFilterSettings(boolean visible, boolean enabled, boolean selected) {
notableCheckbox.setVisible(visible);
notableCheckbox.setEnabled(enabled);
notableCheckbox.setSelected(selected);
}
/**
* Set the UI elements available to be the set of UI elements available when
* an Image search is being performed.
*
* @param enabled Boolean indicating if the filters present for images
* should be enabled.
* @param resetSelected Boolean indicating if selection of the filters
* present for images should be reset to their default
* status.
*/
private void imagesSelected(boolean enabled, boolean resetSelected) {
dataSourceFilterSettings(true, enabled, !resetSelected && dataSourceCheckbox.isSelected(), null);
int[] selectedSizeIndices = {1, 2, 3, 4, 5, 6};
sizeFilterSettings(true, enabled, resetSelected || sizeCheckbox.isSelected(), resetSelected == true ? selectedSizeIndices : null);
int[] selectedFrequencyIndices;
if (!EamDb.isEnabled()) {
selectedFrequencyIndices = new int[]{0};
} else {
selectedFrequencyIndices = new int[]{1, 2, 3, 4, 5, 6, 7};
}
crFrequencyFilterSettings(true, enabled, resetSelected || crFrequencyCheckbox.isSelected(), resetSelected == true ? selectedFrequencyIndices : null);
exifFilterSettings(true, enabled, !resetSelected && exifCheckbox.isSelected());
objectsFilterSettings(true, enabled, !resetSelected && objectsCheckbox.isSelected(), null);
hashSetFilterSettings(true, enabled, !resetSelected && hashSetCheckbox.isSelected(), null);
interestingItemsFilterSettings(true, enabled, !resetSelected && interestingItemsCheckbox.isSelected(), null);
parentFilterSettings(true, false, false, null);
scoreFilterSettings(false, false, false, null);
tagsFilterSettings(false, false, false, null);
keywordFilterSettings(false, false, false, null);
knownFilesFilterSettings(false, false, false);
notableFilterSettings(false, false, false);
}
/**
* Set the UI elements available to be the set of UI elements available when
* a Video search is being performed.
*
* @param enabled Boolean indicating if the filters present for videos
* should be enabled.
* @param resetSelected Boolean indicating if selection of the filters
* present for videos should be reset to their default
* status.
*/
private void videosSelected(boolean enabled, boolean resetSelected) {
dataSourceFilterSettings(true, enabled, !resetSelected && dataSourceCheckbox.isSelected(), null);
sizeFilterSettings(true, enabled, !resetSelected && sizeCheckbox.isSelected(), null);
int[] selectedFrequencyIndices;
if (!EamDb.isEnabled()) {
selectedFrequencyIndices = new int[]{0};
} else {
selectedFrequencyIndices = new int[]{1, 2, 3, 4, 5, 6, 7};
}
crFrequencyFilterSettings(true, enabled, resetSelected || crFrequencyCheckbox.isSelected(), resetSelected == true ? selectedFrequencyIndices : null);
exifFilterSettings(true, enabled, !resetSelected && exifCheckbox.isSelected());
objectsFilterSettings(true, enabled, !resetSelected && objectsCheckbox.isSelected(), null);
hashSetFilterSettings(true, enabled, !resetSelected && hashSetCheckbox.isSelected(), null);
interestingItemsFilterSettings(true, enabled, !resetSelected && interestingItemsCheckbox.isSelected(), null);
parentFilterSettings(true, false, false, null);
scoreFilterSettings(false, false, false, null);
tagsFilterSettings(false, false, false, null);
keywordFilterSettings(false, false, false, null);
knownFilesFilterSettings(false, false, false);
notableFilterSettings(false, false, false);
}
/**
* Set the type of search to perform.
*
* @param type The type of File to be found by the search.
*/
void setSelectedType(FileType type) {
if (type.equals(fileType)) {
//change the size filter if the type changed
setUpSizeFilter();
}
fileType = type;
if (fileType == FileType.IMAGE) {
imagesSelected(true, true);
} else if (fileType == FileType.VIDEO) {
videosSelected(true, true);
}
validateFields();
}
/**
* Reset the panel to its initial configuration.
*/
void resetPanel() {
searchButton.setEnabled(false);
// Set up the filters
setUpDataSourceFilter();
setUpFrequencyFilter();
setUpSizeFilter();
setUpKWFilter();
setUpParentPathFilter();
setUpHashFilter();
setUpInterestingItemsFilter();
setUpTagsFilter();
setUpObjectFilter();
setUpScoreFilter();
groupByCombobox.removeAllItems();
// Set up the grouping attributes
for (FileSearch.GroupingAttributeType type : FileSearch.GroupingAttributeType.getOptionsForGrouping()) {
if (type != GroupingAttributeType.FREQUENCY || EamDb.isEnabled()) {
groupByCombobox.addItem(type);
}
}
orderByCombobox.removeAllItems();
// Set up the file order list
for (FileSorter.SortingMethod method : FileSorter.SortingMethod.getOptionsForOrdering()) {
if (method != SortingMethod.BY_FREQUENCY || EamDb.isEnabled()) {
orderByCombobox.addItem(method);
}
}
setSelectedType(FileType.IMAGE);
validateFields();
}
/**
* Add listeners to the checkbox/list set if listeners have not already been
* added. Either can be null.
*
* @param checkBox
* @param list
*/
private void addListeners(JCheckBox checkBox, JList<?> list) {
if (checkBox != null && checkBox.getActionListeners().length == 0) {
checkBox.addActionListener(this);
}
if (list != null && list.getListSelectionListeners().length == 0) {
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent evt) {
if (!evt.getValueIsAdjusting()) {
validateFields();
}
}
});
}
}
/**
* Initialize the data source filter
*/
private void setUpDataSourceFilter() {
int count = 0;
try {
DefaultListModel<DataSourceItem> dsListModel = (DefaultListModel<DataSourceItem>) dataSourceList.getModel();
dsListModel.removeAllElements();
for (DataSource ds : Case.getCurrentCase().getSleuthkitCase().getDataSources()) {
dsListModel.add(count, new DataSourceItem(ds));
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading data sources", ex);
dataSourceCheckbox.setEnabled(false);
dataSourceList.setEnabled(false);
}
addListeners(dataSourceCheckbox, dataSourceList);
}
/**
* Initialize the frequency filter
*/
private void setUpFrequencyFilter() {
int count = 0;
DefaultListModel<FileSearchData.Frequency> frequencyListModel = (DefaultListModel<FileSearchData.Frequency>) crFrequencyList.getModel();
frequencyListModel.removeAllElements();
if (!EamDb.isEnabled()) {
for (FileSearchData.Frequency freq : FileSearchData.Frequency.getOptionsForFilteringWithoutCr()) {
frequencyListModel.add(count, freq);
}
} else {
for (FileSearchData.Frequency freq : FileSearchData.Frequency.getOptionsForFilteringWithCr()) {
frequencyListModel.add(count, freq);
}
}
addListeners(crFrequencyCheckbox, crFrequencyList);
}
/**
* Initialize the file size filter
*/
private void setUpSizeFilter() {
int count = 0;
DefaultListModel<FileSearchData.FileSize> sizeListModel = (DefaultListModel<FileSearchData.FileSize>) sizeList.getModel();
sizeListModel.removeAllElements();
if (null == fileType) {
for (FileSearchData.FileSize size : FileSearchData.FileSize.values()) {
sizeListModel.add(count, size);
}
} else {
List<FileSearchData.FileSize> sizes;
switch (fileType) {
case VIDEO:
sizes = FileSearchData.FileSize.getOptionsForVideos();
break;
case IMAGE:
sizes = FileSearchData.FileSize.getOptionsForImages();
break;
default:
sizes = new ArrayList<>();
break;
}
for (FileSearchData.FileSize size : sizes) {
sizeListModel.add(count, size);
}
}
addListeners(sizeCheckbox, sizeList);
}
/**
* Initialize the keyword list names filter
*/
private void setUpKWFilter() {
int count = 0;
try {
DefaultListModel<String> kwListModel = (DefaultListModel<String>) keywordList.getModel();
kwListModel.removeAllElements();
List<String> setNames = getSetNames(BlackboardArtifact.ARTIFACT_TYPE.TSK_KEYWORD_HIT,
BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME);
for (String name : setNames) {
kwListModel.add(count, name);
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading keyword list names", ex);
keywordCheckbox.setEnabled(false);
keywordList.setEnabled(false);
}
addListeners(keywordCheckbox, keywordList);
}
/**
* Initialize the hash filter.
*/
private void setUpHashFilter() {
int count = 0;
try {
DefaultListModel<String> hashListModel = (DefaultListModel<String>) hashSetList.getModel();
hashListModel.removeAllElements();
List<String> setNames = getSetNames(BlackboardArtifact.ARTIFACT_TYPE.TSK_HASHSET_HIT,
BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME);
for (String name : setNames) {
hashListModel.add(count, name);
count++;
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading hash set names", ex);
hashSetCheckbox.setEnabled(false);
hashSetList.setEnabled(false);
}
addListeners(hashSetCheckbox, hashSetList);
}
/**
* Initialize the interesting items filter.
*/
private void setUpInterestingItemsFilter() {
int count = 0;
try {
DefaultListModel<String> intListModel = (DefaultListModel<String>) interestingItemsList.getModel();
intListModel.removeAllElements();
List<String> setNames = getSetNames(BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT,
BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME);
for (String name : setNames) {
intListModel.add(count, name);
count++;
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading interesting file set names", ex);
interestingItemsCheckbox.setEnabled(false);
interestingItemsList.setEnabled(false);
}
addListeners(interestingItemsCheckbox, interestingItemsList);
}
/**
* Initialize the tags filter.
*/
private void setUpTagsFilter() {
int count = 0;
try {
DefaultListModel<TagName> tagsListModel = (DefaultListModel<TagName>) tagsList.getModel();
tagsListModel.removeAllElements();
List<TagName> tagNames = Case.getCurrentCase().getSleuthkitCase().getTagNamesInUse();
for (TagName name : tagNames) {
tagsListModel.add(count, name);
count++;
}
tagsList.setCellRenderer(new TagsListCellRenderer());
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading tag names", ex);
tagsCheckbox.setEnabled(false);
tagsList.setEnabled(false);
}
addListeners(tagsCheckbox, tagsList);
}
/**
* TagsListCellRenderer
*/
private class TagsListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
@Override
public java.awt.Component getListCellRendererComponent(
JList<?> list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Object newValue = value;
if (value instanceof TagName) {
newValue = ((TagName) value).getDisplayName();
}
super.getListCellRendererComponent(list, newValue, index, isSelected, cellHasFocus);
return this;
}
}
/**
* Initialize the object filter
*/
private void setUpObjectFilter() {
int count = 0;
try {
DefaultListModel<String> objListModel = (DefaultListModel<String>) objectsList.getModel();
objListModel.removeAllElements();
List<String> setNames = getSetNames(BlackboardArtifact.ARTIFACT_TYPE.TSK_OBJECT_DETECTED, BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DESCRIPTION);
for (String name : setNames) {
objListModel.add(count, name);
count++;
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading object detected set names", ex);
objectsCheckbox.setEnabled(false);
objectsList.setEnabled(false);
}
addListeners(objectsCheckbox, objectsList);
}
/**
* Initialize the score filter
*/
private void setUpScoreFilter() {
int count = 0;
DefaultListModel<Score> scoreListModel = (DefaultListModel<Score>) scoreList.getModel();
scoreListModel.removeAllElements();
for (Score score : Score.getOptionsForFiltering()) {
scoreListModel.add(count, score);
}
addListeners(scoreCheckbox, scoreList);
}
/**
* Get the names of the sets which exist in the case database for the
* specified artifact and attribute types.
*
* @param artifactType The artifact type to get the list of sets for.
* @param setNameAttribute The attribute type which contains the set names.
*
* @return A list of set names which exist in the case for the specified
* artifact and attribute types.
*
* @throws TskCoreException
*/
private List<String> getSetNames(BlackboardArtifact.ARTIFACT_TYPE artifactType, BlackboardAttribute.ATTRIBUTE_TYPE setNameAttribute) throws TskCoreException {
List<BlackboardArtifact> arts = Case.getCurrentCase().getSleuthkitCase().getBlackboardArtifacts(artifactType);
List<String> setNames = new ArrayList<>();
for (BlackboardArtifact art : arts) {
for (BlackboardAttribute attr : art.getAttributes()) {
if (attr.getAttributeType().getTypeID() == setNameAttribute.getTypeID()) {
String setName = attr.getValueString();
if (!setNames.contains(setName)) {
setNames.add(setName);
}
}
}
}
Collections.sort(setNames);
return setNames;
}
/**
* Initialize the parent path filter
*/
private void setUpParentPathFilter() {
fullRadioButton.setSelected(true);
includeRadioButton.setSelected(true);
parentListModel = (DefaultListModel<FileSearchFiltering.ParentSearchTerm>) parentList.getModel();
addListeners(parentCheckbox, parentList);
}
/**
* Get a list of all filters selected by the user.
*
* @return the list of filters
*/
List<FileSearchFiltering.FileFilter> getFilters() {
List<FileSearchFiltering.FileFilter> filters = new ArrayList<>();
filters.add(new FileSearchFiltering.FileTypeFilter(fileType));
if (parentCheckbox.isSelected()) {
// For the parent paths, everything in the box is used (not just the selected entries)
filters.add(new FileSearchFiltering.ParentFilter(getParentPaths()));
}
if (dataSourceCheckbox.isSelected()) {
List<DataSource> dataSources = dataSourceList.getSelectedValuesList().stream().map(t -> t.getDataSource()).collect(Collectors.toList());
filters.add(new FileSearchFiltering.DataSourceFilter(dataSources));
}
if (crFrequencyCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.FrequencyFilter(crFrequencyList.getSelectedValuesList()));
}
if (sizeCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.SizeFilter(sizeList.getSelectedValuesList()));
}
if (keywordCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.KeywordListFilter(keywordList.getSelectedValuesList()));
}
if (hashSetCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.HashSetFilter(hashSetList.getSelectedValuesList()));
}
if (interestingItemsCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.InterestingFileSetFilter(interestingItemsList.getSelectedValuesList()));
}
if (objectsCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.ObjectDetectionFilter(objectsList.getSelectedValuesList()));
}
if (tagsCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.TagsFilter(tagsList.getSelectedValuesList()));
}
if (exifCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.ExifFilter());
}
if (notableCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.NotableFilter());
}
if (knownFilesCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.KnownFilter());
}
if (scoreCheckbox.isSelected()) {
filters.add(new FileSearchFiltering.ScoreFilter(scoreList.getSelectedValuesList()));
}
return filters;
}
/**
* Utility method to get the parent path objects out of the JList.
*
* @return The list of entered ParentSearchTerm objects
*/
private List<FileSearchFiltering.ParentSearchTerm> getParentPaths() {
List<FileSearchFiltering.ParentSearchTerm> results = new ArrayList<>();
for (int i = 0; i < parentListModel.getSize(); i++) {
results.add(parentListModel.get(i));
}
return results;
}
/**
* Get the attribute to group by
*
* @return the grouping attribute
*/
FileSearch.AttributeType getGroupingAttribute() {
FileSearch.GroupingAttributeType groupingAttrType = (FileSearch.GroupingAttributeType) groupByCombobox.getSelectedItem();
return groupingAttrType.getAttributeType();
}
/**
* Get the sorting method for groups.
*
* @return the selected sorting method
*/
FileGroup.GroupSortingAlgorithm getGroupSortingMethod() {
if (attributeRadioButton.isSelected()) {
return FileGroup.GroupSortingAlgorithm.BY_GROUP_KEY;
}
return FileGroup.GroupSortingAlgorithm.BY_GROUP_SIZE;
}
/**
* Get the sorting method for files.
*
* @return the selected sorting method
*/
FileSorter.SortingMethod getFileSortingMethod() {
return (FileSorter.SortingMethod) orderByCombobox.getSelectedItem();
}
@Override
public void actionPerformed(ActionEvent e) {
validateFields();
}
/**
* Utility class to allow us to display the data source ID along with the
* name
*/
private class DataSourceItem {
private final DataSource ds;
DataSourceItem(DataSource ds) {
this.ds = ds;
}
DataSource getDataSource() {
return ds;
}
@Override
public String toString() {
return ds.getName() + " (ID: " + ds.getId() + ")";
}
}
/**
* Validate the form. If we use any of this in the final dialog we should
* use bundle messages.
*/
private void validateFields() {
// There will be a file type selected.
if (fileType == null) {
setInvalid("At least one file type must be selected");
return;
}
// For most enabled filters, there should be something selected
if (dataSourceCheckbox.isSelected() && dataSourceList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one data source must be selected");
return;
}
if (crFrequencyCheckbox.isSelected() && crFrequencyList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one CR frequency must be selected");
return;
}
if (sizeCheckbox.isSelected() && sizeList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one size must be selected");
return;
}
if (keywordCheckbox.isSelected() && keywordList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one keyword list name must be selected");
return;
}
// Parent uses everything in the box
if (parentCheckbox.isSelected() && getParentPaths().isEmpty()) {
setInvalid("At least one parent path must be entered");
return;
}
if (hashSetCheckbox.isSelected() && hashSetList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one hash set name must be selected");
return;
}
if (interestingItemsCheckbox.isSelected() && interestingItemsList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one interesting file set name must be selected");
return;
}
if (objectsCheckbox.isSelected() && objectsList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one object type name must be selected");
return;
}
if (tagsCheckbox.isSelected() && tagsList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one tag name must be selected");
return;
}
if (scoreCheckbox.isSelected() && scoreList.getSelectedValuesList().isEmpty()) {
setInvalid("At least one score must be selected");
return;
}
setValid();
}
/**
* The settings are valid so enable the Search button
*/
private void setValid() {
errorLabel.setText("");
searchButton.setEnabled(true);
}
/**
* The settings are not valid so disable the search button and display the
* given error message.
*
* @param error
*/
private void setInvalid(String error) {
errorLabel.setText(error);
searchButton.setEnabled(false);
}
/**
* 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() {
java.awt.GridBagConstraints gridBagConstraints;
javax.swing.ButtonGroup parentPathButtonGroup = new javax.swing.ButtonGroup();
orderGroupsByButtonGroup = new javax.swing.ButtonGroup();
javax.swing.ButtonGroup parentIncludeButtonGroup = new javax.swing.ButtonGroup();
filtersScrollPane = new javax.swing.JScrollPane();
filtersPanel = new javax.swing.JPanel();
sizeCheckbox = new javax.swing.JCheckBox();
dataSourceCheckbox = new javax.swing.JCheckBox();
crFrequencyCheckbox = new javax.swing.JCheckBox();
keywordCheckbox = new javax.swing.JCheckBox();
parentCheckbox = new javax.swing.JCheckBox();
dataSourceScrollPane = new javax.swing.JScrollPane();
dataSourceList = new javax.swing.JList<>();
fullRadioButton = new javax.swing.JRadioButton();
substringRadioButton = new javax.swing.JRadioButton();
parentTextField = new javax.swing.JTextField();
addButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
sizeScrollPane = new javax.swing.JScrollPane();
sizeList = new javax.swing.JList<>();
crFrequencyScrollPane = new javax.swing.JScrollPane();
crFrequencyList = new javax.swing.JList<>();
keywordScrollPane = new javax.swing.JScrollPane();
keywordList = new javax.swing.JList<>();
parentLabel = new javax.swing.JLabel();
parentScrollPane = new javax.swing.JScrollPane();
parentList = new javax.swing.JList<>();
hashSetCheckbox = new javax.swing.JCheckBox();
hashSetScrollPane = new javax.swing.JScrollPane();
hashSetList = new javax.swing.JList<>();
objectsCheckbox = new javax.swing.JCheckBox();
tagsCheckbox = new javax.swing.JCheckBox();
interestingItemsCheckbox = new javax.swing.JCheckBox();
scoreCheckbox = new javax.swing.JCheckBox();
exifCheckbox = new javax.swing.JCheckBox();
notableCheckbox = new javax.swing.JCheckBox();
objectsScrollPane = new javax.swing.JScrollPane();
objectsList = new javax.swing.JList<>();
tagsScrollPane = new javax.swing.JScrollPane();
tagsList = new javax.swing.JList<>();
interestingItemsScrollPane = new javax.swing.JScrollPane();
interestingItemsList = new javax.swing.JList<>();
scoreScrollPane = new javax.swing.JScrollPane();
scoreList = new javax.swing.JList<>();
includeRadioButton = new javax.swing.JRadioButton();
excludeRadioButton = new javax.swing.JRadioButton();
knownFilesCheckbox = new javax.swing.JCheckBox();
searchButton = new javax.swing.JButton();
sortingPanel = new javax.swing.JPanel();
groupByCombobox = new javax.swing.JComboBox<>();
orderByCombobox = new javax.swing.JComboBox<>();
orderGroupsByLabel = new javax.swing.JLabel();
attributeRadioButton = new javax.swing.JRadioButton();
groupSizeRadioButton = new javax.swing.JRadioButton();
orderByLabel = new javax.swing.JLabel();
groupByLabel = new javax.swing.JLabel();
errorLabel = new javax.swing.JLabel();
cancelButton = new javax.swing.JButton();
setMinimumSize(new java.awt.Dimension(424, 0));
setPreferredSize(new java.awt.Dimension(424, 533));
filtersScrollPane.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.filtersScrollPane.border.title"))); // NOI18N
filtersScrollPane.setPreferredSize(new java.awt.Dimension(416, 338));
filtersPanel.setLayout(new java.awt.GridBagLayout());
org.openide.awt.Mnemonics.setLocalizedText(sizeCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.sizeCheckbox.text")); // NOI18N
sizeCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sizeCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 4, 0);
filtersPanel.add(sizeCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(dataSourceCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.dataSourceCheckbox.text")); // NOI18N
dataSourceCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dataSourceCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(dataSourceCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(crFrequencyCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.crFrequencyCheckbox.text")); // NOI18N
crFrequencyCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
crFrequencyCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(crFrequencyCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(keywordCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.keywordCheckbox.text")); // NOI18N
keywordCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
keywordCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 12;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(keywordCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(parentCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.parentCheckbox.text")); // NOI18N
parentCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
parentCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(parentCheckbox, gridBagConstraints);
dataSourceList.setModel(new DefaultListModel<DataSourceItem>());
dataSourceList.setEnabled(false);
dataSourceList.setVisibleRowCount(5);
dataSourceScrollPane.setViewportView(dataSourceList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(dataSourceScrollPane, gridBagConstraints);
parentPathButtonGroup.add(fullRadioButton);
fullRadioButton.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(fullRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.fullRadioButton.text")); // NOI18N
fullRadioButton.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
filtersPanel.add(fullRadioButton, gridBagConstraints);
parentPathButtonGroup.add(substringRadioButton);
org.openide.awt.Mnemonics.setLocalizedText(substringRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.substringRadioButton.text")); // NOI18N
substringRadioButton.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
filtersPanel.add(substringRadioButton, gridBagConstraints);
parentTextField.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 11;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 6, 0);
filtersPanel.add(parentTextField, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(addButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.addButton.text")); // NOI18N
addButton.setEnabled(false);
addButton.setMaximumSize(new java.awt.Dimension(70, 23));
addButton.setMinimumSize(new java.awt.Dimension(70, 23));
addButton.setPreferredSize(new java.awt.Dimension(70, 23));
addButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 11;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 6);
filtersPanel.add(addButton, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(deleteButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.deleteButton.text")); // NOI18N
deleteButton.setEnabled(false);
deleteButton.setMaximumSize(new java.awt.Dimension(70, 23));
deleteButton.setMinimumSize(new java.awt.Dimension(70, 23));
deleteButton.setPreferredSize(new java.awt.Dimension(70, 23));
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 4, 6);
filtersPanel.add(deleteButton, gridBagConstraints);
sizeList.setModel(new DefaultListModel<FileSize>());
sizeList.setEnabled(false);
sizeList.setVisibleRowCount(5);
sizeScrollPane.setViewportView(sizeList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(6, 4, 4, 6);
filtersPanel.add(sizeScrollPane, gridBagConstraints);
crFrequencyList.setModel(new DefaultListModel<Frequency>());
crFrequencyList.setEnabled(false);
crFrequencyList.setVisibleRowCount(3);
crFrequencyScrollPane.setViewportView(crFrequencyList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(crFrequencyScrollPane, gridBagConstraints);
keywordList.setModel(new DefaultListModel<String>());
keywordList.setEnabled(false);
keywordList.setVisibleRowCount(3);
keywordScrollPane.setViewportView(keywordList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 12;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(keywordScrollPane, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(parentLabel, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.parentLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(parentLabel, gridBagConstraints);
parentList.setModel(new DefaultListModel<ParentSearchTerm>());
parentList.setEnabled(false);
parentList.setVisibleRowCount(3);
parentList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
parentListValueChanged(evt);
}
});
parentScrollPane.setViewportView(parentList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(parentScrollPane, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(hashSetCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.hashSetCheckbox.text")); // NOI18N
hashSetCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
hashSetCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(hashSetCheckbox, gridBagConstraints);
hashSetList.setModel(new DefaultListModel<String>());
hashSetList.setEnabled(false);
hashSetList.setVisibleRowCount(3);
hashSetScrollPane.setViewportView(hashSetList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(hashSetScrollPane, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(objectsCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.objectsCheckbox.text")); // NOI18N
objectsCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
objectsCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(objectsCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(tagsCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.tagsCheckbox.text")); // NOI18N
tagsCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tagsCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 13;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(tagsCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(interestingItemsCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.interestingItemsCheckbox.text")); // NOI18N
interestingItemsCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
interestingItemsCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(interestingItemsCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(scoreCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.scoreCheckbox.text")); // NOI18N
scoreCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
scoreCheckboxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 14;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 0);
filtersPanel.add(scoreCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(exifCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.exifCheckbox.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 6);
filtersPanel.add(exifCheckbox, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(notableCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.notableCheckbox.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 15;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 6);
filtersPanel.add(notableCheckbox, gridBagConstraints);
objectsList.setModel(new DefaultListModel<String>());
objectsList.setEnabled(false);
objectsList.setVisibleRowCount(3);
objectsScrollPane.setViewportView(objectsList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(objectsScrollPane, gridBagConstraints);
tagsList.setModel(new DefaultListModel<TagName>());
tagsList.setEnabled(false);
tagsList.setVisibleRowCount(3);
tagsScrollPane.setViewportView(tagsList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 13;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(tagsScrollPane, gridBagConstraints);
interestingItemsList.setModel(new DefaultListModel<String>());
interestingItemsList.setEnabled(false);
interestingItemsList.setVisibleRowCount(3);
interestingItemsScrollPane.setViewportView(interestingItemsList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(interestingItemsScrollPane, gridBagConstraints);
scoreList.setModel(new DefaultListModel<Score>());
scoreList.setEnabled(false);
scoreList.setVisibleRowCount(3);
scoreScrollPane.setViewportView(scoreList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 14;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 6);
filtersPanel.add(scoreScrollPane, gridBagConstraints);
parentIncludeButtonGroup.add(includeRadioButton);
includeRadioButton.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(includeRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.includeRadioButton.text")); // NOI18N
includeRadioButton.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
filtersPanel.add(includeRadioButton, gridBagConstraints);
parentIncludeButtonGroup.add(excludeRadioButton);
org.openide.awt.Mnemonics.setLocalizedText(excludeRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.excludeRadioButton.text")); // NOI18N
excludeRadioButton.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
filtersPanel.add(excludeRadioButton, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(knownFilesCheckbox, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.knownFilesCheckbox.text")); // NOI18N
knownFilesCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.knownFilesCheckbox.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 16;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 4, 6);
filtersPanel.add(knownFilesCheckbox, gridBagConstraints);
filtersScrollPane.setViewportView(filtersPanel);
org.openide.awt.Mnemonics.setLocalizedText(searchButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.searchButton.text")); // NOI18N
searchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchButtonActionPerformed(evt);
}
});
sortingPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.sortingPanel.border.title"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(orderGroupsByLabel, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.orderGroupsByLabel.text")); // NOI18N
orderGroupsByButtonGroup.add(attributeRadioButton);
attributeRadioButton.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(attributeRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.attributeRadioButton.text")); // NOI18N
orderGroupsByButtonGroup.add(groupSizeRadioButton);
org.openide.awt.Mnemonics.setLocalizedText(groupSizeRadioButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.groupSizeRadioButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(orderByLabel, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.orderByLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(groupByLabel, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.groupByLabel.text")); // NOI18N
javax.swing.GroupLayout sortingPanelLayout = new javax.swing.GroupLayout(sortingPanel);
sortingPanel.setLayout(sortingPanelLayout);
sortingPanelLayout.setHorizontalGroup(
sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(attributeRadioButton))
.addGroup(sortingPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(orderByLabel))
.addGroup(sortingPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(groupByLabel)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(groupByCombobox, 0, 280, Short.MAX_VALUE)
.addComponent(orderByCombobox, 0, 1, Short.MAX_VALUE)))
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(orderGroupsByLabel))
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(groupSizeRadioButton)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
sortingPanelLayout.setVerticalGroup(
sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(orderByCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(orderByLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(groupByCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(groupByLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(orderGroupsByLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(attributeRadioButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(groupSizeRadioButton)
.addContainerGap())
);
errorLabel.setForeground(new java.awt.Color(255, 0, 0));
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(FileSearchPanel.class, "FileSearchPanel.cancelButton.text")); // NOI18N
cancelButton.setEnabled(false);
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(searchButton))
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(filtersScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(sortingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(6, 6, 6))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, searchButton});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(filtersScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sortingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(errorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(searchButton)))
.addGap(6, 6, 6))
);
}// </editor-fold>//GEN-END:initComponents
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
// Get the selected filters
List<FileSearchFiltering.FileFilter> filters = getFilters();
enableSearch(false);
DiscoveryEvents.getDiscoveryEventBus().post(new DiscoveryEvents.SearchStartedEvent(fileType));
// Get the grouping attribute and group sorting method
FileSearch.AttributeType groupingAttr = getGroupingAttribute();
FileGroup.GroupSortingAlgorithm groupSortAlgorithm = getGroupSortingMethod();
// Get the file sorting method
FileSorter.SortingMethod fileSort = getFileSortingMethod();
EamDb centralRepoDb = null;
if (EamDb.isEnabled()) {
try {
centralRepoDb = EamDb.getInstance();
} catch (EamDbException ex) {
centralRepoDb = null;
logger.log(Level.SEVERE, "Error loading central repository database, no central repository options will be available for File Discovery", ex);
}
}
searchWorker = new SearchWorker(centralRepoDb, filters, groupingAttr, groupSortAlgorithm, fileSort);
searchWorker.execute();
}//GEN-LAST:event_searchButtonActionPerformed
/**
* Set the enabled status of the search controls.
*
* @param enabled Boolean which indicates if the search should be enabled.
* True if the search button and controls should be enabled,
* false otherwise.
*/
private void enableSearch(boolean enabled) {
if (enabled) {
DiscoveryTopComponent.getTopComponent().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
} else {
DiscoveryTopComponent.getTopComponent().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
if (fileType == FileType.IMAGE) {
imagesSelected(enabled, false);
} else if (fileType == FileType.VIDEO) {
videosSelected(enabled, false);
}
searchButton.setEnabled(enabled);
cancelButton.setEnabled(!enabled);
orderByCombobox.setEnabled(enabled);
groupByCombobox.setEnabled(enabled);
attributeRadioButton.setEnabled(enabled);
groupSizeRadioButton.setEnabled(enabled);
}
/**
* Update the user interface when a search has been cancelled.
*
* @param searchCancelledEvent The SearchCancelledEvent which was received.
*/
@Subscribe
void handleSearchCancelledEvent(DiscoveryEvents.SearchCancelledEvent searchCancelledEvent) {
SwingUtilities.invokeLater(() -> {
enableSearch(true);
});
}
/**
* Update the user interface when a search has been successfully completed.
*
* @param searchCompleteEvent The SearchCompleteEvent which was received.
*/
@Subscribe
void handleSearchCompleteEvent(DiscoveryEvents.SearchCompleteEvent searchCompleteEvent) {
SwingUtilities.invokeLater(() -> {
enableSearch(true);
});
}
private void parentCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_parentCheckboxActionPerformed
parentFilterSettings(true, true, parentCheckbox.isSelected(), null);
}//GEN-LAST:event_parentCheckboxActionPerformed
private void keywordCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_keywordCheckboxActionPerformed
keywordList.setEnabled(keywordCheckbox.isSelected());
}//GEN-LAST:event_keywordCheckboxActionPerformed
private void sizeCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sizeCheckboxActionPerformed
sizeList.setEnabled(sizeCheckbox.isSelected());
}//GEN-LAST:event_sizeCheckboxActionPerformed
private void crFrequencyCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_crFrequencyCheckboxActionPerformed
crFrequencyList.setEnabled(crFrequencyCheckbox.isSelected());
}//GEN-LAST:event_crFrequencyCheckboxActionPerformed
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
if (!parentTextField.getText().isEmpty()) {
ParentSearchTerm searchTerm;
searchTerm = new ParentSearchTerm(parentTextField.getText(), fullRadioButton.isSelected(), includeRadioButton.isSelected());
parentListModel.add(parentListModel.size(), searchTerm);
validateFields();
parentTextField.setText("");
}
}//GEN-LAST:event_addButtonActionPerformed
/**
* Cancel the current search.
*/
void cancelSearch() {
if (searchWorker != null) {
searchWorker.cancel(true);
}
}
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
int index = parentList.getSelectedIndex();
if (index >= 0) {
parentListModel.remove(index);
}
validateFields();
}//GEN-LAST:event_deleteButtonActionPerformed
private void parentListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_parentListValueChanged
if (parentList.getSelectedValuesList().isEmpty()) {
deleteButton.setEnabled(false);
} else {
deleteButton.setEnabled(true);
}
}//GEN-LAST:event_parentListValueChanged
private void dataSourceCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataSourceCheckboxActionPerformed
dataSourceList.setEnabled(dataSourceCheckbox.isSelected());
}//GEN-LAST:event_dataSourceCheckboxActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
cancelSearch();
}//GEN-LAST:event_cancelButtonActionPerformed
private void hashSetCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hashSetCheckboxActionPerformed
hashSetList.setEnabled(hashSetCheckbox.isSelected());
}//GEN-LAST:event_hashSetCheckboxActionPerformed
private void objectsCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_objectsCheckboxActionPerformed
objectsList.setEnabled(objectsCheckbox.isSelected());
}//GEN-LAST:event_objectsCheckboxActionPerformed
private void tagsCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tagsCheckboxActionPerformed
tagsList.setEnabled(tagsCheckbox.isSelected());
}//GEN-LAST:event_tagsCheckboxActionPerformed
private void interestingItemsCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_interestingItemsCheckboxActionPerformed
interestingItemsList.setEnabled(interestingItemsCheckbox.isSelected());
}//GEN-LAST:event_interestingItemsCheckboxActionPerformed
private void scoreCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scoreCheckboxActionPerformed
scoreList.setEnabled(scoreCheckbox.isSelected());
}//GEN-LAST:event_scoreCheckboxActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addButton;
private javax.swing.JRadioButton attributeRadioButton;
private javax.swing.JButton cancelButton;
private javax.swing.JCheckBox crFrequencyCheckbox;
private javax.swing.JList<Frequency> crFrequencyList;
private javax.swing.JScrollPane crFrequencyScrollPane;
private javax.swing.JCheckBox dataSourceCheckbox;
private javax.swing.JList<DataSourceItem> dataSourceList;
private javax.swing.JScrollPane dataSourceScrollPane;
private javax.swing.JButton deleteButton;
private javax.swing.JLabel errorLabel;
private javax.swing.JRadioButton excludeRadioButton;
private javax.swing.JCheckBox exifCheckbox;
private javax.swing.JPanel filtersPanel;
private javax.swing.JScrollPane filtersScrollPane;
private javax.swing.JRadioButton fullRadioButton;
private javax.swing.JComboBox<GroupingAttributeType> groupByCombobox;
private javax.swing.JLabel groupByLabel;
private javax.swing.JRadioButton groupSizeRadioButton;
private javax.swing.JCheckBox hashSetCheckbox;
private javax.swing.JList<String> hashSetList;
private javax.swing.JScrollPane hashSetScrollPane;
private javax.swing.JRadioButton includeRadioButton;
private javax.swing.JCheckBox interestingItemsCheckbox;
private javax.swing.JList<String> interestingItemsList;
private javax.swing.JScrollPane interestingItemsScrollPane;
private javax.swing.JCheckBox keywordCheckbox;
private javax.swing.JList<String> keywordList;
private javax.swing.JScrollPane keywordScrollPane;
private javax.swing.JCheckBox knownFilesCheckbox;
private javax.swing.JCheckBox notableCheckbox;
private javax.swing.JCheckBox objectsCheckbox;
private javax.swing.JList<String> objectsList;
private javax.swing.JScrollPane objectsScrollPane;
private javax.swing.JComboBox<SortingMethod> orderByCombobox;
private javax.swing.JLabel orderByLabel;
private javax.swing.ButtonGroup orderGroupsByButtonGroup;
private javax.swing.JLabel orderGroupsByLabel;
private javax.swing.JCheckBox parentCheckbox;
private javax.swing.JLabel parentLabel;
private javax.swing.JList<ParentSearchTerm> parentList;
private javax.swing.JScrollPane parentScrollPane;
private javax.swing.JTextField parentTextField;
private javax.swing.JCheckBox scoreCheckbox;
private javax.swing.JList<Score> scoreList;
private javax.swing.JScrollPane scoreScrollPane;
private javax.swing.JButton searchButton;
private javax.swing.JCheckBox sizeCheckbox;
private javax.swing.JList<FileSize> sizeList;
private javax.swing.JScrollPane sizeScrollPane;
private javax.swing.JPanel sortingPanel;
private javax.swing.JRadioButton substringRadioButton;
private javax.swing.JCheckBox tagsCheckbox;
private javax.swing.JList<TagName> tagsList;
private javax.swing.JScrollPane tagsScrollPane;
// End of variables declaration//GEN-END:variables
}
| 5673 enable parent filter
| Core/src/org/sleuthkit/autopsy/filequery/FileSearchPanel.java | 5673 enable parent filter | <ide><path>ore/src/org/sleuthkit/autopsy/filequery/FileSearchPanel.java
<ide> objectsFilterSettings(true, enabled, !resetSelected && objectsCheckbox.isSelected(), null);
<ide> hashSetFilterSettings(true, enabled, !resetSelected && hashSetCheckbox.isSelected(), null);
<ide> interestingItemsFilterSettings(true, enabled, !resetSelected && interestingItemsCheckbox.isSelected(), null);
<del> parentFilterSettings(true, false, false, null);
<add> parentFilterSettings(true, true, false, null);
<ide> scoreFilterSettings(false, false, false, null);
<ide> tagsFilterSettings(false, false, false, null);
<ide> keywordFilterSettings(false, false, false, null);
<ide> objectsFilterSettings(true, enabled, !resetSelected && objectsCheckbox.isSelected(), null);
<ide> hashSetFilterSettings(true, enabled, !resetSelected && hashSetCheckbox.isSelected(), null);
<ide> interestingItemsFilterSettings(true, enabled, !resetSelected && interestingItemsCheckbox.isSelected(), null);
<del> parentFilterSettings(true, false, false, null);
<add> parentFilterSettings(true, true, false, null);
<ide> scoreFilterSettings(false, false, false, null);
<ide> tagsFilterSettings(false, false, false, null);
<ide> keywordFilterSettings(false, false, false, null); |
|
Java | apache-2.0 | 6c60bc9f6cf0f62c8557296dcab9335b680951b5 | 0 | mahak/hbase,gustavoanatoly/hbase,Eshcar/hbase,JingchengDu/hbase,ultratendency/hbase,ChinmaySKulkarni/hbase,Apache9/hbase,vincentpoon/hbase,vincentpoon/hbase,ndimiduk/hbase,vincentpoon/hbase,ultratendency/hbase,mahak/hbase,HubSpot/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,mahak/hbase,gustavoanatoly/hbase,HubSpot/hbase,vincentpoon/hbase,francisliu/hbase,ultratendency/hbase,francisliu/hbase,Apache9/hbase,Apache9/hbase,mahak/hbase,mahak/hbase,ndimiduk/hbase,francisliu/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,mahak/hbase,ultratendency/hbase,Eshcar/hbase,gustavoanatoly/hbase,JingchengDu/hbase,bijugs/hbase,bijugs/hbase,ndimiduk/hbase,gustavoanatoly/hbase,gustavoanatoly/hbase,vincentpoon/hbase,Apache9/hbase,ultratendency/hbase,bijugs/hbase,vincentpoon/hbase,JingchengDu/hbase,gustavoanatoly/hbase,vincentpoon/hbase,JingchengDu/hbase,francisliu/hbase,Eshcar/hbase,apurtell/hbase,Apache9/hbase,bijugs/hbase,ChinmaySKulkarni/hbase,ultratendency/hbase,bijugs/hbase,HubSpot/hbase,Eshcar/hbase,mahak/hbase,apurtell/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,apurtell/hbase,bijugs/hbase,apurtell/hbase,Eshcar/hbase,Eshcar/hbase,francisliu/hbase,ultratendency/hbase,JingchengDu/hbase,JingchengDu/hbase,mahak/hbase,HubSpot/hbase,ndimiduk/hbase,Eshcar/hbase,JingchengDu/hbase,HubSpot/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,ndimiduk/hbase,HubSpot/hbase,ndimiduk/hbase,Apache9/hbase,vincentpoon/hbase,francisliu/hbase,bijugs/hbase,HubSpot/hbase,HubSpot/hbase,ChinmaySKulkarni/hbase,mahak/hbase,JingchengDu/hbase,ndimiduk/hbase,Eshcar/hbase,francisliu/hbase,mahak/hbase,Eshcar/hbase,Eshcar/hbase,vincentpoon/hbase,apurtell/hbase,ultratendency/hbase,Apache9/hbase,gustavoanatoly/hbase,ndimiduk/hbase,gustavoanatoly/hbase,ultratendency/hbase,ChinmaySKulkarni/hbase,gustavoanatoly/hbase,ultratendency/hbase,bijugs/hbase,ndimiduk/hbase,Apache9/hbase,francisliu/hbase,bijugs/hbase,HubSpot/hbase,bijugs/hbase,apurtell/hbase,gustavoanatoly/hbase,francisliu/hbase,vincentpoon/hbase,ndimiduk/hbase,apurtell/hbase,HubSpot/hbase,apurtell/hbase,Apache9/hbase,JingchengDu/hbase,francisliu/hbase,JingchengDu/hbase | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.mapred;
import java.io.IOException;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;
import org.apache.hadoop.hbase.client.BufferedMutator;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.InvalidJobConfException;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Progressable;
/**
* Convert Map/Reduce output and write it to an HBase table
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class TableOutputFormat extends FileOutputFormat<ImmutableBytesWritable, Put> {
/** JobConf parameter that specifies the output table */
public static final String OUTPUT_TABLE = "hbase.mapred.outputtable";
/**
* Convert Reduce output (key, value) to (HStoreKey, KeyedDataArrayWritable)
* and write to an HBase table.
*/
protected static class TableRecordWriter implements RecordWriter<ImmutableBytesWritable, Put> {
private BufferedMutator m_mutator;
private Connection connection;
/**
* Instantiate a TableRecordWriter with the HBase HClient for writing. Assumes control over the
* lifecycle of {@code conn}.
*/
public TableRecordWriter(final BufferedMutator mutator) throws IOException {
this.m_mutator = mutator;
}
public TableRecordWriter(JobConf job) throws IOException {
// expecting exactly one path
TableName tableName = TableName.valueOf(job.get(OUTPUT_TABLE));
connection = ConnectionFactory.createConnection(job);
m_mutator = connection.getBufferedMutator(tableName);
}
public void close(Reporter reporter) throws IOException {
this.m_mutator.close();
if (connection != null) {
connection.close();
connection = null;
}
}
public void write(ImmutableBytesWritable key, Put value) throws IOException {
m_mutator.mutate(new Put(value));
}
}
/**
* Creates a new record writer.
*
* Be aware that the baseline javadoc gives the impression that there is a single
* {@link RecordWriter} per job but in HBase, it is more natural if we give you a new
* RecordWriter per call of this method. You must close the returned RecordWriter when done.
* Failure to do so will drop writes.
*
* @param ignored Ignored filesystem
* @param job Current JobConf
* @param name Name of the job
* @param progress
* @return The newly created writer instance.
* @throws IOException When creating the writer fails.
*/
@Override
public RecordWriter getRecordWriter(FileSystem ignored, JobConf job, String name,
Progressable progress)
throws IOException {
return new TableRecordWriter(job);
}
@Override
public void checkOutputSpecs(FileSystem ignored, JobConf job)
throws FileAlreadyExistsException, InvalidJobConfException, IOException {
String tableName = job.get(OUTPUT_TABLE);
if (tableName == null) {
throw new IOException("Must specify table name");
}
}
}
| hbase-server/src/main/java/org/apache/hadoop/hbase/mapred/TableOutputFormat.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.mapred;
import java.io.IOException;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;
import org.apache.hadoop.hbase.client.BufferedMutator;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.InvalidJobConfException;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Progressable;
/**
* Convert Map/Reduce output and write it to an HBase table
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class TableOutputFormat extends FileOutputFormat<ImmutableBytesWritable, Put> {
/** JobConf parameter that specifies the output table */
public static final String OUTPUT_TABLE = "hbase.mapred.outputtable";
/**
* Convert Reduce output (key, value) to (HStoreKey, KeyedDataArrayWritable)
* and write to an HBase table.
*/
protected static class TableRecordWriter implements RecordWriter<ImmutableBytesWritable, Put> {
private BufferedMutator m_mutator;
/**
* Instantiate a TableRecordWriter with the HBase HClient for writing. Assumes control over the
* lifecycle of {@code conn}.
*/
public TableRecordWriter(final BufferedMutator mutator) throws IOException {
this.m_mutator = mutator;
}
public void close(Reporter reporter) throws IOException {
this.m_mutator.close();
}
public void write(ImmutableBytesWritable key, Put value) throws IOException {
m_mutator.mutate(new Put(value));
}
}
/**
* Creates a new record writer.
*
* Be aware that the baseline javadoc gives the impression that there is a single
* {@link RecordWriter} per job but in HBase, it is more natural if we give you a new
* RecordWriter per call of this method. You must close the returned RecordWriter when done.
* Failure to do so will drop writes.
*
* @param ignored Ignored filesystem
* @param job Current JobConf
* @param name Name of the job
* @param progress
* @return The newly created writer instance.
* @throws IOException When creating the writer fails.
*/
@Override
public RecordWriter getRecordWriter(FileSystem ignored, JobConf job, String name,
Progressable progress)
throws IOException {
// expecting exactly one path
TableName tableName = TableName.valueOf(job.get(OUTPUT_TABLE));
BufferedMutator mutator = null;
// Connection is not closed. Dies with JVM. No possibility for cleanup.
Connection connection = ConnectionFactory.createConnection(job);
mutator = connection.getBufferedMutator(tableName);
// Clear write buffer on fail is true by default so no need to reset it.
return new TableRecordWriter(mutator);
}
@Override
public void checkOutputSpecs(FileSystem ignored, JobConf job)
throws FileAlreadyExistsException, InvalidJobConfException, IOException {
String tableName = job.get(OUTPUT_TABLE);
if (tableName == null) {
throw new IOException("Must specify table name");
}
}
}
| HBASE-16017 HBase TableOutputFormat has connection leak in getRecordWriter (Zhan Zhang)
| hbase-server/src/main/java/org/apache/hadoop/hbase/mapred/TableOutputFormat.java | HBASE-16017 HBase TableOutputFormat has connection leak in getRecordWriter (Zhan Zhang) | <ide><path>base-server/src/main/java/org/apache/hadoop/hbase/mapred/TableOutputFormat.java
<ide> */
<ide> protected static class TableRecordWriter implements RecordWriter<ImmutableBytesWritable, Put> {
<ide> private BufferedMutator m_mutator;
<del>
<add> private Connection connection;
<ide> /**
<ide> * Instantiate a TableRecordWriter with the HBase HClient for writing. Assumes control over the
<ide> * lifecycle of {@code conn}.
<ide> this.m_mutator = mutator;
<ide> }
<ide>
<add> public TableRecordWriter(JobConf job) throws IOException {
<add> // expecting exactly one path
<add> TableName tableName = TableName.valueOf(job.get(OUTPUT_TABLE));
<add> connection = ConnectionFactory.createConnection(job);
<add> m_mutator = connection.getBufferedMutator(tableName);
<add> }
<add>
<ide> public void close(Reporter reporter) throws IOException {
<ide> this.m_mutator.close();
<add> if (connection != null) {
<add> connection.close();
<add> connection = null;
<add> }
<ide> }
<ide>
<ide> public void write(ImmutableBytesWritable key, Put value) throws IOException {
<ide> public RecordWriter getRecordWriter(FileSystem ignored, JobConf job, String name,
<ide> Progressable progress)
<ide> throws IOException {
<del> // expecting exactly one path
<del> TableName tableName = TableName.valueOf(job.get(OUTPUT_TABLE));
<del> BufferedMutator mutator = null;
<del> // Connection is not closed. Dies with JVM. No possibility for cleanup.
<del> Connection connection = ConnectionFactory.createConnection(job);
<del> mutator = connection.getBufferedMutator(tableName);
<del> // Clear write buffer on fail is true by default so no need to reset it.
<del> return new TableRecordWriter(mutator);
<add> return new TableRecordWriter(job);
<ide> }
<ide>
<ide> @Override |
|
Java | mit | b0d6a7923725e07fc587056dcaf2052f8235f599 | 0 | FlareBot/FlareBot,binaryoverload/FlareBot,weeryan17/FlareBot | package com.bwfcwalshy.flarebot.music.extractors;
import com.arsenarsen.lavaplayerbridge.player.Player;
import com.arsenarsen.lavaplayerbridge.player.Track;
import com.bwfcwalshy.flarebot.FlareBot;
import com.bwfcwalshy.flarebot.MessageUtils;
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IUser;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class YouTubeExtractor implements Extractor {
public static final String YOUTUBE_URL = "https://www.youtube.com";
public static final String PLAYLIST_URL = "https://www.youtube.com/playlist?list=";
public static final String WATCH_URL = "https://www.youtube.com/watch?v=";
public static String ANY_YT_URL = "(?:https?://)?(?:(?:(?:(?:www\\.)?(?:youtube\\.com))/(?:(?:watch\\?v=([^?&\\n]+)(?:&(?:[^?&\\n]+=(?:[^?&\\n]+)+))?)|(?:playlist\\?list=([^&?]+))(?:&[^&]*=[^&]+)?))|(?:youtu\\.be/(.*)))";
public static Pattern YT_PATTERN = Pattern.compile(ANY_YT_URL);
public static final String ANY_PLAYLIST = "https?://(www\\.)?youtube\\.com/playlist\\?list=([0-9A-z+-]*)(&.*=.*)*";
private static final Pattern MIX_PATTERN = Pattern.compile("(?:https?://)(?:www\\.)youtube\\.com/watch\\?v=(.+)&list=RD(.+)");
@Override
public Class<? extends AudioSourceManager> getSourceManagerClass() {
return YoutubeAudioSourceManager.class;
}
@Override
public void process(String input, Player player, IMessage message, IUser user) throws Exception {
Document doc = Jsoup.connect(input).get();
if (doc.title().equals("YouTube")) {
MessageUtils.editMessage(message, "Unable to retrieve the video/playlist :-(");
return;
}
String title = doc.title().substring(0, doc.title().length() - 10);
if (input.matches(ANY_PLAYLIST) || isMix(input)) {
ProcessBuilder bld = new ProcessBuilder("youtube-dl", "-i", "-4", "-J", "--flat-playlist", input);
Playlist playlist = FlareBot.GSON.fromJson(new InputStreamReader(bld.start().getInputStream()), Playlist.class);
int c = 0;
for (Playlist.PlaylistEntry e : playlist) {
if (e != null && e.id != null) {
try {
if (e.title == null) {
String title2 = Jsoup.connect(WATCH_URL + e.id).get().title();
if (title2.equals("YouTube"))
continue;
e.title = title2.substring(0, doc.title().length() - 10);
c++; // I want to increment my knowledge in it
}
Track track = new Track((AudioTrack) player.resolve(WATCH_URL + e.id));
track.getMeta().put("name", e.title);
track.getMeta().put("id", e.id);
player.queue(track);
} catch (Exception ignored) {
}
}
}
MessageUtils.editMessage(MessageUtils.getEmbed(user)
.withDesc("Added the playlist [**" + title + "**]("
+ WATCH_URL + input + ") to the playlist!")
.appendField("Songs:", String.valueOf(c), false).build(), message);
} else {
try {
if (input.contains("&"))
input = input.substring(input.indexOf('&'));
Track track = new Track((AudioTrack) player.resolve(input));
track.getMeta().put("name", title);
if (input.contains("&")) input = input.substring(input.indexOf('&'));
input = input.substring(input.indexOf("?v=") + 3);
track.getMeta().put("id", input);
player.queue(track);
MessageUtils.editMessage(MessageUtils.getEmbed(user)
.withDesc("Added the video [**" + title + "**]("
+ WATCH_URL + track.getTrack().getIdentifier() + ") to the playlist!").build(), message);
} catch (FriendlyException e) {
MessageUtils.editMessage(MessageUtils.getEmbed(user)
.withDesc("Could not get that song!").appendField("YouTube said: ", (e.getMessage().contains("\n") ?
e.getMessage().substring(e.getMessage().indexOf('\n')) :
e.getMessage()), true).build(), message);
}
}
}
@Override
public boolean valid(String input) {
return input.matches(ANY_YT_URL) || isMix(input);
}
public boolean isMix(String url) {
Matcher m = MIX_PATTERN.matcher(url);
return m.matches() && m.group(1).equals(m.group(2));
}
public static class Playlist implements Iterable<Playlist.PlaylistEntry> {
public List<Playlist.PlaylistEntry> entries = new ArrayList<>();
@Override
public Iterator<PlaylistEntry> iterator() {
return entries.iterator();
}
public static class PlaylistEntry {
public String id;
public String title;
}
public String title;
}
}
| src/main/java/com/bwfcwalshy/flarebot/music/extractors/YouTubeExtractor.java | package com.bwfcwalshy.flarebot.music.extractors;
import com.arsenarsen.lavaplayerbridge.player.Player;
import com.arsenarsen.lavaplayerbridge.player.Track;
import com.bwfcwalshy.flarebot.FlareBot;
import com.bwfcwalshy.flarebot.MessageUtils;
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IUser;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class YouTubeExtractor implements Extractor {
public static final String YOUTUBE_URL = "https://www.youtube.com";
public static final String PLAYLIST_URL = "https://www.youtube.com/playlist?list=";
public static final String WATCH_URL = "https://www.youtube.com/watch?v=";
public static String ANY_YT_URL = "(?:https?://)?(?:(?:(?:(?:www\\.)?(?:youtube\\.com))/(?:(?:watch\\?v=([^?&\\n]+)(?:&(?:[^?&\\n]+=(?:[^?&\\n]+)+))?)|(?:playlist\\?list=([^&?]+))(?:&[^&]*=[^&]+)?))|(?:youtu\\.be/(.*)))";
public static Pattern YT_PATTERN = Pattern.compile(ANY_YT_URL);
public static final String ANY_PLAYLIST = "https?://(www\\.)?youtube\\.com/playlist\\?list=([0-9A-z+-]*)(&.*=.*)*";
private static final Pattern MIX_PATTERN = Pattern.compile("(?:https?://)(?:www\\.)youtube\\.com/watch\\?v=(.+)&list=RD(.+)");
@Override
public Class<? extends AudioSourceManager> getSourceManagerClass() {
return YoutubeAudioSourceManager.class;
}
@Override
public void process(String input, Player player, IMessage message, IUser user) throws Exception {
Document doc = Jsoup.connect(input).get();
if (doc.title().equals("YouTube")) {
MessageUtils.editMessage(message, "Unable to retrieve the video/playlist :-(");
return;
}
String title = doc.title().substring(0, doc.title().length() - 10);
if (input.matches(ANY_PLAYLIST) || isMix(input)) {
ProcessBuilder bld = new ProcessBuilder("youtube-dl", "-i", "-4", "-J", "--flat-playlist", input);
Playlist playlist = FlareBot.GSON.fromJson(new InputStreamReader(bld.start().getInputStream()), Playlist.class);
int c = 0;
for (Playlist.PlaylistEntry e : playlist) {
if (e != null && e.id != null) {
try {
if (e.title == null) {
String title2 = Jsoup.connect(WATCH_URL + e.id).get().title();
if (title2.equals("YouTube"))
continue;
e.title = title2.substring(0, doc.title().length() - 10);
c++; // I want to increment my knowledge in it
}
Track track = new Track((AudioTrack) player.resolve(WATCH_URL + e.id));
track.getMeta().put("name", e.title);
track.getMeta().put("id", e.id);
player.queue(track);
} catch (Exception ignored) {
}
}
}
MessageUtils.editMessage(MessageUtils.getEmbed(user)
.withDesc("Added the playlist [**" + title + "**]("
+ WATCH_URL + input + ") to the playlist!")
.appendField("Songs:", String.valueOf(c), false).build(), message);
} else {
try {
Track track = new Track((AudioTrack) player.resolve(input));
track.getMeta().put("name", title);
if (input.contains("&")) input = input.substring(input.indexOf('&'));
input = input.substring(input.indexOf("?v=") + 3);
track.getMeta().put("id", input);
player.queue(track);
MessageUtils.editMessage(MessageUtils.getEmbed(user)
.withDesc("Added the video [**" + title + "**]("
+ WATCH_URL + track.getTrack().getIdentifier() + ") to the playlist!").build(), message);
} catch (FriendlyException e) {
MessageUtils.editMessage(MessageUtils.getEmbed(user)
.withDesc("Could not get that song!").appendField("YouTube said: ", (e.getMessage().contains("\n") ?
e.getMessage().substring(e.getMessage().indexOf('\n')) :
e.getMessage()), true).build(), message);
}
}
}
@Override
public boolean valid(String input) {
return input.matches(ANY_YT_URL) || isMix(input);
}
public boolean isMix(String url) {
Matcher m = MIX_PATTERN.matcher(url);
return m.matches() && m.group(1).equals(m.group(2));
}
public static class Playlist implements Iterable<Playlist.PlaylistEntry> {
public List<Playlist.PlaylistEntry> entries = new ArrayList<>();
@Override
public Iterator<PlaylistEntry> iterator() {
return entries.iterator();
}
public static class PlaylistEntry {
public String id;
public String title;
}
public String title;
}
}
| Make sure YouTubeExtractor.java ignores additional URL parameters
| src/main/java/com/bwfcwalshy/flarebot/music/extractors/YouTubeExtractor.java | Make sure YouTubeExtractor.java ignores additional URL parameters | <ide><path>rc/main/java/com/bwfcwalshy/flarebot/music/extractors/YouTubeExtractor.java
<ide> .appendField("Songs:", String.valueOf(c), false).build(), message);
<ide> } else {
<ide> try {
<add> if (input.contains("&"))
<add> input = input.substring(input.indexOf('&'));
<ide> Track track = new Track((AudioTrack) player.resolve(input));
<ide> track.getMeta().put("name", title);
<ide> if (input.contains("&")) input = input.substring(input.indexOf('&')); |
|
Java | apache-2.0 | 437153dfda6ca325228514904c936ffca211b880 | 0 | epiphany27/SeriesGuide,hoanganhx86/SeriesGuide,UweTrottmann/SeriesGuide,r00t-user/SeriesGuide,UweTrottmann/SeriesGuide,artemnikitin/SeriesGuide,0359xiaodong/SeriesGuide | /*
* Copyright 2012 Uwe Trottmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.battlelancer.seriesguide.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.actionbarsherlock.app.SherlockFragment;
import com.google.analytics.tracking.android.EasyTracker;
import com.uwetrottmann.seriesguide.R;
/**
* Helps the user to get familiar with the basic functions of SeriesGuide. Shown
* only on first start up.
*
* @author Uwe Trottmann
*/
public class FirstRunFragment extends SherlockFragment {
private static final String PREF_KEY_FIRSTRUN = "accepted_eula";
protected static final String TAG = "First Run";
private OnFirstRunDismissedListener mListener;
public static FirstRunFragment newInstance() {
FirstRunFragment f = new FirstRunFragment();
return f;
}
public interface OnFirstRunDismissedListener {
public void onFirstRunDismissed();
}
public static boolean hasSeenFirstRunFragment(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(PREF_KEY_FIRSTRUN, false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.firstrun_fragment, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFirstRunDismissedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFirstRunDismissedListener");
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// add button
getView().findViewById(R.id.addbutton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
fireTrackerEvent("Add show");
startActivity(new Intent(getActivity(), AddActivity.class));
setFirstRunDismissed();
}
});
// language chooser
Spinner spinner = (Spinner) getView().findViewById(R.id.welcome_setuplanguage);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.languages, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnLanguageSelectedListener());
// trakt connect button
getView().findViewById(R.id.welcome_setuptrakt).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
fireTrackerEvent("Connect trakt");
Intent i = new Intent(getActivity(), ConnectTraktActivity.class);
startActivity(i);
}
});
// dismiss button
getView().findViewById(R.id.dismissButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
fireTrackerEvent("Dismiss");
setFirstRunDismissed();
}
});
// peek menu
final Runnable peekDoneRunnable = new Runnable() {
public void run() {
FragmentActivity activity = getActivity();
if (activity != null) {
((BaseActivity) activity).showContent();
}
}
};
final Runnable peekRunnable = new Runnable() {
public void run() {
FragmentActivity activity = getActivity();
if (activity != null) {
((BaseActivity) activity).showMenu();
getView().postDelayed(peekDoneRunnable, 2000);
}
}
};
getView().postDelayed(peekRunnable, 2000);
}
@Override
public void onStart() {
super.onStart();
EasyTracker.getTracker().sendView(TAG);
}
private void setFirstRunDismissed() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getActivity());
prefs.edit().putBoolean(PREF_KEY_FIRSTRUN, true).commit();
// display shows fragment again, better use an interface!
mListener.onFirstRunDismissed();
}
public class OnLanguageSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getActivity());
final String value = getResources().getStringArray(R.array.languageData)[pos];
prefs.edit().putString(SeriesGuidePreferences.KEY_LANGUAGE, value).commit();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
private void fireTrackerEvent(String label) {
EasyTracker.getTracker().sendEvent(TAG, "Click", label, (long) 0);
}
}
| SeriesGuide/src/com/battlelancer/seriesguide/ui/FirstRunFragment.java | /*
* Copyright 2012 Uwe Trottmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.battlelancer.seriesguide.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.actionbarsherlock.app.SherlockFragment;
import com.google.analytics.tracking.android.EasyTracker;
import com.uwetrottmann.seriesguide.R;
/**
* Helps the user to get familiar with the basic functions of SeriesGuide. Shown
* only on first start up.
*
* @author Uwe Trottmann
*/
public class FirstRunFragment extends SherlockFragment {
private static final String PREF_KEY_FIRSTRUN = "accepted_eula";
protected static final String TAG = "FirstRunFragment";
private OnFirstRunDismissedListener mListener;
public static FirstRunFragment newInstance() {
FirstRunFragment f = new FirstRunFragment();
return f;
}
public interface OnFirstRunDismissedListener {
public void onFirstRunDismissed();
}
public static boolean hasSeenFirstRunFragment(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(PREF_KEY_FIRSTRUN, false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.firstrun_fragment, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFirstRunDismissedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFirstRunDismissedListener");
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// add button
getView().findViewById(R.id.addbutton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddActivity.class));
setFirstRunDismissed();
}
});
// language chooser
Spinner spinner = (Spinner) getView().findViewById(R.id.welcome_setuplanguage);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.languages, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnLanguageSelectedListener());
// trakt connect button
getView().findViewById(R.id.welcome_setuptrakt).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), ConnectTraktActivity.class);
startActivity(i);
EasyTracker.getTracker().trackEvent(TAG, "Click", "Connect trakt", (long) 0);
}
});
// dismiss button
getView().findViewById(R.id.dismissButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setFirstRunDismissed();
}
});
// peek menu
final Runnable peekDoneRunnable = new Runnable() {
public void run() {
FragmentActivity activity = getActivity();
if (activity != null) {
((BaseActivity) activity).showContent();
}
}
};
final Runnable peekRunnable = new Runnable() {
public void run() {
FragmentActivity activity = getActivity();
if (activity != null) {
((BaseActivity) activity).showMenu();
getView().postDelayed(peekDoneRunnable, 2000);
}
}
};
getView().postDelayed(peekRunnable, 2000);
}
private void setFirstRunDismissed() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getActivity());
prefs.edit().putBoolean(PREF_KEY_FIRSTRUN, true).commit();
// display shows fragment again, better use an interface!
mListener.onFirstRunDismissed();
}
public class OnLanguageSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getActivity());
final String value = getResources().getStringArray(R.array.languageData)[pos];
prefs.edit().putString(SeriesGuidePreferences.KEY_LANGUAGE, value).commit();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
}
| New events for first run fragment.
| SeriesGuide/src/com/battlelancer/seriesguide/ui/FirstRunFragment.java | New events for first run fragment. | <ide><path>eriesGuide/src/com/battlelancer/seriesguide/ui/FirstRunFragment.java
<ide>
<ide> private static final String PREF_KEY_FIRSTRUN = "accepted_eula";
<ide>
<del> protected static final String TAG = "FirstRunFragment";
<add> protected static final String TAG = "First Run";
<ide>
<ide> private OnFirstRunDismissedListener mListener;
<ide>
<ide> getView().findViewById(R.id.addbutton).setOnClickListener(new OnClickListener() {
<ide> @Override
<ide> public void onClick(View v) {
<add> fireTrackerEvent("Add show");
<ide> startActivity(new Intent(getActivity(), AddActivity.class));
<ide> setFirstRunDismissed();
<ide> }
<ide> getView().findViewById(R.id.welcome_setuptrakt).setOnClickListener(new OnClickListener() {
<ide> @Override
<ide> public void onClick(View v) {
<add> fireTrackerEvent("Connect trakt");
<add>
<ide> Intent i = new Intent(getActivity(), ConnectTraktActivity.class);
<ide> startActivity(i);
<del>
<del> EasyTracker.getTracker().trackEvent(TAG, "Click", "Connect trakt", (long) 0);
<ide> }
<ide> });
<ide>
<ide> getView().findViewById(R.id.dismissButton).setOnClickListener(new OnClickListener() {
<ide> @Override
<ide> public void onClick(View v) {
<add> fireTrackerEvent("Dismiss");
<ide> setFirstRunDismissed();
<ide> }
<ide> });
<ide> getView().postDelayed(peekRunnable, 2000);
<ide> }
<ide>
<add> @Override
<add> public void onStart() {
<add> super.onStart();
<add> EasyTracker.getTracker().sendView(TAG);
<add> }
<add>
<ide> private void setFirstRunDismissed() {
<ide> SharedPreferences prefs = PreferenceManager
<ide> .getDefaultSharedPreferences(getActivity());
<ide> }
<ide> }
<ide>
<add> private void fireTrackerEvent(String label) {
<add> EasyTracker.getTracker().sendEvent(TAG, "Click", label, (long) 0);
<add> }
<ide> } |
|
Java | agpl-3.0 | 3a4bbf8be133769f84424a59be6121bd9db3d1f0 | 0 | arenaoftitans/arena-of-titans,arenaoftitans/arena-of-titans,arenaoftitans/arena-of-titans | package com.derniereligne.engine.cards;
import com.derniereligne.engine.board.Square;
import java.util.Set;
/**
* <b>Interface used to to abstract the way we get probable squares from the board.</b>
*
* @author "Dernière Ligne" first development team
*/
@FunctionalInterface
public interface ProbableSquaresGetter {
/**
* <b>Returns the set of the probable squares.</b>
*
* @param currentSquare
* The start square.
*
* @return
* Set of probable squares.
*/
public Set<Square> get(Square currentSquare);
}
| src/main/java/com/derniereligne/engine/cards/ProbableSquaresGetter.java | package com.derniereligne.engine.cards;
import com.derniereligne.engine.board.Square;
import java.util.Set;
/**
* <b>Interface used to to abstract the way we get probable squares from the board.</b>
*
* @author "Dernière Ligne" first development team
*/
@FunctionalInterface
public interface ProbableSquaresGetter {
/**
*
* @param currentSquare
* @return
*/
public Set<Square> get(Square currentSquare);
}
| doc(ProbableSquaresGetter): improve javadoc.
| src/main/java/com/derniereligne/engine/cards/ProbableSquaresGetter.java | doc(ProbableSquaresGetter): improve javadoc. | <ide><path>rc/main/java/com/derniereligne/engine/cards/ProbableSquaresGetter.java
<ide> public interface ProbableSquaresGetter {
<ide>
<ide> /**
<add> * <b>Returns the set of the probable squares.</b>
<ide> *
<ide> * @param currentSquare
<add> * The start square.
<add> *
<ide> * @return
<add> * Set of probable squares.
<ide> */
<ide> public Set<Square> get(Square currentSquare);
<ide> |
|
JavaScript | mit | 58454fbab46e0d95368307b92b651928024175fb | 0 | quasarframework/quasar,fsgiudice/quasar,fsgiudice/quasar,rstoenescu/quasar-framework,rstoenescu/quasar-framework,pdanpdan/quasar,rstoenescu/quasar-framework,quasarframework/quasar,quasarframework/quasar,pdanpdan/quasar,pdanpdan/quasar,quasarframework/quasar,fsgiudice/quasar,pdanpdan/quasar | import Vue from 'vue'
import QField from '../field/QField.js'
import QIcon from '../icon/QIcon.js'
import QChip from '../chip/QChip.js'
import QItem from '../list/QItem.js'
import QItemSection from '../list/QItemSection.js'
import QItemLabel from '../list/QItemLabel.js'
import QMenu from '../menu/QMenu.js'
import QDialog from '../dialog/QDialog.js'
import { isDeepEqual } from '../../utils/is.js'
import { stop, prevent, stopAndPrevent } from '../../utils/event.js'
import { normalizeToInterval } from '../../utils/format.js'
import VirtualScroll from '../../mixins/virtual-scroll.js'
import CompositionMixin from '../../mixins/composition.js'
const validateNewValueMode = v => ['add', 'add-unique', 'toggle'].includes(v)
export default Vue.extend({
name: 'QSelect',
mixins: [ QField, VirtualScroll, CompositionMixin ],
props: {
value: {
required: true
},
multiple: Boolean,
displayValue: [String, Number],
displayValueSanitize: Boolean,
dropdownIcon: String,
options: {
type: Array,
default: () => []
},
optionValue: [Function, String],
optionLabel: [Function, String],
optionDisable: [Function, String],
hideSelected: Boolean,
hideDropdownIcon: Boolean,
fillInput: Boolean,
maxValues: [Number, String],
optionsDense: Boolean,
optionsDark: Boolean,
optionsSelectedClass: String,
optionsCover: Boolean,
optionsSanitize: Boolean,
popupContentClass: String,
popupContentStyle: [String, Array, Object],
useInput: Boolean,
useChips: Boolean,
newValueMode: {
type: String,
validator: validateNewValueMode
},
mapOptions: Boolean,
emitValue: Boolean,
inputDebounce: {
type: [Number, String],
default: 500
},
inputClass: [Array, String, Object],
inputStyle: [Array, String, Object],
transitionShow: String,
transitionHide: String,
behavior: {
type: String,
validator: v => ['default', 'menu', 'dialog'].includes(v),
default: 'default'
}
},
data () {
return {
menu: false,
dialog: false,
optionIndex: -1,
inputValue: '',
dialogFieldFocused: false
}
},
watch: {
innerValue: {
handler () {
if (
this.useInput === true &&
this.fillInput === true &&
this.multiple !== true &&
// Prevent re-entering in filter while filtering
// Also prevent clearing inputValue while filtering
this.innerLoading !== true &&
((this.dialog !== true && this.menu !== true) || this.hasValue !== true)
) {
this.__resetInputValue()
if (this.dialog === true || this.menu === true) {
this.filter('')
}
}
},
immediate: true
},
menu (show) {
this.__updateMenu(show)
}
},
computed: {
virtualScrollLength () {
return Array.isArray(this.options)
? this.options.length
: 0
},
fieldClass () {
return `q-select q-field--auto-height q-select--with${this.useInput !== true ? 'out' : ''}-input`
},
computedInputClass () {
if (this.hideSelected === true || this.innerValue.length === 0) {
return this.inputClass
}
return this.inputClass === void 0
? 'q-select__input--padding'
: [this.inputClass, 'q-select__input--padding']
},
menuContentClass () {
return (this.virtualScrollHorizontal === true ? 'q-virtual-scroll--horizontal' : '') +
(this.popupContentClass ? ' ' + this.popupContentClass : '')
},
menuClass () {
return this.menuContentClass + (this.optionsDark === true ? ' q-select__menu--dark' : '')
},
innerValue () {
const
mapNull = this.mapOptions === true && this.multiple !== true,
val = this.value !== void 0 && (this.value !== null || mapNull === true)
? (this.multiple === true && Array.isArray(this.value) ? this.value : [ this.value ])
: []
return this.mapOptions === true && Array.isArray(this.options) === true
? (
this.value === null && mapNull === true
? val.map(v => this.__getOption(v)).filter(v => v !== null)
: val.map(v => this.__getOption(v))
)
: val
},
noOptions () {
return this.virtualScrollLength === 0
},
selectedString () {
return this.innerValue
.map(opt => this.__getOptionLabel(opt))
.join(', ')
},
displayAsText () {
return this.displayValueSanitize === true || (
this.displayValue === void 0 && (
this.optionsSanitize === true ||
this.innerValue.some(opt => opt !== null && opt.sanitize === true)
)
)
},
selectedScope () {
const tabindex = this.focused === true ? 0 : -1
return this.innerValue.map((opt, i) => ({
index: i,
opt,
sanitize: this.optionsSanitize === true || opt.sanitize === true,
selected: true,
removeAtIndex: this.__removeAtIndexAndFocus,
toggleOption: this.toggleOption,
tabindex
}))
},
optionScope () {
if (this.virtualScrollLength === 0) {
return []
}
const { from, to } = this.virtualScrollSliceRange
return this.options.slice(from, to).map((opt, i) => {
const disable = this.__isDisabled(opt)
const index = from + i
const itemProps = {
clickable: true,
active: false,
activeClass: this.optionsSelectedClass,
manualFocus: true,
focused: false,
disable,
tabindex: -1,
dense: this.optionsDense,
dark: this.optionsDark
}
if (disable !== true) {
this.__isSelected(opt) === true && (itemProps.active = true)
this.optionIndex === index && (itemProps.focused = true)
}
const itemEvents = {
click: () => { this.toggleOption(opt) }
}
if (this.$q.platform.is.desktop === true) {
itemEvents.mousemove = () => { this.setOptionIndex(index) }
}
return {
index,
opt,
sanitize: this.optionsSanitize === true || opt.sanitize === true,
selected: itemProps.active,
focused: itemProps.focused,
toggleOption: this.toggleOption,
setOptionIndex: this.setOptionIndex,
itemProps,
itemEvents
}
})
},
dropdownArrowIcon () {
return this.dropdownIcon !== void 0
? this.dropdownIcon
: this.$q.iconSet.arrow.dropdown
},
squaredMenu () {
return this.optionsCover === false &&
this.outlined !== true &&
this.standout !== true &&
this.borderless !== true &&
this.rounded !== true
}
},
methods: {
removeAtIndex (index) {
if (index > -1 && index < this.innerValue.length) {
if (this.multiple === true) {
const model = [].concat(this.value)
this.$emit('remove', { index, value: model.splice(index, 1) })
this.$emit('input', model)
}
else {
this.$emit('input', null)
}
}
},
__removeAtIndexAndFocus (index) {
this.removeAtIndex(index)
this.__focus()
},
add (opt, unique) {
const val = this.emitValue === true
? this.__getOptionValue(opt)
: opt
if (this.multiple !== true) {
this.$emit('input', val)
return
}
if (this.innerValue.length === 0) {
this.$emit('add', { index: 0, value: val })
this.$emit('input', this.multiple === true ? [ val ] : val)
return
}
if (unique === true && this.__isSelected(opt) === true) {
return
}
const model = [].concat(this.value)
if (this.maxValues !== void 0 && model.length >= this.maxValues) {
return
}
this.$emit('add', { index: model.length, value: val })
model.push(val)
this.$emit('input', model)
},
toggleOption (opt) {
if (this.editable !== true || opt === void 0 || this.__isDisabled(opt) === true) {
return
}
const optValue = this.__getOptionValue(opt)
if (this.multiple !== true) {
this.updateInputValue(
this.fillInput === true ? this.__getOptionLabel(opt) : '',
true,
true
)
this.hidePopup()
if (isDeepEqual(this.__getOptionValue(this.value), optValue) !== true) {
this.$emit('input', this.emitValue === true ? optValue : opt)
}
return
}
(this.hasDialog !== true || this.dialogFieldFocused === true) && this.__focus()
if (this.innerValue.length === 0) {
const val = this.emitValue === true ? optValue : opt
this.$emit('add', { index: 0, value: val })
this.$emit('input', this.multiple === true ? [ val ] : val)
return
}
const
model = [].concat(this.value),
index = this.value.findIndex(v => isDeepEqual(this.__getOptionValue(v), optValue))
if (index > -1) {
this.$emit('remove', { index, value: model.splice(index, 1) })
}
else {
if (this.maxValues !== void 0 && model.length >= this.maxValues) {
return
}
const val = this.emitValue === true ? optValue : opt
this.$emit('add', { index: model.length, value: val })
model.push(val)
}
this.$emit('input', model)
},
setOptionIndex (index) {
if (this.$q.platform.is.desktop !== true) { return }
const val = index > -1 && index < this.virtualScrollLength
? index
: -1
if (this.optionIndex !== val) {
this.optionIndex = val
}
},
__getOption (value) {
return this.options.find(opt => isDeepEqual(this.__getOptionValue(opt), value)) || value
},
__getOptionValue (opt) {
if (typeof this.optionValue === 'function') {
return this.optionValue(opt)
}
if (Object(opt) === opt) {
return typeof this.optionValue === 'string'
? opt[this.optionValue]
: opt.value
}
return opt
},
__getOptionLabel (opt) {
if (typeof this.optionLabel === 'function') {
return this.optionLabel(opt)
}
if (Object(opt) === opt) {
return typeof this.optionLabel === 'string'
? opt[this.optionLabel]
: opt.label
}
return opt
},
__isDisabled (opt) {
if (typeof this.optionDisable === 'function') {
return this.optionDisable(opt) === true
}
if (Object(opt) === opt) {
return typeof this.optionDisable === 'string'
? opt[this.optionDisable] === true
: opt.disable === true
}
return false
},
__isSelected (opt) {
const val = this.__getOptionValue(opt)
return this.innerValue
.find(v => isDeepEqual(this.__getOptionValue(v), val)) !== void 0
},
__onTargetKeyup (e) {
// if ESC and we have an opened menu
// then stop propagation (might be caught by a QDialog
// and so it will also close the QDialog, which is wrong)
if (e.keyCode === 27 && this.menu === true) {
stop(e)
// on ESC we need to close the dialog also
this.hidePopup()
}
this.$emit('keyup', e)
},
__onTargetKeypress (e) {
this.$emit('keypress', e)
},
__onTargetKeydown (e) {
this.$emit('keydown', e)
const tabShouldSelect = e.shiftKey !== true && this.multiple !== true && this.optionIndex > -1
// escape
if (e.keyCode === 27) {
return
}
// tab
if (e.keyCode === 9 && tabShouldSelect === false) {
this.__closeMenu()
return
}
if (e.target !== this.$refs.target) { return }
// down
if (
e.keyCode === 40 &&
this.innerLoading !== true &&
this.menu === false
) {
stopAndPrevent(e)
this.showPopup()
return
}
// backspace
if (
e.keyCode === 8 &&
this.multiple === true &&
this.inputValue.length === 0 &&
Array.isArray(this.value)
) {
this.removeAtIndex(this.value.length - 1)
return
}
// up, down
const optionsLength = this.virtualScrollLength
if (e.keyCode === 38 || e.keyCode === 40) {
stopAndPrevent(e)
if (this.menu === true) {
let index = this.optionIndex
do {
index = normalizeToInterval(
index + (e.keyCode === 38 ? -1 : 1),
-1,
optionsLength - 1
)
}
while (index !== -1 && index !== this.optionIndex && this.__isDisabled(this.options[index]) === true)
if (this.optionIndex !== index) {
this.setOptionIndex(index)
this.scrollTo(index)
if (index >= 0 && this.useInput === true && this.fillInput === true) {
const inputValue = this.__getOptionLabel(this.options[index])
if (this.inputValue !== inputValue) {
this.inputValue = inputValue
}
}
}
}
}
// keyboard search when not having use-input
if (optionsLength > 0 && this.useInput !== true && e.keyCode >= 48 && e.keyCode <= 90) {
this.menu !== true && this.showPopup(e)
// clear search buffer if expired
if (this.searchBuffer === void 0 || this.searchBufferExp < Date.now()) {
this.searchBuffer = ''
}
const
char = String.fromCharCode(e.keyCode).toLocaleLowerCase(),
keyRepeat = this.searchBuffer.length === 1 && this.searchBuffer[0] === char
this.searchBufferExp = Date.now() + 1500
if (keyRepeat === false) {
this.searchBuffer += char
}
const searchRe = new RegExp('^' + this.searchBuffer.split('').join('.*'), 'i')
let index = this.optionIndex
if (keyRepeat === true || searchRe.test(this.__getOptionLabel(this.options[index])) !== true) {
do {
index = normalizeToInterval(index + 1, -1, optionsLength - 1)
}
while (index !== this.optionIndex && (
this.__isDisabled(this.options[index]) === true ||
searchRe.test(this.__getOptionLabel(this.options[index])) !== true
))
}
if (this.optionIndex !== index) {
this.$nextTick(() => {
this.setOptionIndex(index)
this.scrollTo(index)
if (index >= 0 && this.useInput === true && this.fillInput === true) {
const inputValue = this.__getOptionLabel(this.options[index])
if (this.inputValue !== inputValue) {
this.inputValue = inputValue
}
}
})
}
return
}
// enter, space (when not using use-input), or tab (when not using multiple and option selected)
if (
e.target !== this.$refs.target ||
(
e.keyCode !== 13 &&
(this.useInput === true || e.keyCode !== 32) &&
(tabShouldSelect === false || e.keyCode !== 9)
)
) { return }
e.keyCode !== 9 && stopAndPrevent(e)
if (this.optionIndex > -1 && this.optionIndex < optionsLength) {
this.toggleOption(this.options[this.optionIndex])
return
}
if (
this.inputValue.length > 0 &&
(this.newValueMode !== void 0 || this.$listeners['new-value'] !== void 0)
) {
const done = (val, mode) => {
if (mode) {
if (validateNewValueMode(mode) !== true) {
console.error('QSelect: invalid new value mode - ' + mode)
return
}
}
else {
mode = this.newValueMode
}
if (val !== void 0 && val !== null) {
this[mode === 'toggle' ? 'toggleOption' : 'add'](
val,
mode === 'add-unique'
)
}
this.updateInputValue('', this.multiple !== true, true)
}
if (this.$listeners['new-value'] !== void 0) {
this.$emit('new-value', this.inputValue, done)
if (this.multiple !== true) {
return
}
}
else {
done(this.inputValue)
}
}
if (this.menu === true) {
this.__closeMenu()
}
else if (this.innerLoading !== true) {
this.showPopup()
}
},
__getVirtualScrollEl () {
return this.hasDialog === true
? this.$refs.menuContent
: (
this.$refs.menu !== void 0 && this.$refs.menu.__portal !== void 0
? this.$refs.menu.__portal.$el
: void 0
)
},
__getVirtualScrollTarget () {
return this.__getVirtualScrollEl()
},
__getSelection (h, fromDialog) {
if (this.hideSelected === true) {
return fromDialog !== true && this.hasDialog === true
? [
h('span', {
domProps: {
'textContent': this.inputValue
}
})
]
: []
}
if (this.$scopedSlots['selected-item'] !== void 0) {
return this.selectedScope.map(scope => this.$scopedSlots['selected-item'](scope))
}
if (this.$scopedSlots.selected !== void 0) {
return this.$scopedSlots.selected()
}
if (this.useChips === true) {
const tabindex = this.focused === true ? 0 : -1
return this.selectedScope.map((scope, i) => h(QChip, {
key: 'option-' + i,
props: {
removable: this.__isDisabled(scope.opt) !== true,
dense: true,
textColor: this.color,
tabindex
},
on: {
remove () { scope.removeAtIndex(i) }
}
}, [
h('span', {
domProps: {
[scope.sanitize === true ? 'textContent' : 'innerHTML']: this.__getOptionLabel(scope.opt)
}
})
]))
}
return [
h('span', {
domProps: {
[this.displayAsText ? 'textContent' : 'innerHTML']: this.displayValue !== void 0
? this.displayValue
: this.selectedString
}
})
]
},
__getControl (h, fromDialog) {
const child = this.__getSelection(h, fromDialog)
if (this.useInput === true && (fromDialog === true || this.hasDialog === false)) {
child.push(this.__getInput(h, fromDialog))
}
else if (this.editable === true) {
const isShadowField = this.hasDialog === true && fromDialog !== true && this.menu === true
child.push(h('div', {
// there can be only one (when dialog is opened the control in dialog should be target)
ref: isShadowField === true ? void 0 : 'target',
staticClass: 'no-outline',
attrs: {
tabindex: 0,
id: isShadowField === true ? void 0 : this.targetUid
},
on: {
keydown: this.__onTargetKeydown,
keyup: this.__onTargetKeyup,
keypress: this.__onTargetKeypress
}
}))
}
return h('div', { staticClass: 'q-field__native row items-center', attrs: this.$attrs }, child)
},
__getOptions (h) {
if (this.menu !== true) {
return void 0
}
const fn = this.$scopedSlots.option !== void 0
? this.$scopedSlots.option
: scope => h(QItem, {
key: scope.index,
props: scope.itemProps,
on: scope.itemEvents
}, [
h(QItemSection, [
h(QItemLabel, {
domProps: {
[scope.sanitize === true ? 'textContent' : 'innerHTML']: this.__getOptionLabel(scope.opt)
}
})
])
])
let options = this.__padVirtualScroll(h, 'div', this.optionScope.map(fn))
if (this.$scopedSlots['before-options'] !== void 0) {
options = this.$scopedSlots['before-options']().concat(options)
}
if (this.$scopedSlots['after-options'] !== void 0) {
options = options.concat(this.$scopedSlots['after-options']())
}
return options
},
__getInnerAppend (h) {
return this.loading !== true && this.innerLoading !== true && this.hideDropdownIcon !== true
? [
h(QIcon, {
staticClass: 'q-select__dropdown-icon',
props: { name: this.dropdownArrowIcon }
})
]
: null
},
__getInput (h, fromDialog) {
const on = {
input: this.__onInput,
// Safari < 10.2 & UIWebView doesn't fire compositionend when
// switching focus before confirming composition choice
// this also fixes the issue where some browsers e.g. iOS Chrome
// fires "change" instead of "input" on autocomplete.
change: this.__onChange,
keydown: this.__onTargetKeydown,
keyup: this.__onTargetKeyup,
keypress: this.__onTargetKeypress
}
on.compositionstart = on.compositionupdate = on.compositionend = this.__onComposition
if (this.hasDialog === true) {
on.click = stop
}
return h('input', {
ref: 'target',
staticClass: 'q-select__input q-placeholder col',
style: this.inputStyle,
class: this.computedInputClass,
domProps: { value: this.inputValue },
attrs: {
// required for Android in order to show ENTER key when in form
type: 'search',
...this.$attrs,
tabindex: 0,
autofocus: fromDialog === true ? false : this.autofocus,
id: this.targetUid,
disabled: this.disable === true,
readonly: this.readonly === true
},
on
})
},
__onChange (e) {
this.__onComposition(e)
},
__onInput (e) {
clearTimeout(this.inputTimer)
if (e && e.target && e.target.composing === true) {
return
}
this.inputValue = e.target.value || ''
// mark it here as user input so that if updateInputValue is called
// before filter is called the indicator is reset
this.userInputValue = true
if (this.$listeners.filter !== void 0) {
this.inputTimer = setTimeout(() => {
this.filter(this.inputValue)
}, this.inputDebounce)
}
},
updateInputValue (val, noFiltering, internal) {
this.userInputValue = internal !== true
if (this.useInput === true) {
if (this.inputValue !== val) {
this.inputValue = val
}
noFiltering !== true && this.filter(val)
}
},
filter (val) {
if (this.$listeners.filter === void 0 || this.focused !== true) {
return
}
if (this.innerLoading === true) {
this.$emit('filter-abort')
}
else {
this.innerLoading = true
}
if (
val !== '' &&
this.multiple !== true &&
this.innerValue.length > 0 &&
this.userInputValue !== true &&
val === this.__getOptionLabel(this.innerValue[0])
) {
val = ''
}
const filterId = setTimeout(() => {
this.menu === true && (this.menu = false)
}, 10)
clearTimeout(this.filterId)
this.filterId = filterId
this.$emit(
'filter',
val,
fn => {
if (this.focused === true && this.filterId === filterId) {
clearTimeout(this.filterId)
typeof fn === 'function' && fn()
this.$nextTick(() => {
this.innerLoading = false
if (this.menu === true) {
this.__updateMenu(true)
}
else {
this.menu = true
}
})
}
},
() => {
if (this.focused === true && this.filterId === filterId) {
clearTimeout(this.filterId)
this.innerLoading = false
}
this.menu === true && (this.menu = false)
}
)
},
__getControlEvents () {
const focusout = e => {
this.__onControlFocusout(e, () => {
this.__resetInputValue()
this.__closeMenu()
})
}
return {
focusin: this.__onControlFocusin,
focusout,
'popup-show': this.__onControlPopupShow,
'popup-hide': e => {
e !== void 0 && stop(e)
this.$emit('popup-hide', e)
this.hasPopupOpen = false
focusout(e)
},
click: e => {
// label from QField will propagate click on the input (except IE)
if (
this.hasDialog !== true &&
this.useInput === true &&
e.target.classList.contains('q-select__input') !== true
) {
return
}
if (this.hasDialog !== true && this.menu === true) {
this.__closeMenu()
this.$refs.target !== void 0 && this.$refs.target.focus()
}
else {
this.showPopup(e)
}
}
}
},
__getPopup (h) {
if (
this.editable !== false && (
this.dialog === true || // dialog always has menu displayed, so need to render it
this.noOptions !== true ||
this.$scopedSlots['no-option'] !== void 0
)
) {
return this[`__get${this.hasDialog === true ? 'Dialog' : 'Menu'}`](h)
}
},
__getMenu (h) {
const child = this.noOptions === true
? (
this.$scopedSlots['no-option'] !== void 0
? this.$scopedSlots['no-option']({ inputValue: this.inputValue })
: null
)
: this.__getOptions(h)
return h(QMenu, {
ref: 'menu',
props: {
value: this.menu,
fit: true,
cover: this.optionsCover === true && this.noOptions !== true && this.useInput !== true,
contentClass: this.menuClass,
contentStyle: this.popupContentStyle,
noParentEvent: true,
noRefocus: true,
noFocus: true,
square: this.squaredMenu,
transitionShow: this.transitionShow,
transitionHide: this.transitionHide,
separateClosePopup: true
},
on: {
'&scroll': this.__onVirtualScrollEvt,
'before-hide': this.__closeMenu
}
}, child)
},
__onDialogFieldFocus (e) {
stop(e)
this.$refs.target !== void 0 && this.$refs.target.focus()
this.dialogFieldFocused = true
window.scrollTo(window.pageXOffset || window.scrollX || document.body.scrollLeft || 0, 0)
},
__onDialogFieldBlur (e) {
stop(e)
this.$nextTick(() => {
this.dialogFieldFocused = false
})
},
__getDialog (h) {
const content = [
h(QField, {
staticClass: `col-auto ${this.fieldClass}`,
attrs: {
for: this.targetUid
},
props: {
...this.$props,
dark: this.optionsDark,
square: true,
loading: this.innerLoading,
filled: true,
stackLabel: this.inputValue.length > 0
},
on: {
...this.$listeners,
focus: this.__onDialogFieldFocus,
blur: this.__onDialogFieldBlur
},
scopedSlots: {
...this.$scopedSlots,
rawControl: () => this.__getControl(h, true),
before: void 0,
after: void 0
}
})
]
this.menu === true && content.push(
h('div', {
ref: 'menuContent',
staticClass: 'scroll',
class: this.menuContentClass,
style: this.popupContentStyle,
on: {
click: prevent,
'&scroll': this.__onVirtualScrollEvt
}
}, (
this.noOptions === true
? (
this.$scopedSlots['no-option'] !== void 0
? this.$scopedSlots['no-option']({ inputValue: this.inputValue })
: null
)
: this.__getOptions(h)
))
)
return h(QDialog, {
props: {
value: this.dialog,
noRefocus: true,
position: this.useInput === true ? 'top' : void 0,
transitionShow: this.transitionShowComputed,
transitionHide: this.transitionHide
},
on: {
'before-hide': this.__onDialogBeforeHide,
hide: this.__onDialogHide,
show: this.__onDialogShow
}
}, [
h('div', {
staticClass: 'q-select__dialog' +
(this.optionsDark === true ? ' q-select__menu--dark' : '') +
(this.dialogFieldFocused === true ? ' q-select__dialog--focused' : '')
}, content)
])
},
__onDialogBeforeHide () {
this.focused = false
},
__onDialogHide (e) {
this.hidePopup()
this.$emit('blur', e)
this.__resetInputValue()
},
__onDialogShow () {
const el = document.activeElement
// IE can have null document.activeElement
if (
(el === null || el.id !== this.targetUid) &&
this.$refs.target !== el
) {
this.$refs.target.focus()
}
},
__closeMenu () {
if (this.dialog === true) {
return
}
if (this.menu === true) {
this.menu = false
// allow $refs.target to move to the field (when dialog)
this.$nextTick(() => {
this.$refs.target !== void 0 && this.$refs.target.focus()
})
}
if (this.focused === false) {
clearTimeout(this.filterId)
this.filterId = void 0
if (this.innerLoading === true) {
this.$emit('filter-abort')
this.innerLoading = false
}
}
},
showPopup (e) {
if (this.hasDialog === true) {
this.__onControlFocusin(e)
this.dialog = true
}
else {
this.__focus()
}
if (this.$listeners.filter !== void 0) {
this.filter(this.inputValue)
}
else if (this.noOptions !== true || this.$scopedSlots['no-option'] !== void 0) {
this.menu = true
}
},
hidePopup () {
this.dialog = false
this.__closeMenu()
},
__resetInputValue () {
this.useInput === true && this.updateInputValue(
this.multiple !== true && this.fillInput === true && this.innerValue.length > 0
? this.__getOptionLabel(this.innerValue[0]) || ''
: '',
true,
true
)
},
__updateMenu (show) {
let optionIndex = -1
if (show === true) {
if (this.innerValue.length > 0) {
const val = this.__getOptionValue(this.innerValue[0])
optionIndex = this.options.findIndex(v => isDeepEqual(this.__getOptionValue(v), val))
}
this.__resetVirtualScroll(optionIndex)
}
this.setOptionIndex(optionIndex)
},
__onPreRender () {
this.hasDialog = this.$q.platform.is.mobile !== true && this.behavior !== 'dialog'
? false
: this.behavior !== 'menu' && (
this.useInput === true
? this.$scopedSlots['no-option'] !== void 0 || this.$listeners.filter !== void 0 || this.noOptions === false
: true
)
this.transitionShowComputed = this.hasDialog === true && this.useInput === true && this.$q.platform.is.ios === true
? 'fade'
: this.transitionShow
},
__onPostRender () {
if (this.dialog === false && this.$refs.menu !== void 0) {
this.$refs.menu.updatePosition()
}
},
updateMenuPosition () {
this.__onPostRender()
}
},
beforeDestroy () {
clearTimeout(this.inputTimer)
}
})
| ui/src/components/select/QSelect.js | import Vue from 'vue'
import QField from '../field/QField.js'
import QIcon from '../icon/QIcon.js'
import QChip from '../chip/QChip.js'
import QItem from '../list/QItem.js'
import QItemSection from '../list/QItemSection.js'
import QItemLabel from '../list/QItemLabel.js'
import QMenu from '../menu/QMenu.js'
import QDialog from '../dialog/QDialog.js'
import { isDeepEqual } from '../../utils/is.js'
import { stop, prevent, stopAndPrevent } from '../../utils/event.js'
import { normalizeToInterval } from '../../utils/format.js'
import VirtualScroll from '../../mixins/virtual-scroll.js'
import CompositionMixin from '../../mixins/composition.js'
const validateNewValueMode = v => ['add', 'add-unique', 'toggle'].includes(v)
export default Vue.extend({
name: 'QSelect',
mixins: [ QField, VirtualScroll, CompositionMixin ],
props: {
value: {
required: true
},
multiple: Boolean,
displayValue: [String, Number],
displayValueSanitize: Boolean,
dropdownIcon: String,
options: {
type: Array,
default: () => []
},
optionValue: [Function, String],
optionLabel: [Function, String],
optionDisable: [Function, String],
hideSelected: Boolean,
hideDropdownIcon: Boolean,
fillInput: Boolean,
maxValues: [Number, String],
optionsDense: Boolean,
optionsDark: Boolean,
optionsSelectedClass: String,
optionsCover: Boolean,
optionsSanitize: Boolean,
popupContentClass: String,
popupContentStyle: [String, Array, Object],
useInput: Boolean,
useChips: Boolean,
newValueMode: {
type: String,
validator: validateNewValueMode
},
mapOptions: Boolean,
emitValue: Boolean,
inputDebounce: {
type: [Number, String],
default: 500
},
inputClass: [Array, String, Object],
inputStyle: [Array, String, Object],
transitionShow: String,
transitionHide: String,
behavior: {
type: String,
validator: v => ['default', 'menu', 'dialog'].includes(v),
default: 'default'
}
},
data () {
return {
menu: false,
dialog: false,
optionIndex: -1,
inputValue: '',
dialogFieldFocused: false
}
},
watch: {
innerValue: {
handler () {
if (
this.useInput === true &&
this.fillInput === true &&
this.multiple !== true &&
// Prevent re-entering in filter while filtering
// Also prevent clearing inputValue while filtering
this.innerLoading !== true &&
((this.dialog !== true && this.menu !== true) || this.hasValue !== true)
) {
this.__resetInputValue()
if (this.dialog === true || this.menu === true) {
this.filter('')
}
}
},
immediate: true
},
menu (show) {
this.__updateMenu(show)
}
},
computed: {
virtualScrollLength () {
return Array.isArray(this.options)
? this.options.length
: 0
},
fieldClass () {
return `q-select q-field--auto-height q-select--with${this.useInput !== true ? 'out' : ''}-input`
},
computedInputClass () {
if (this.hideSelected === true || this.innerValue.length === 0) {
return this.inputClass
}
return this.inputClass === void 0
? 'q-select__input--padding'
: [this.inputClass, 'q-select__input--padding']
},
menuContentClass () {
return (this.virtualScrollHorizontal === true ? 'q-virtual-scroll--horizontal' : '') +
(this.popupContentClass ? ' ' + this.popupContentClass : '')
},
menuClass () {
return this.menuContentClass + (this.optionsDark === true ? ' q-select__menu--dark' : '')
},
innerValue () {
const
mapNull = this.mapOptions === true && this.multiple !== true,
val = this.value !== void 0 && (this.value !== null || mapNull === true)
? (this.multiple === true && Array.isArray(this.value) ? this.value : [ this.value ])
: []
return this.mapOptions === true && Array.isArray(this.options) === true
? (
this.value === null && mapNull === true
? val.map(v => this.__getOption(v)).filter(v => v !== null)
: val.map(v => this.__getOption(v))
)
: val
},
noOptions () {
return this.virtualScrollLength === 0
},
selectedString () {
return this.innerValue
.map(opt => this.__getOptionLabel(opt))
.join(', ')
},
displayAsText () {
return this.displayValueSanitize === true || (
this.displayValue === void 0 && (
this.optionsSanitize === true ||
this.innerValue.some(opt => opt !== null && opt.sanitize === true)
)
)
},
selectedScope () {
const tabindex = this.focused === true ? 0 : -1
return this.innerValue.map((opt, i) => ({
index: i,
opt,
sanitize: this.optionsSanitize === true || opt.sanitize === true,
selected: true,
removeAtIndex: this.__removeAtIndexAndFocus,
toggleOption: this.toggleOption,
tabindex
}))
},
optionScope () {
if (this.virtualScrollLength === 0) {
return []
}
const { from, to } = this.virtualScrollSliceRange
return this.options.slice(from, to).map((opt, i) => {
const disable = this.__isDisabled(opt)
const index = from + i
const itemProps = {
clickable: true,
active: false,
activeClass: this.optionsSelectedClass,
manualFocus: true,
focused: false,
disable,
tabindex: -1,
dense: this.optionsDense,
dark: this.optionsDark
}
if (disable !== true) {
this.__isSelected(opt) === true && (itemProps.active = true)
this.optionIndex === index && (itemProps.focused = true)
}
const itemEvents = {
click: () => { this.toggleOption(opt) }
}
if (this.$q.platform.is.desktop === true) {
itemEvents.mousemove = () => { this.setOptionIndex(index) }
}
return {
index,
opt,
sanitize: this.optionsSanitize === true || opt.sanitize === true,
selected: itemProps.active,
focused: itemProps.focused,
toggleOption: this.toggleOption,
setOptionIndex: this.setOptionIndex,
itemProps,
itemEvents
}
})
},
dropdownArrowIcon () {
return this.dropdownIcon !== void 0
? this.dropdownIcon
: this.$q.iconSet.arrow.dropdown
},
squaredMenu () {
return this.optionsCover === false &&
this.outlined !== true &&
this.standout !== true &&
this.borderless !== true &&
this.rounded !== true
}
},
methods: {
removeAtIndex (index) {
if (index > -1 && index < this.innerValue.length) {
if (this.multiple === true) {
const model = [].concat(this.value)
this.$emit('remove', { index, value: model.splice(index, 1) })
this.$emit('input', model)
}
else {
this.$emit('input', null)
}
}
},
__removeAtIndexAndFocus (index) {
this.removeAtIndex(index)
this.__focus()
},
add (opt, unique) {
const val = this.emitValue === true
? this.__getOptionValue(opt)
: opt
if (this.multiple !== true) {
this.$emit('input', val)
return
}
if (this.innerValue.length === 0) {
this.$emit('add', { index: 0, value: val })
this.$emit('input', this.multiple === true ? [ val ] : val)
return
}
if (unique === true && this.__isSelected(opt) === true) {
return
}
const model = [].concat(this.value)
if (this.maxValues !== void 0 && model.length >= this.maxValues) {
return
}
this.$emit('add', { index: model.length, value: val })
model.push(val)
this.$emit('input', model)
},
toggleOption (opt) {
if (this.editable !== true || opt === void 0 || this.__isDisabled(opt) === true) {
return
}
const optValue = this.__getOptionValue(opt)
if (this.multiple !== true) {
this.updateInputValue(
this.fillInput === true ? this.__getOptionLabel(opt) : '',
true,
true
)
this.hidePopup()
if (isDeepEqual(this.__getOptionValue(this.value), optValue) !== true) {
this.$emit('input', this.emitValue === true ? optValue : opt)
}
return
}
(this.hasDialog !== true || this.dialogFieldFocused === true) && this.__focus()
if (this.innerValue.length === 0) {
const val = this.emitValue === true ? optValue : opt
this.$emit('add', { index: 0, value: val })
this.$emit('input', this.multiple === true ? [ val ] : val)
return
}
const
model = [].concat(this.value),
index = this.value.findIndex(v => isDeepEqual(this.__getOptionValue(v), optValue))
if (index > -1) {
this.$emit('remove', { index, value: model.splice(index, 1) })
}
else {
if (this.maxValues !== void 0 && model.length >= this.maxValues) {
return
}
const val = this.emitValue === true ? optValue : opt
this.$emit('add', { index: model.length, value: val })
model.push(val)
}
this.$emit('input', model)
},
setOptionIndex (index) {
if (this.$q.platform.is.desktop !== true) { return }
const val = index > -1 && index < this.virtualScrollLength
? index
: -1
if (this.optionIndex !== val) {
this.optionIndex = val
}
},
__getOption (value) {
return this.options.find(opt => isDeepEqual(this.__getOptionValue(opt), value)) || value
},
__getOptionValue (opt) {
if (typeof this.optionValue === 'function') {
return this.optionValue(opt)
}
if (Object(opt) === opt) {
return typeof this.optionValue === 'string'
? opt[this.optionValue]
: opt.value
}
return opt
},
__getOptionLabel (opt) {
if (typeof this.optionLabel === 'function') {
return this.optionLabel(opt)
}
if (Object(opt) === opt) {
return typeof this.optionLabel === 'string'
? opt[this.optionLabel]
: opt.label
}
return opt
},
__isDisabled (opt) {
if (typeof this.optionDisable === 'function') {
return this.optionDisable(opt) === true
}
if (Object(opt) === opt) {
return typeof this.optionDisable === 'string'
? opt[this.optionDisable] === true
: opt.disable === true
}
return false
},
__isSelected (opt) {
const val = this.__getOptionValue(opt)
return this.innerValue
.find(v => isDeepEqual(this.__getOptionValue(v), val)) !== void 0
},
__onTargetKeyup (e) {
// if ESC and we have an opened menu
// then stop propagation (might be caught by a QDialog
// and so it will also close the QDialog, which is wrong)
if (e.keyCode === 27 && this.menu === true) {
stop(e)
// on ESC we need to close the dialog also
this.hidePopup()
}
this.$emit('keyup', e)
},
__onTargetKeypress (e) {
this.$emit('keypress', e)
},
__onTargetKeydown (e) {
this.$emit('keydown', e)
const tabShouldSelect = e.shiftKey !== true && this.multiple !== true && this.optionIndex > -1
// escape
if (e.keyCode === 27) {
return
}
// tab
if (e.keyCode === 9 && tabShouldSelect === false) {
this.__closeMenu()
return
}
if (e.target !== this.$refs.target) { return }
// down
if (
e.keyCode === 40 &&
this.innerLoading !== true &&
this.menu === false
) {
stopAndPrevent(e)
this.showPopup()
return
}
// backspace
if (
e.keyCode === 8 &&
this.multiple === true &&
this.inputValue.length === 0 &&
Array.isArray(this.value)
) {
this.removeAtIndex(this.value.length - 1)
return
}
// up, down
const optionsLength = this.virtualScrollLength
if (e.keyCode === 38 || e.keyCode === 40) {
stopAndPrevent(e)
if (this.menu === true) {
let index = this.optionIndex
do {
index = normalizeToInterval(
index + (e.keyCode === 38 ? -1 : 1),
-1,
optionsLength - 1
)
}
while (index !== -1 && index !== this.optionIndex && this.__isDisabled(this.options[index]) === true)
if (this.optionIndex !== index) {
this.setOptionIndex(index)
this.scrollTo(index)
if (index >= 0 && this.useInput === true && this.fillInput === true) {
const inputValue = this.__getOptionLabel(this.options[index])
if (this.inputValue !== inputValue) {
this.inputValue = inputValue
}
}
}
}
}
// keyboard search when not having use-input
if (optionsLength > 0 && this.useInput !== true && e.keyCode >= 48 && e.keyCode <= 90) {
this.menu !== true && this.showPopup(e)
// clear search buffer if expired
if (this.searchBuffer === void 0 || this.searchBufferExp < Date.now()) {
this.searchBuffer = ''
}
const
char = String.fromCharCode(e.keyCode).toLocaleLowerCase(),
keyRepeat = this.searchBuffer.length === 1 && this.searchBuffer[0] === char
this.searchBufferExp = Date.now() + 1500
if (keyRepeat === false) {
this.searchBuffer += char
}
const searchRe = new RegExp('^' + this.searchBuffer.split('').join('.*'), 'i')
let index = this.optionIndex
if (keyRepeat === true || searchRe.test(this.__getOptionLabel(this.options[index])) !== true) {
do {
index = normalizeToInterval(index + 1, -1, optionsLength - 1)
}
while (index !== this.optionIndex && (
this.__isDisabled(this.options[index]) === true ||
searchRe.test(this.__getOptionLabel(this.options[index])) !== true
))
}
if (this.optionIndex !== index) {
this.$nextTick(() => {
this.setOptionIndex(index)
this.scrollTo(index)
if (index >= 0 && this.useInput === true && this.fillInput === true) {
const inputValue = this.__getOptionLabel(this.options[index])
if (this.inputValue !== inputValue) {
this.inputValue = inputValue
}
}
})
}
return
}
// enter, space (when not using use-input), or tab (when not using multiple and option selected)
if (
e.target !== this.$refs.target ||
(
e.keyCode !== 13 &&
(this.useInput === true || e.keyCode !== 32) &&
(tabShouldSelect === false || e.keyCode !== 9)
)
) { return }
e.keyCode !== 9 && stopAndPrevent(e)
if (this.optionIndex > -1 && this.optionIndex < optionsLength) {
this.toggleOption(this.options[this.optionIndex])
return
}
if (
this.inputValue.length > 0 &&
(this.newValueMode !== void 0 || this.$listeners['new-value'] !== void 0)
) {
const done = (val, mode) => {
if (mode) {
if (validateNewValueMode(mode) !== true) {
console.error('QSelect: invalid new value mode - ' + mode)
return
}
}
else {
mode = this.newValueMode
}
if (val !== void 0 && val !== null) {
this[mode === 'toggle' ? 'toggleOption' : 'add'](
val,
mode === 'add-unique'
)
}
this.updateInputValue('', this.multiple !== true, true)
}
if (this.$listeners['new-value'] !== void 0) {
this.$emit('new-value', this.inputValue, done)
if (this.multiple !== true) {
return
}
}
else {
done(this.inputValue)
}
}
if (this.menu === true) {
this.__closeMenu()
}
else if (this.innerLoading !== true) {
this.showPopup()
}
},
__getVirtualScrollEl () {
return this.hasDialog === true
? this.$refs.menuContent
: (
this.$refs.menu !== void 0 && this.$refs.menu.__portal !== void 0
? this.$refs.menu.__portal.$el
: void 0
)
},
__getVirtualScrollTarget () {
return this.__getVirtualScrollEl()
},
__getSelection (h, fromDialog) {
if (this.hideSelected === true) {
return fromDialog !== true && this.hasDialog === true
? [
h('span', {
domProps: {
'textContent': this.inputValue
}
})
]
: []
}
if (this.$scopedSlots['selected-item'] !== void 0) {
return this.selectedScope.map(scope => this.$scopedSlots['selected-item'](scope))
}
if (this.$scopedSlots.selected !== void 0) {
return this.$scopedSlots.selected()
}
if (this.useChips === true) {
const tabindex = this.focused === true ? 0 : -1
return this.selectedScope.map((scope, i) => h(QChip, {
key: 'option-' + i,
props: {
removable: this.__isDisabled(scope.opt) !== true,
dense: true,
textColor: this.color,
tabindex
},
on: {
remove () { scope.removeAtIndex(i) }
}
}, [
h('span', {
domProps: {
[scope.sanitize === true ? 'textContent' : 'innerHTML']: this.__getOptionLabel(scope.opt)
}
})
]))
}
return [
h('span', {
domProps: {
[this.displayAsText ? 'textContent' : 'innerHTML']: this.displayValue !== void 0
? this.displayValue
: this.selectedString
}
})
]
},
__getControl (h, fromDialog) {
const child = this.__getSelection(h, fromDialog)
if (this.useInput === true && (fromDialog === true || this.hasDialog === false)) {
child.push(this.__getInput(h, fromDialog))
}
else if (this.editable === true) {
const isShadowField = this.hasDialog === true && fromDialog !== true && this.menu === true
child.push(h('div', {
// there can be only one (when dialog is opened the control in dialog should be target)
ref: isShadowField === true ? void 0 : 'target',
staticClass: 'no-outline',
attrs: {
tabindex: 0,
id: isShadowField === true ? void 0 : this.targetUid
},
on: {
keydown: this.__onTargetKeydown,
keyup: this.__onTargetKeyup,
keypress: this.__onTargetKeypress
}
}))
}
return h('div', { staticClass: 'q-field__native row items-center', attrs: this.$attrs }, child)
},
__getOptions (h) {
if (this.menu !== true) {
return void 0
}
const fn = this.$scopedSlots.option !== void 0
? this.$scopedSlots.option
: scope => h(QItem, {
key: scope.index,
props: scope.itemProps,
on: scope.itemEvents
}, [
h(QItemSection, [
h(QItemLabel, {
domProps: {
[scope.sanitize === true ? 'textContent' : 'innerHTML']: this.__getOptionLabel(scope.opt)
}
})
])
])
let options = this.__padVirtualScroll(h, 'div', this.optionScope.map(fn))
if (this.$scopedSlots['before-options'] !== void 0) {
options = this.$scopedSlots['before-options']().concat(options)
}
if (this.$scopedSlots['after-options'] !== void 0) {
options = options.concat(this.$scopedSlots['after-options']())
}
return options
},
__getInnerAppend (h) {
return this.loading !== true && this.innerLoading !== true && this.hideDropdownIcon !== true
? [
h(QIcon, {
staticClass: 'q-select__dropdown-icon',
props: { name: this.dropdownArrowIcon }
})
]
: null
},
__getInput (h, fromDialog) {
const on = {
input: this.__onInput,
// Safari < 10.2 & UIWebView doesn't fire compositionend when
// switching focus before confirming composition choice
// this also fixes the issue where some browsers e.g. iOS Chrome
// fires "change" instead of "input" on autocomplete.
change: this.__onChange,
keydown: this.__onTargetKeydown,
keyup: this.__onTargetKeyup,
keypress: this.__onTargetKeypress
}
on.compositionstart = on.compositionupdate = on.compositionend = this.__onComposition
if (this.hasDialog === true) {
on.click = stop
}
return h('input', {
ref: 'target',
staticClass: 'q-select__input q-placeholder col',
style: this.inputStyle,
class: this.computedInputClass,
domProps: { value: this.inputValue },
attrs: {
// required for Android in order to show ENTER key when in form
type: 'search',
...this.$attrs,
tabindex: 0,
autofocus: fromDialog === true ? false : this.autofocus,
id: this.targetUid,
disabled: this.disable === true,
readonly: this.readonly === true
},
on
})
},
__onChange (e) {
this.__onComposition(e)
},
__onInput (e) {
clearTimeout(this.inputTimer)
if (e && e.target && e.target.composing === true) {
return
}
this.inputValue = e.target.value || ''
// mark it here as user input so that if updateInputValue is called
// before filter is called the indicator is reset
this.userInputValue = true
if (this.$listeners.filter !== void 0) {
this.inputTimer = setTimeout(() => {
this.filter(this.inputValue)
}, this.inputDebounce)
}
},
updateInputValue (val, noFiltering, internal) {
this.userInputValue = internal !== true
if (this.useInput === true) {
if (this.inputValue !== val) {
this.inputValue = val
}
noFiltering !== true && this.filter(val)
}
},
filter (val) {
if (this.$listeners.filter === void 0 || this.focused !== true) {
return
}
if (this.innerLoading === true) {
this.$emit('filter-abort')
}
else {
this.innerLoading = true
}
if (
val !== '' &&
this.multiple !== true &&
this.innerValue.length > 0 &&
this.userInputValue !== true &&
val === this.__getOptionLabel(this.innerValue[0])
) {
val = ''
}
const filterId = setTimeout(() => {
this.menu === true && (this.menu = false)
}, 10)
clearTimeout(this.filterId)
this.filterId = filterId
this.$emit(
'filter',
val,
fn => {
if (this.focused === true && this.filterId === filterId) {
clearTimeout(this.filterId)
typeof fn === 'function' && fn()
this.$nextTick(() => {
this.innerLoading = false
if (this.menu === true) {
this.__updateMenu(true)
}
else {
this.menu = true
}
})
}
},
() => {
if (this.focused === true && this.filterId === filterId) {
clearTimeout(this.filterId)
this.innerLoading = false
}
this.menu === true && (this.menu = false)
}
)
},
__getControlEvents () {
const focusout = e => {
this.__onControlFocusout(e, () => {
this.__resetInputValue()
this.__closeMenu()
})
}
return {
focusin: this.__onControlFocusin,
focusout,
'popup-show': this.__onControlPopupShow,
'popup-hide': e => {
e !== void 0 && stop(e)
this.$emit('popup-hide', e)
this.hasPopupOpen = false
focusout(e)
},
click: e => {
// label from QField will propagate click on the input (except IE)
if (
this.hasDialog !== true &&
this.useInput === true &&
e.target.classList.contains('q-select__input') !== true
) {
return
}
if (this.hasDialog !== true && this.menu === true) {
this.__closeMenu()
this.$refs.target !== void 0 && this.$refs.target.focus()
}
else {
this.showPopup(e)
}
}
}
},
__getPopup (h) {
if (
this.editable !== false && (
this.dialog === true || // dialog always has menu displayed, so need to render it
this.noOptions !== true ||
this.$scopedSlots['no-option'] !== void 0
)
) {
return this[`__get${this.hasDialog === true ? 'Dialog' : 'Menu'}`](h)
}
},
__getMenu (h) {
const child = this.noOptions === true
? (
this.$scopedSlots['no-option'] !== void 0
? this.$scopedSlots['no-option']({ inputValue: this.inputValue })
: null
)
: this.__getOptions(h)
return h(QMenu, {
ref: 'menu',
props: {
value: this.menu,
fit: true,
cover: this.optionsCover === true && this.noOptions !== true && this.useInput !== true,
contentClass: this.menuClass,
contentStyle: this.popupContentStyle,
noParentEvent: true,
noRefocus: true,
noFocus: true,
square: this.squaredMenu,
transitionShow: this.transitionShow,
transitionHide: this.transitionHide,
separateClosePopup: true
},
on: {
'&scroll': this.__onVirtualScrollEvt,
'before-hide': this.__closeMenu
}
}, child)
},
__onDialogFieldFocus (e) {
stop(e)
this.$refs.target !== void 0 && this.$refs.target.focus()
this.dialogFieldFocused = true
window.scrollTo(window.pageXOffset || window.scrollX || document.body.scrollLeft || 0, 0)
},
__onDialogFieldBlur (e) {
stop(e)
this.$nextTick(() => {
this.dialogFieldFocused = false
})
},
__getDialog (h) {
const content = [
h(QField, {
staticClass: `col-auto ${this.fieldClass}`,
attrs: {
for: this.targetUid
},
props: {
...this.$props,
dark: this.optionsDark,
square: true,
loading: this.innerLoading,
filled: true,
stackLabel: this.inputValue.length > 0
},
on: {
...this.$listeners,
focus: this.__onDialogFieldFocus,
blur: this.__onDialogFieldBlur
},
scopedSlots: {
...this.$scopedSlots,
rawControl: () => this.__getControl(h, true),
before: void 0,
after: void 0
}
})
]
this.menu === true && content.push(
h('div', {
ref: 'menuContent',
staticClass: 'scroll',
class: this.menuContentClass,
style: this.popupContentStyle,
on: {
click: prevent,
'&scroll': this.__onVirtualScrollEvt
}
}, (
this.noOptions === true
? (
this.$scopedSlots['no-option'] !== void 0
? this.$scopedSlots['no-option']({ inputValue: this.inputValue })
: null
)
: this.__getOptions(h)
))
)
return h(QDialog, {
props: {
value: this.dialog,
noRefocus: true,
position: this.useInput === true ? 'top' : void 0,
transitionShow: this.transitionShowComputed,
transitionHide: this.transitionHide
},
on: {
'before-hide': () => {
this.focused = false
},
hide: e => {
this.hidePopup()
this.$emit('blur', e)
this.__resetInputValue()
},
show: () => {
const el = document.activeElement
// IE can have null document.activeElement
if (
(el === null || el.id !== this.targetUid) &&
this.$refs.target !== el
) {
this.$refs.target.focus()
}
}
}
}, [
h('div', {
staticClass: 'q-select__dialog' +
(this.optionsDark === true ? ' q-select__menu--dark' : '') +
(this.dialogFieldFocused === true ? ' q-select__dialog--focused' : '')
}, content)
])
},
__closeMenu () {
if (this.dialog === true) {
return
}
if (this.menu === true) {
this.menu = false
// allow $refs.target to move to the field (when dialog)
this.$nextTick(() => {
this.$refs.target !== void 0 && this.$refs.target.focus()
})
}
if (this.focused === false) {
clearTimeout(this.filterId)
this.filterId = void 0
if (this.innerLoading === true) {
this.$emit('filter-abort')
this.innerLoading = false
}
}
},
showPopup (e) {
if (this.hasDialog === true) {
this.__onControlFocusin(e)
this.dialog = true
}
else {
this.__focus()
}
if (this.$listeners.filter !== void 0) {
this.filter(this.inputValue)
}
else if (this.noOptions !== true || this.$scopedSlots['no-option'] !== void 0) {
this.menu = true
}
},
hidePopup () {
this.dialog = false
this.__closeMenu()
},
__resetInputValue () {
this.useInput === true && this.updateInputValue(
this.multiple !== true && this.fillInput === true && this.innerValue.length > 0
? this.__getOptionLabel(this.innerValue[0]) || ''
: '',
true,
true
)
},
__updateMenu (show) {
let optionIndex = -1
if (show === true) {
if (this.innerValue.length > 0) {
const val = this.__getOptionValue(this.innerValue[0])
optionIndex = this.options.findIndex(v => isDeepEqual(this.__getOptionValue(v), val))
}
this.__resetVirtualScroll(optionIndex)
}
this.setOptionIndex(optionIndex)
},
__onPreRender () {
this.hasDialog = this.$q.platform.is.mobile !== true && this.behavior !== 'dialog'
? false
: this.behavior !== 'menu' && (
this.useInput === true
? this.$scopedSlots['no-option'] !== void 0 || this.$listeners.filter !== void 0 || this.noOptions === false
: true
)
this.transitionShowComputed = this.hasDialog === true && this.useInput === true && this.$q.platform.is.ios === true
? 'fade'
: this.transitionShow
},
__onPostRender () {
if (this.dialog === false && this.$refs.menu !== void 0) {
this.$refs.menu.updatePosition()
}
},
updateMenuPosition () {
this.__onPostRender()
}
},
beforeDestroy () {
clearTimeout(this.inputTimer)
}
})
| perf(QSelect): avoid Vue re-attaching QDialog events on each render
| ui/src/components/select/QSelect.js | perf(QSelect): avoid Vue re-attaching QDialog events on each render | <ide><path>i/src/components/select/QSelect.js
<ide> transitionHide: this.transitionHide
<ide> },
<ide> on: {
<del> 'before-hide': () => {
<del> this.focused = false
<del> },
<del> hide: e => {
<del> this.hidePopup()
<del> this.$emit('blur', e)
<del> this.__resetInputValue()
<del> },
<del> show: () => {
<del> const el = document.activeElement
<del> // IE can have null document.activeElement
<del> if (
<del> (el === null || el.id !== this.targetUid) &&
<del> this.$refs.target !== el
<del> ) {
<del> this.$refs.target.focus()
<del> }
<del> }
<add> 'before-hide': this.__onDialogBeforeHide,
<add> hide: this.__onDialogHide,
<add> show: this.__onDialogShow
<ide> }
<ide> }, [
<ide> h('div', {
<ide> (this.dialogFieldFocused === true ? ' q-select__dialog--focused' : '')
<ide> }, content)
<ide> ])
<add> },
<add>
<add> __onDialogBeforeHide () {
<add> this.focused = false
<add> },
<add>
<add> __onDialogHide (e) {
<add> this.hidePopup()
<add> this.$emit('blur', e)
<add> this.__resetInputValue()
<add> },
<add>
<add> __onDialogShow () {
<add> const el = document.activeElement
<add> // IE can have null document.activeElement
<add> if (
<add> (el === null || el.id !== this.targetUid) &&
<add> this.$refs.target !== el
<add> ) {
<add> this.$refs.target.focus()
<add> }
<ide> },
<ide>
<ide> __closeMenu () { |
|
JavaScript | mit | 1510e0fcac5d3c084405cf330c9daa3986087f49 | 0 | shopapps/sparkphase-couchbase-orm | /*
Sparkphase Couchbase ORM Version 0.1.0
Updated: Friday 17th October 2014
Author: Jonathan Bristow <[email protected]>
Repository: https://github.com/JonathanBristow/Sparky
*/
module.exports = function(Options) {
} | index.js | /*
Sparky Version 0.1.0
Updated: Friday 17th October 2014
Author: Jonathan Bristow <[email protected]>
Repository: https://github.com/JonathanBristow/Sparky
*/
module.exports = function Sparky(Options) {
console.log(Options.Type+' => '+Options.Group+' => '+Options.Message);
if (Options.Detail) {
console.log('Detail:', Options.Detail);
}
if (Options.Exit) {
console.log('This error has caused the application to exit.');
process.exit();
}
} | Update
| index.js | Update | <ide><path>ndex.js
<ide> /*
<del> Sparky Version 0.1.0
<add> Sparkphase Couchbase ORM Version 0.1.0
<ide> Updated: Friday 17th October 2014
<ide> Author: Jonathan Bristow <[email protected]>
<ide> Repository: https://github.com/JonathanBristow/Sparky
<ide> */
<ide>
<del>module.exports = function Sparky(Options) {
<del> console.log(Options.Type+' => '+Options.Group+' => '+Options.Message);
<del> if (Options.Detail) {
<del> console.log('Detail:', Options.Detail);
<del> }
<del> if (Options.Exit) {
<del> console.log('This error has caused the application to exit.');
<del> process.exit();
<del> }
<add>module.exports = function(Options) {
<add>
<add>
<add>
<add>
<ide> } |
|
Java | bsd-2-clause | 8c820861b7648827d96f2e746989075bf22a0db4 | 0 | zlamalp/perun-wui,zlamalp/perun-wui,zlamalp/perun-wui | package cz.metacentrum.perun.wui.json;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.storage.client.Storage;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import cz.metacentrum.perun.wui.client.resources.PerunErrorTranslation;
import cz.metacentrum.perun.wui.client.resources.PerunSession;
import cz.metacentrum.perun.wui.client.resources.PerunWebConstants;
import cz.metacentrum.perun.wui.json.managers.UtilsManager;
import cz.metacentrum.perun.wui.model.PerunException;
import cz.metacentrum.perun.wui.model.common.PerunRequest;
import cz.metacentrum.perun.wui.widgets.PerunButton;
import org.gwtbootstrap3.client.shared.event.ModalHiddenEvent;
import org.gwtbootstrap3.client.shared.event.ModalHiddenHandler;
import org.gwtbootstrap3.client.shared.event.ModalShownEvent;
import org.gwtbootstrap3.client.shared.event.ModalShownHandler;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.ModalBody;
import org.gwtbootstrap3.client.ui.ModalFooter;
import org.gwtbootstrap3.client.ui.ModalHeader;
import org.gwtbootstrap3.client.ui.html.Paragraph;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Client class performing GET/POST requests to Perun's API.
* For each call, new instance must be created.
*
* @author Pavel Zlámal <[email protected]>
*/
public class JsonClient {
private JsonEvents events = new JsonEvents() {
@Override
public void onFinished(JavaScriptObject jso) {
}
@Override
public void onError(PerunException error) {
}
@Override
public void onLoadingStart() {
}
};
private String urlPrefix = PerunSession.getInstance().getRpcUrl();
private String requestUrl;
private JSONObject json = new JSONObject();
private boolean checkIfPending = false;
private PerunErrorTranslation errorTranslation = GWT.create(PerunErrorTranslation.class);
private Map<String, PerunRequest> runningRequests = new HashMap<>();
private static Paragraph layout = new Paragraph();
private static int counter = 0;
private static Modal modal;
private static boolean shown = false;
public static Storage localStorage = Storage.getLocalStorageIfSupported();
public boolean showErrorMessage = true;
/**
* New JsonClient using GET method
*/
public JsonClient() {
// init modal dialog
if (modal == null) {
modal = new Modal();
modal.setClosable(true);
modal.addShownHandler(new ModalShownHandler() {
@Override
public void onShown(ModalShownEvent modalShownEvent) {
shown = true;
}
});
modal.addHiddenHandler(new ModalHiddenHandler() {
@Override
public void onHidden(ModalHiddenEvent modalHiddenEvent) {
shown = false;
}
});
ModalHeader header = new ModalHeader();
header.setTitle("Processing long request");
modal.add(header);
ModalBody body = new ModalBody();
body.add(layout);
modal.add(body);
ModalFooter footer = new ModalFooter();
PerunButton close = new PerunButton("Hide");
close.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
modal.hide();
}
});
footer.add(close);
modal.add(footer);
}
}
/**
* Create new JsonClient
*
* @param checkIfPending If {@code true} check for callback results even after server timeout.
*/
public JsonClient(boolean checkIfPending) {
this();
this.checkIfPending = checkIfPending;
}
/**
* Create new JsonClient
*
* @param events events, which handles retrieved response
*/
public JsonClient(JsonEvents events) {
this();
if (events != null) this.events = events;
}
/**
* Create new JsonClient
*
* @param checkIfPending If {@code true} check for callback results even after server timeout.
* @param events events, which handles retrieved response
*/
public JsonClient(boolean checkIfPending, JsonEvents events) {
this(checkIfPending);
if (events != null) this.events = events;
}
/**
* Put custom parameter into payload of a request.
*
* @param key key (parameter name)
* @param data int data to send (parameter value)
*/
public void put(String key, int data) {
put(key, new JSONNumber(data));
}
/**
* Put custom parameter into payload of a request.
*
* @param key key (parameter name)
* @param data String data to send (parameter value)
*/
public void put(String key, String data) {
put(key, new JSONString(data));
}
/**
* Put custom parameter into payload of a request.
*
* @param key key (parameter name)
* @param data boolean data to send (parameter value)
*/
public void put(String key, boolean data) {
put(key, JSONBoolean.getInstance(data));
}
/**
* Put custom parameter into payload of a request.
*
* @param key key (parameter name)
* @param data JavaScriptObject data to send (parameter value)
*/
public <T extends JavaScriptObject> void put(String key, T data) {
put(key, JsonUtils.convertToJSON(data));
}
/**
* Put custom parameter into payload of a request.
*
* @param key key (parameter name)
* @param data List data to send as one parameter (parameter values)
*/
public void put(String key, List<? extends Object> data) {
JSONArray array = new JSONArray();
for (int i=0; i<data.size(); i++) {
if (data.get(i).getClass().isEnum()) {
array.set(i, new JSONString(data.get(i).toString()));
} else if (data.get(i) instanceof JavaScriptObject) {
array.set(i, JsonUtils.convertToJSON((JavaScriptObject)data.get(i)));
} else if (data.get(i) instanceof Integer) {
array.set(i, new JSONNumber(((Integer) data.get(i)).intValue()));
} else if (data.get(i) instanceof String) {
array.set(i, new JSONString(((String) data.get(i))));
} else if (data.get(i) instanceof Boolean) {
array.set(i, JSONBoolean.getInstance(((Boolean) data.get(i)).booleanValue()));
}
}
put(key, array);
}
/**
* Actually put parameter into payload of a request.
*
* @param key key (parameter name)
* @param data data to send in a JSON valid format (parameter value)
*/
private void put(String key, JSONValue data) {
json.put(key, data);
}
/**
* Call specific URL with custom events.
*
* @param url URL to send data to
* @return Request unique handling Request
*/
public Request call(final String url) {
final PerunRequest perunRequest = new JSONObject().getJavaScriptObject().cast();
perunRequest.setStartTime();
final String callbackName = perunRequest.getStartTime()+"";
if (checkIfPending) runningRequests.put(callbackName, perunRequest);
// build request URL
this.requestUrl = URL.encode(urlPrefix + url + ((checkIfPending) ? ("?callback=" + callbackName) : ""));
// we do use POST every time in order to use JSON deserializer on server side
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, requestUrl);
if (Cookies.getCookie("XSRF-TOKEN") != null) {
builder.setHeader("X-XSRF-TOKEN", Cookies.getCookie("XSRF-TOKEN"));
}
try {
events.onLoadingStart();
final String data = (json != null && json.isObject() != null) ? json.toString() : "";
Request request = builder.sendRequest(data, new RequestCallback() {
@Override
public void onResponseReceived(Request req, Response resp) {
// make JSO from textual JSON response
JavaScriptObject jso = parseResponse(callbackName, resp.getText());
// HTTP status code is OK
if (resp.getStatusCode() == 200) {
// remove csrf check from localStorage if the request is successful
if (localStorage.getItem("csrf") != null) {
localStorage.removeItem("csrf");
}
// check JSO, if not PerunException
if (jso != null) {
PerunException error = (PerunException)jso;
if (error.getErrorId() != null && error.getMessage() != null) {
error.setRequestURL(url);
error.setPostData((json != null) ? json.toString() : "");
if (checkIfPending) runningRequests.remove(callbackName);
events.onError(error);
return;
}
}
// Response is OK (object or null)
if (checkIfPending) runningRequests.remove(callbackName);
events.onFinished(jso);
} else {
// HTTP status code != OK (200)
PerunException error = new JSONObject().getJavaScriptObject().cast();
error.setErrorId("" + resp.getStatusCode());
error.setName(resp.getStatusText());
error.setMessage(errorTranslation.httpErrorAny(resp.getStatusCode(), resp.getStatusText()));
error.setPostData(data);
error.setRequestURL(url);
if (resp.getStatusCode() == 401 || resp.getStatusCode() == 403) {
error.setName("Not Authorized");
error.setMessage(errorTranslation.httpError401or403());
// force reload page if it is the first getPerunPrincipal call, otherwise keep it to alert box
if (Cookies.getCookie("XSRF-TOKEN") != null &&
localStorage.getItem("csrf") == null &&
url.contains("authzResolver") &&
url.contains("getPerunPrincipal")
) {
localStorage.setItem("csrf", "reload");
showErrorMessage = false;
Window.Location.reload();
} else {
showErrorMessage = true;
}
} else if (resp.getStatusCode() == 500) {
if (runningRequests.get(callbackName) != null) {
// 5 minute timeout for POST callbacks
if ((runningRequests.get(callbackName).getDuration() / (1000)) >= 5 && checkIfPending) {
counter++;
layout.setHTML("Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: " + counter);
if (!shown && counter > 0) modal.show();
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
boolean again = true;
@Override
public boolean execute() {
if (again) {
UtilsManager.getPendingRequest(callbackName, new JsonEvents() {
@Override
public void onFinished(JavaScriptObject jso) {
final PerunRequest req = jso.cast();
if ((req.getCallbackName().equals(perunRequest.getStartTime() + "")) && req.getEndTime() > 0) {
if (again) {
again = false;
counter--;
layout.setHTML("Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: " + counter);
// hide notification
if (shown && counter <= 0) modal.hide();
JavaScriptObject result = req.getResult();
// check JSO, if not PerunException
if (result != null) {
PerunException error = (PerunException) result;
if (error.getErrorId() != null && error.getMessage() != null) {
error.setRequestURL(url);
error.setPostData((json != null) ? json.toString() : "");
if (checkIfPending) runningRequests.remove(callbackName);
events.onError(error);
return;
}
}
// Response is OK (object or null)
if (checkIfPending) runningRequests.remove(callbackName);
events.onFinished(result);
}
}
}
@Override
public void onError(PerunException error) {
}
@Override
public void onLoadingStart() {
}
});
}
return again;
}
}, ((PerunWebConstants) GWT.create(PerunWebConstants.class)).pendingRequestsRefreshInterval());
return;
} else {
error.setName("ServerInternalError");
error.setMessage(errorTranslation.httpError500());
}
}
} else if (resp.getStatusCode() == 503) {
error.setName("Server Temporarily Unavailable");
error.setMessage(errorTranslation.httpError503());
} else if (resp.getStatusCode() == 404) {
error.setName("Not found");
error.setMessage(errorTranslation.httpError404());
} else if (resp.getStatusCode() == 0) {
error.setName("Aborted");
error.setMessage(errorTranslation.httpError0());
// force reload page if it's first GUI call, otherwise keep it to alert box
if (runningRequests.get(requestUrl) != null && runningRequests.get(requestUrl).getManager().equals("authzResolver") &&
runningRequests.get(requestUrl).getMethod().equals("getPerunPrincipal")) {
Window.Location.reload();
}
}
if (checkIfPending) runningRequests.remove(requestUrl);
if (showErrorMessage) {
handleErrors(error);
}
}
}
@Override
public void onError(Request req, Throwable exc) {
// request not sent
handleErrors(parseResponse(callbackName, exc.toString()));
}
});
return request;
} catch (RequestException exc) {
// usually couldn't connect to server
handleErrors(parseResponse(callbackName, exc.toString()));
}
// request failed
return null;
}
/**
* Handles callback errors before passing them to events handler.
*
* @param jso retrieved data (error response)
*/
private void handleErrors(JavaScriptObject jso) {
if (jso != null) {
events.onError((PerunException) jso);
} else {
PerunException error = PerunException.createNew("0", "Cross-site request", errorTranslation.httpError0CrossSite());
error.setRequestURL(requestUrl);
error.setPostData(json.toString());
events.onError(error);
}
}
/**
* Parse server response so it can be evaluated as JSON.
* If primitive type is returned, it's wrapped as BasicOverlayObject
*
* @param callbackName unique name associated with this callback
* @param resp server response
* @return returned data as JavaScriptObject
*/
private JavaScriptObject parseResponse(String callbackName, String resp) {
// we don't send callback name if checkIfPending == false
if (!checkIfPending) callbackName = "null";
if (resp == null || resp.isEmpty()) return null;
// trims the whitespace
resp = resp.trim();
// short comparing
if ((callbackName + "(null);").equalsIgnoreCase(resp)) {
return null;
}
// if starts with 'callbackPost(' and ends with ')'or ');' == wrapped => must be unwrapped
RegExp re = RegExp.compile("^" + callbackName + "\\((.*)\\)|\\);$");
MatchResult result = re.exec(resp);
if (result != null) {
resp = result.getGroup(1);
}
// if response == null => return null
if (resp.equalsIgnoreCase("null")) {
return null;
}
// normal object
JavaScriptObject jso = JsonUtils.parseJson(resp);
return jso;
}
}
| perun-wui-core/src/main/java/cz/metacentrum/perun/wui/json/JsonClient.java | package cz.metacentrum.perun.wui.json;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import cz.metacentrum.perun.wui.client.resources.PerunErrorTranslation;
import cz.metacentrum.perun.wui.client.resources.PerunSession;
import cz.metacentrum.perun.wui.client.resources.PerunWebConstants;
import cz.metacentrum.perun.wui.json.managers.UtilsManager;
import cz.metacentrum.perun.wui.model.PerunException;
import cz.metacentrum.perun.wui.model.common.PerunRequest;
import cz.metacentrum.perun.wui.widgets.PerunButton;
import org.gwtbootstrap3.client.shared.event.ModalHiddenEvent;
import org.gwtbootstrap3.client.shared.event.ModalHiddenHandler;
import org.gwtbootstrap3.client.shared.event.ModalShownEvent;
import org.gwtbootstrap3.client.shared.event.ModalShownHandler;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.ModalBody;
import org.gwtbootstrap3.client.ui.ModalFooter;
import org.gwtbootstrap3.client.ui.ModalHeader;
import org.gwtbootstrap3.client.ui.html.Paragraph;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Client class performing GET/POST requests to Perun's API.
* For each call, new instance must be created.
*
* @author Pavel Zlámal <[email protected]>
*/
public class JsonClient {
private JsonEvents events = new JsonEvents() {
@Override
public void onFinished(JavaScriptObject jso) {
}
@Override
public void onError(PerunException error) {
}
@Override
public void onLoadingStart() {
}
};
private String urlPrefix = PerunSession.getInstance().getRpcUrl();
private String requestUrl;
private JSONObject json = new JSONObject();
private boolean checkIfPending = false;
private PerunErrorTranslation errorTranslation = GWT.create(PerunErrorTranslation.class);
private Map<String, PerunRequest> runningRequests = new HashMap<>();
private static Paragraph layout = new Paragraph();
private static int counter = 0;
private static Modal modal;
private static boolean shown = false;
/**
* New JsonClient using GET method
*/
public JsonClient() {
// init modal dialog
if (modal == null) {
modal = new Modal();
modal.setClosable(true);
modal.addShownHandler(new ModalShownHandler() {
@Override
public void onShown(ModalShownEvent modalShownEvent) {
shown = true;
}
});
modal.addHiddenHandler(new ModalHiddenHandler() {
@Override
public void onHidden(ModalHiddenEvent modalHiddenEvent) {
shown = false;
}
});
ModalHeader header = new ModalHeader();
header.setTitle("Processing long request");
modal.add(header);
ModalBody body = new ModalBody();
body.add(layout);
modal.add(body);
ModalFooter footer = new ModalFooter();
PerunButton close = new PerunButton("Hide");
close.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
modal.hide();
}
});
footer.add(close);
modal.add(footer);
}
}
/**
* Create new JsonClient
*
* @param checkIfPending If {@code true} check for callback results even after server timeout.
*/
public JsonClient(boolean checkIfPending) {
this();
this.checkIfPending = checkIfPending;
}
/**
* Create new JsonClient
*
* @param events events, which handles retrieved response
*/
public JsonClient(JsonEvents events) {
this();
if (events != null) this.events = events;
}
/**
* Create new JsonClient
*
* @param checkIfPending If {@code true} check for callback results even after server timeout.
* @param events events, which handles retrieved response
*/
public JsonClient(boolean checkIfPending, JsonEvents events) {
this(checkIfPending);
if (events != null) this.events = events;
}
/**
* Put custom parameter into payload of a request.
*
* @param key key (parameter name)
* @param data int data to send (parameter value)
*/
public void put(String key, int data) {
put(key, new JSONNumber(data));
}
/**
* Put custom parameter into payload of a request.
*
* @param key key (parameter name)
* @param data String data to send (parameter value)
*/
public void put(String key, String data) {
put(key, new JSONString(data));
}
/**
* Put custom parameter into payload of a request.
*
* @param key key (parameter name)
* @param data boolean data to send (parameter value)
*/
public void put(String key, boolean data) {
put(key, JSONBoolean.getInstance(data));
}
/**
* Put custom parameter into payload of a request.
*
* @param key key (parameter name)
* @param data JavaScriptObject data to send (parameter value)
*/
public <T extends JavaScriptObject> void put(String key, T data) {
put(key, JsonUtils.convertToJSON(data));
}
/**
* Put custom parameter into payload of a request.
*
* @param key key (parameter name)
* @param data List data to send as one parameter (parameter values)
*/
public void put(String key, List<? extends Object> data) {
JSONArray array = new JSONArray();
for (int i=0; i<data.size(); i++) {
if (data.get(i).getClass().isEnum()) {
array.set(i, new JSONString(data.get(i).toString()));
} else if (data.get(i) instanceof JavaScriptObject) {
array.set(i, JsonUtils.convertToJSON((JavaScriptObject)data.get(i)));
} else if (data.get(i) instanceof Integer) {
array.set(i, new JSONNumber(((Integer) data.get(i)).intValue()));
} else if (data.get(i) instanceof String) {
array.set(i, new JSONString(((String) data.get(i))));
} else if (data.get(i) instanceof Boolean) {
array.set(i, JSONBoolean.getInstance(((Boolean) data.get(i)).booleanValue()));
}
}
put(key, array);
}
/**
* Actually put parameter into payload of a request.
*
* @param key key (parameter name)
* @param data data to send in a JSON valid format (parameter value)
*/
private void put(String key, JSONValue data) {
json.put(key, data);
}
/**
* Call specific URL with custom events.
*
* @param url URL to send data to
* @return Request unique handling Request
*/
public Request call(final String url) {
final PerunRequest perunRequest = new JSONObject().getJavaScriptObject().cast();
perunRequest.setStartTime();
final String callbackName = perunRequest.getStartTime()+"";
if (checkIfPending) runningRequests.put(callbackName, perunRequest);
// build request URL
this.requestUrl = URL.encode(urlPrefix + url + ((checkIfPending) ? ("?callback=" + callbackName) : ""));
// we do use POST every time in order to use JSON deserializer on server side
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, requestUrl);
if (Cookies.getCookie("XSRF-TOKEN") != null) {
builder.setHeader("X-XSRF-TOKEN", Cookies.getCookie("XSRF-TOKEN"));
}
try {
events.onLoadingStart();
final String data = (json != null && json.isObject() != null) ? json.toString() : "";
Request request = builder.sendRequest(data, new RequestCallback() {
@Override
public void onResponseReceived(Request req, Response resp) {
// make JSO from textual JSON response
JavaScriptObject jso = parseResponse(callbackName, resp.getText());
// HTTP status code is OK
if (resp.getStatusCode() == 200) {
// check JSO, if not PerunException
if (jso != null) {
PerunException error = (PerunException)jso;
if (error.getErrorId() != null && error.getMessage() != null) {
error.setRequestURL(url);
error.setPostData((json != null) ? json.toString() : "");
if (checkIfPending) runningRequests.remove(callbackName);
events.onError(error);
return;
}
}
// Response is OK (object or null)
if (checkIfPending) runningRequests.remove(callbackName);
events.onFinished(jso);
} else {
// HTTP status code != OK (200)
PerunException error = new JSONObject().getJavaScriptObject().cast();
error.setErrorId("" + resp.getStatusCode());
error.setName(resp.getStatusText());
error.setMessage(errorTranslation.httpErrorAny(resp.getStatusCode(), resp.getStatusText()));
error.setPostData(data);
error.setRequestURL(url);
if (resp.getStatusCode() == 401 || resp.getStatusCode() == 403) {
error.setName("Not Authorized");
error.setMessage(errorTranslation.httpError401or403());
} else if (resp.getStatusCode() == 500) {
if (runningRequests.get(callbackName) != null) {
// 5 minute timeout for POST callbacks
if ((runningRequests.get(callbackName).getDuration() / (1000)) >= 5 && checkIfPending) {
counter++;
layout.setHTML("Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: " + counter);
if (!shown && counter > 0) modal.show();
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
boolean again = true;
@Override
public boolean execute() {
if (again) {
UtilsManager.getPendingRequest(callbackName, new JsonEvents() {
@Override
public void onFinished(JavaScriptObject jso) {
final PerunRequest req = jso.cast();
if ((req.getCallbackName().equals(perunRequest.getStartTime() + "")) && req.getEndTime() > 0) {
if (again) {
again = false;
counter--;
layout.setHTML("Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: " + counter);
// hide notification
if (shown && counter <= 0) modal.hide();
JavaScriptObject result = req.getResult();
// check JSO, if not PerunException
if (result != null) {
PerunException error = (PerunException) result;
if (error.getErrorId() != null && error.getMessage() != null) {
error.setRequestURL(url);
error.setPostData((json != null) ? json.toString() : "");
if (checkIfPending) runningRequests.remove(callbackName);
events.onError(error);
return;
}
}
// Response is OK (object or null)
if (checkIfPending) runningRequests.remove(callbackName);
events.onFinished(result);
}
}
}
@Override
public void onError(PerunException error) {
}
@Override
public void onLoadingStart() {
}
});
}
return again;
}
}, ((PerunWebConstants) GWT.create(PerunWebConstants.class)).pendingRequestsRefreshInterval());
return;
} else {
error.setName("ServerInternalError");
error.setMessage(errorTranslation.httpError500());
}
}
} else if (resp.getStatusCode() == 503) {
error.setName("Server Temporarily Unavailable");
error.setMessage(errorTranslation.httpError503());
} else if (resp.getStatusCode() == 404) {
error.setName("Not found");
error.setMessage(errorTranslation.httpError404());
} else if (resp.getStatusCode() == 0) {
error.setName("Aborted");
error.setMessage(errorTranslation.httpError0());
// force reload page if it's first GUI call, otherwise keep it to alert box
if (runningRequests.get(requestUrl) != null && runningRequests.get(requestUrl).getManager().equals("authzResolver") &&
runningRequests.get(requestUrl).getMethod().equals("getPerunPrincipal")) {
Window.Location.reload();
}
}
if (checkIfPending) runningRequests.remove(requestUrl);
handleErrors(error);
}
}
@Override
public void onError(Request req, Throwable exc) {
// request not sent
handleErrors(parseResponse(callbackName, exc.toString()));
}
});
return request;
} catch (RequestException exc) {
// usually couldn't connect to server
handleErrors(parseResponse(callbackName, exc.toString()));
}
// request failed
return null;
}
/**
* Handles callback errors before passing them to events handler.
*
* @param jso retrieved data (error response)
*/
private void handleErrors(JavaScriptObject jso) {
if (jso != null) {
events.onError((PerunException) jso);
} else {
PerunException error = PerunException.createNew("0", "Cross-site request", errorTranslation.httpError0CrossSite());
error.setRequestURL(requestUrl);
error.setPostData(json.toString());
events.onError(error);
}
}
/**
* Parse server response so it can be evaluated as JSON.
* If primitive type is returned, it's wrapped as BasicOverlayObject
*
* @param callbackName unique name associated with this callback
* @param resp server response
* @return returned data as JavaScriptObject
*/
private JavaScriptObject parseResponse(String callbackName, String resp) {
// we don't send callback name if checkIfPending == false
if (!checkIfPending) callbackName = "null";
if (resp == null || resp.isEmpty()) return null;
// trims the whitespace
resp = resp.trim();
// short comparing
if ((callbackName + "(null);").equalsIgnoreCase(resp)) {
return null;
}
// if starts with 'callbackPost(' and ends with ')'or ');' == wrapped => must be unwrapped
RegExp re = RegExp.compile("^" + callbackName + "\\((.*)\\)|\\);$");
MatchResult result = re.exec(resp);
if (result != null) {
resp = result.getGroup(1);
}
// if response == null => return null
if (resp.equalsIgnoreCase("null")) {
return null;
}
// normal object
JavaScriptObject jso = JsonUtils.parseJson(resp);
return jso;
}
}
| fix(registrar): CSRF authentication bug
* Second request sometimes fails with 403 due to CSRF cookie and user have to refresh window.
| perun-wui-core/src/main/java/cz/metacentrum/perun/wui/json/JsonClient.java | fix(registrar): CSRF authentication bug | <ide><path>erun-wui-core/src/main/java/cz/metacentrum/perun/wui/json/JsonClient.java
<ide> import com.google.gwt.json.client.JSONValue;
<ide> import com.google.gwt.regexp.shared.MatchResult;
<ide> import com.google.gwt.regexp.shared.RegExp;
<add>import com.google.gwt.storage.client.Storage;
<ide> import com.google.gwt.user.client.Cookies;
<ide> import com.google.gwt.user.client.Window;
<ide> import cz.metacentrum.perun.wui.client.resources.PerunErrorTranslation;
<ide> private static int counter = 0;
<ide> private static Modal modal;
<ide> private static boolean shown = false;
<add> public static Storage localStorage = Storage.getLocalStorageIfSupported();
<add> public boolean showErrorMessage = true;
<ide>
<ide> /**
<ide> * New JsonClient using GET method
<ide> // HTTP status code is OK
<ide> if (resp.getStatusCode() == 200) {
<ide>
<add> // remove csrf check from localStorage if the request is successful
<add> if (localStorage.getItem("csrf") != null) {
<add> localStorage.removeItem("csrf");
<add> }
<add>
<ide> // check JSO, if not PerunException
<ide> if (jso != null) {
<ide>
<ide> error.setName("Not Authorized");
<ide> error.setMessage(errorTranslation.httpError401or403());
<ide>
<add> // force reload page if it is the first getPerunPrincipal call, otherwise keep it to alert box
<add> if (Cookies.getCookie("XSRF-TOKEN") != null &&
<add> localStorage.getItem("csrf") == null &&
<add> url.contains("authzResolver") &&
<add> url.contains("getPerunPrincipal")
<add> ) {
<add> localStorage.setItem("csrf", "reload");
<add> showErrorMessage = false;
<add> Window.Location.reload();
<add> } else {
<add> showErrorMessage = true;
<add> }
<add>
<ide> } else if (resp.getStatusCode() == 500) {
<ide>
<ide> if (runningRequests.get(callbackName) != null) {
<ide> }
<ide>
<ide> if (checkIfPending) runningRequests.remove(requestUrl);
<del> handleErrors(error);
<del>
<add> if (showErrorMessage) {
<add> handleErrors(error);
<add> }
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 4403befbf053504b461c4282416d21ad5bdf5cf0 | 0 | mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.index;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.ASYNC_PROPERTY_NAME;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_DEFINITIONS_NAME;
import static org.apache.jackrabbit.oak.plugins.index.IndexUtils.createIndexDefinition;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.common.collect.Sets;
import org.apache.jackrabbit.oak.OakBaseTest;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.fixture.NodeStoreFixture;
import org.apache.jackrabbit.oak.plugins.index.AsyncIndexUpdate.AsyncIndexStats;
import org.apache.jackrabbit.oak.plugins.index.AsyncIndexUpdate.AsyncUpdateCallback;
import org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexEditorProvider;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.apache.jackrabbit.oak.stats.Clock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableSet;
public class AsyncIndexUpdateLeaseTest extends OakBaseTest {
private final String name = "async";
private IndexEditorProvider provider;
private final AtomicBoolean executed = new AtomicBoolean(false);
public AsyncIndexUpdateLeaseTest(NodeStoreFixture fixture) {
super(fixture);
}
@Before
public void setup() throws Exception {
provider = new PropertyIndexEditorProvider();
NodeBuilder builder = store.getRoot().builder();
createIndexDefinition(builder.child(INDEX_DEFINITIONS_NAME),
"rootIndex", true, false, ImmutableSet.of("foo"), null)
.setProperty(ASYNC_PROPERTY_NAME, name);
builder.child("testRoot").setProperty("foo", "abc");
store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
executed.set(false);
}
@After
public void cleanup() throws Exception {
assertTrue("Test method was not executed", executed.get());
String referenced = getReferenceCp(store, name);
assertNotNull("Reference checkpoint doesn't exist", referenced);
assertNotNull(
"Failed indexer must not clean successful indexer's checkpoint",
store.retrieve(referenced));
}
@Test
public void testPrePrepare() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void prePrepare() {
executed.set(true);
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostPrepare() {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postPrepare() {
executed.set(true);
// lease must prevent this run
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPreIndexUpdate() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
testContent(store);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void preIndexUpdate() {
executed.set(true);
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostIndexUpdate() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
testContent(store);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postIndexUpdate() {
executed.set(true);
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPreClose() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
testContent(store);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void preClose() {
executed.set(true);
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostPrepareLeaseExpired() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postPrepare() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testPreIndexUpdateLeaseExpired() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
// add extra indexed content
testContent(store);
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void preIndexUpdate() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testPostIndexUpdateLeaseExpired() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
// add extra indexed content
testContent(store);
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postIndexUpdate() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testPrePrepareRexindex() throws Exception {
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void prePrepare() {
executed.set(true);
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostPrepareReindex() {
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postPrepare() {
executed.set(true);
// lease must prevent this run
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPreIndexUpdateReindex() throws Exception {
testContent(store);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void preIndexUpdate() {
executed.set(true);
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostIndexUpdateReindex() throws Exception {
testContent(store);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postIndexUpdate() {
executed.set(true);
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostPrepareReindexLeaseExpired() throws Exception {
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postPrepare() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testPreIndexUpdateReindexLeaseExpired() throws Exception {
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void preIndexUpdate() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testPostIndexUpdateReindexLeaseExpired() throws Exception {
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postIndexUpdate() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testLeaseDisabled() throws Exception {
// take care of initial reindex before
AsyncIndexUpdate async = new AsyncIndexUpdate(name, store, provider).setLeaseTimeOut(0);
async.run();
testContent(store);
assertRunOk(async);
testContent(store);
assertRunOk(async);
executed.set(true);
}
@Test
public void testLeaseExpiredToDisabled() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
// add extra indexed content
testContent(store);
// make it look like lease got stuck due to force shutdown
NodeBuilder builder = store.getRoot().builder();
builder.getChildNode(AsyncIndexUpdate.ASYNC).setProperty(
AsyncIndexUpdate.leasify(name),
System.currentTimeMillis() + 500000);
store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postIndexUpdate() {
executed.set(true);
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(0));
assertFalse("Stale lease info must be cleaned",
store.getRoot().getChildNode(AsyncIndexUpdate.ASYNC)
.hasProperty(AsyncIndexUpdate.leasify(name)));
}
@Test
public void testLeaseUpdateAndNumberOfChanges() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
final long lease = 50;
testContent(store, AsyncUpdateCallback.LEASE_CHECK_INTERVAL / 2);
Set<Long> leaseTimes = Sets.newHashSet();
final Clock.Virtual clock = new Clock.Virtual();
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postPrepare() {
collectLeaseTimes();
}
@Override
protected void postTraverseNode() {
collectLeaseTimes();
if (!executed.get()) {
clock.waitUntil(clock.getTime() + lease * 3);
}
executed.set(true);
}
private void collectLeaseTimes() {
leaseTimes.add(getLeaseValue());
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1, clock)
.setLeaseTimeOut(lease));
assertEquals(1, leaseTimes.size());
executed.set(false);
leaseTimes.clear();
//Run with changes more than threshold and then lease should change more than once
testContent(store, AsyncUpdateCallback.LEASE_CHECK_INTERVAL * 2);
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1, clock)
.setLeaseTimeOut(lease));
assertTrue(leaseTimes.size() > 1);
}
// -------------------------------------------------------------------
private long getLeaseValue() {
return store.getRoot().getChildNode(":async").getLong( AsyncIndexUpdate.leasify(name));
}
private static String getReferenceCp(NodeStore store, String name) {
return store.getRoot().getChildNode(AsyncIndexUpdate.ASYNC)
.getString(name);
}
private void assertRunOk(AsyncIndexUpdate a) {
assertRun(a, false);
}
private void assertRunKo(AsyncIndexUpdate a) {
assertRun(a, true);
assertConcurrentUpdate(a.getIndexStats());
}
private void assertRun(AsyncIndexUpdate a, boolean failing) {
a.run();
assertEquals("Unexpected failiure flag", failing, a.isFailing());
}
private void assertConcurrentUpdate(AsyncIndexStats stats) {
assertTrue("Error must be of type 'Concurrent update'", stats
.getLatestError().contains("Concurrent update detected"));
}
private static void testContent(NodeStore store) throws Exception {
NodeBuilder builder = store.getRoot().builder();
builder.child("testRoot").setProperty("foo",
"abc " + System.currentTimeMillis());
store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
}
private static void testContent(NodeStore store, int numOfNodes) throws Exception {
NodeBuilder builder = store.getRoot().builder();
for (int i = 0; i < numOfNodes; i++) {
builder.child("testRoot"+i).setProperty("foo",
"abc " + System.currentTimeMillis());
}
store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
}
private static class SpecialAsyncIndexUpdate extends AsyncIndexUpdate {
private final IndexStatusListener listener;
private final Clock clock;
public SpecialAsyncIndexUpdate(String name, NodeStore store,
IndexEditorProvider provider, IndexStatusListener listener) {
this(name, store, provider, listener, Clock.SIMPLE);
}
public SpecialAsyncIndexUpdate(String name, NodeStore store,
IndexEditorProvider provider, IndexStatusListener listener, Clock clock) {
super(name, store, provider);
this.listener = listener;
this.clock = clock;
}
@Override
public synchronized void run() {
super.run();
}
@Override
protected AsyncUpdateCallback newAsyncUpdateCallback(NodeStore store,
String name, long leaseTimeOut, String checkpoint,
AsyncIndexStats indexStats,
AtomicBoolean stopFlag) {
return new SpecialAsyncUpdateCallback(store, name, leaseTimeOut,
checkpoint, indexStats, stopFlag, listener, clock);
}
}
private static class SpecialAsyncUpdateCallback extends AsyncUpdateCallback {
private IndexStatusListener listener;
private final Clock clock;
public SpecialAsyncUpdateCallback(NodeStore store, String name,
long leaseTimeOut, String checkpoint,
AsyncIndexStats indexStats, AtomicBoolean stopFlag, IndexStatusListener listener, Clock clock) {
super(store, name, leaseTimeOut, checkpoint, indexStats, stopFlag);
this.listener = listener;
this.clock = clock;
}
@Override
protected void prepare(String afterCheckpoint) throws CommitFailedException {
listener.prePrepare();
super.prepare(afterCheckpoint);
listener.postPrepare();
}
@Override
public void indexUpdate() throws CommitFailedException {
listener.preIndexUpdate();
super.indexUpdate();
listener.postIndexUpdate();
}
@Override
public void traversedNode() throws CommitFailedException {
listener.preTraverseNode();
super.traversedNode();
listener.postTraverseNode();
}
@Override
void close() throws CommitFailedException {
listener.preClose();
super.close();
listener.postClose();
}
@Override
protected long getTime() {
return clock.getTime();
}
}
private abstract static class IndexStatusListener {
protected void prePrepare() {
}
protected void postPrepare() {
}
protected void preIndexUpdate() {
}
protected void postIndexUpdate() {
}
protected void preTraverseNode() {
}
protected void postTraverseNode() {
}
protected void preClose() {
}
protected void postClose() {
}
}
}
| oak-it/src/test/java/org/apache/jackrabbit/oak/plugins/index/AsyncIndexUpdateLeaseTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.index;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.ASYNC_PROPERTY_NAME;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_DEFINITIONS_NAME;
import static org.apache.jackrabbit.oak.plugins.index.IndexUtils.createIndexDefinition;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.common.collect.Sets;
import org.apache.jackrabbit.oak.OakBaseTest;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.fixture.NodeStoreFixture;
import org.apache.jackrabbit.oak.plugins.index.AsyncIndexUpdate.AsyncIndexStats;
import org.apache.jackrabbit.oak.plugins.index.AsyncIndexUpdate.AsyncUpdateCallback;
import org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexEditorProvider;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.apache.jackrabbit.oak.stats.Clock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableSet;
public class AsyncIndexUpdateLeaseTest extends OakBaseTest {
private final String name = "async";
private IndexEditorProvider provider;
private final AtomicBoolean executed = new AtomicBoolean(false);
public AsyncIndexUpdateLeaseTest(NodeStoreFixture fixture) {
super(fixture);
}
@Before
public void setup() throws Exception {
provider = new PropertyIndexEditorProvider();
NodeBuilder builder = store.getRoot().builder();
createIndexDefinition(builder.child(INDEX_DEFINITIONS_NAME),
"rootIndex", true, false, ImmutableSet.of("foo"), null)
.setProperty(ASYNC_PROPERTY_NAME, name);
builder.child("testRoot").setProperty("foo", "abc");
store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
executed.set(false);
}
@After
public void cleanup() throws Exception {
assertTrue("Test method was not executed", executed.get());
String referenced = getReferenceCp(store, name);
assertNotNull("Reference checkpoint doesn't exist", referenced);
assertNotNull(
"Failed indexer must not clean successful indexer's checkpoint",
store.retrieve(referenced));
}
@Test
public void testPrePrepare() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void prePrepare() {
executed.set(true);
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostPrepare() {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postPrepare() {
executed.set(true);
// lease must prevent this run
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPreIndexUpdate() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
testContent(store);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void preIndexUpdate() {
executed.set(true);
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostIndexUpdate() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
testContent(store);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postIndexUpdate() {
executed.set(true);
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPreClose() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
testContent(store);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void preClose() {
executed.set(true);
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostPrepareLeaseExpired() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postPrepare() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testPreIndexUpdateLeaseExpired() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
// add extra indexed content
testContent(store);
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void preIndexUpdate() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testPostIndexUpdateLeaseExpired() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
// add extra indexed content
testContent(store);
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postIndexUpdate() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testPrePrepareRexindex() throws Exception {
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void prePrepare() {
executed.set(true);
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostPrepareReindex() {
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postPrepare() {
executed.set(true);
// lease must prevent this run
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPreIndexUpdateReindex() throws Exception {
testContent(store);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void preIndexUpdate() {
executed.set(true);
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostIndexUpdateReindex() throws Exception {
testContent(store);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postIndexUpdate() {
executed.set(true);
assertRunKo(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1));
}
@Test
public void testPostPrepareReindexLeaseExpired() throws Exception {
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postPrepare() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testPreIndexUpdateReindexLeaseExpired() throws Exception {
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void preIndexUpdate() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testPostIndexUpdateReindexLeaseExpired() throws Exception {
final long lease = 50;
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postIndexUpdate() {
executed.set(true);
try {
TimeUnit.MILLISECONDS.sleep(lease * 3);
} catch (InterruptedException e) {
//
}
assertRunOk(new AsyncIndexUpdate(name, store, provider));
}
};
assertRunKo(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(lease));
}
@Test
public void testLeaseDisabled() throws Exception {
// take care of initial reindex before
AsyncIndexUpdate async = new AsyncIndexUpdate(name, store, provider).setLeaseTimeOut(0);
async.run();
testContent(store);
assertRunOk(async);
testContent(store);
assertRunOk(async);
executed.set(true);
}
@Test
public void testLeaseExpiredToDisabled() throws Exception {
// take care of initial reindex before
new AsyncIndexUpdate(name, store, provider).run();
// add extra indexed content
testContent(store);
// make it look like lease got stuck due to force shutdown
NodeBuilder builder = store.getRoot().builder();
builder.getChildNode(AsyncIndexUpdate.ASYNC).setProperty(
AsyncIndexUpdate.leasify(name),
System.currentTimeMillis() + 500000);
store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postIndexUpdate() {
executed.set(true);
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1)
.setLeaseTimeOut(0));
assertFalse("Stale lease info must be cleaned",
store.getRoot().getChildNode(AsyncIndexUpdate.ASYNC)
.hasProperty(AsyncIndexUpdate.leasify(name)));
}
@Test
public void testLeaseUpdateAndNumberOfChanges() throws Exception {
final long lease = 50;
testContent(store, AsyncUpdateCallback.LEASE_CHECK_INTERVAL / 2);
Set<Long> leaseTimes = Sets.newHashSet();
final Clock.Virtual clock = new Clock.Virtual();
final IndexStatusListener l1 = new IndexStatusListener() {
@Override
protected void postPrepare() {
collectLeaseTimes();
}
@Override
protected void postTraverseNode() {
collectLeaseTimes();
if (!executed.get()) {
clock.waitUntil(clock.getTime() + lease * 3);
}
executed.set(true);
}
private void collectLeaseTimes() {
leaseTimes.add(getLeaseValue());
}
};
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1, clock)
.setLeaseTimeOut(lease));
assertEquals(1, leaseTimes.size());
executed.set(false);
leaseTimes.clear();
//Run with changes more than threshold and then lease should change more than once
testContent(store, AsyncUpdateCallback.LEASE_CHECK_INTERVAL * 2);
assertRunOk(new SpecialAsyncIndexUpdate(name, store, provider, l1, clock)
.setLeaseTimeOut(lease));
assertTrue(leaseTimes.size() > 1);
}
// -------------------------------------------------------------------
private long getLeaseValue() {
return store.getRoot().getChildNode(":async").getLong( AsyncIndexUpdate.leasify(name));
}
private static String getReferenceCp(NodeStore store, String name) {
return store.getRoot().getChildNode(AsyncIndexUpdate.ASYNC)
.getString(name);
}
private void assertRunOk(AsyncIndexUpdate a) {
assertRun(a, false);
}
private void assertRunKo(AsyncIndexUpdate a) {
assertRun(a, true);
assertConcurrentUpdate(a.getIndexStats());
}
private void assertRun(AsyncIndexUpdate a, boolean failing) {
a.run();
assertEquals("Unexpected failiure flag", failing, a.isFailing());
}
private void assertConcurrentUpdate(AsyncIndexStats stats) {
assertTrue("Error must be of type 'Concurrent update'", stats
.getLatestError().contains("Concurrent update detected"));
}
private static void testContent(NodeStore store) throws Exception {
NodeBuilder builder = store.getRoot().builder();
builder.child("testRoot").setProperty("foo",
"abc " + System.currentTimeMillis());
store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
}
private static void testContent(NodeStore store, int numOfNodes) throws Exception {
NodeBuilder builder = store.getRoot().builder();
for (int i = 0; i < numOfNodes; i++) {
builder.child("testRoot"+i).setProperty("foo",
"abc " + System.currentTimeMillis());
}
store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
}
private static class SpecialAsyncIndexUpdate extends AsyncIndexUpdate {
private final IndexStatusListener listener;
private final Clock clock;
public SpecialAsyncIndexUpdate(String name, NodeStore store,
IndexEditorProvider provider, IndexStatusListener listener) {
this(name, store, provider, listener, Clock.SIMPLE);
}
public SpecialAsyncIndexUpdate(String name, NodeStore store,
IndexEditorProvider provider, IndexStatusListener listener, Clock clock) {
super(name, store, provider);
this.listener = listener;
this.clock = clock;
}
@Override
public synchronized void run() {
super.run();
}
@Override
protected AsyncUpdateCallback newAsyncUpdateCallback(NodeStore store,
String name, long leaseTimeOut, String checkpoint,
AsyncIndexStats indexStats,
AtomicBoolean stopFlag) {
return new SpecialAsyncUpdateCallback(store, name, leaseTimeOut,
checkpoint, indexStats, stopFlag, listener, clock);
}
}
private static class SpecialAsyncUpdateCallback extends AsyncUpdateCallback {
private IndexStatusListener listener;
private final Clock clock;
public SpecialAsyncUpdateCallback(NodeStore store, String name,
long leaseTimeOut, String checkpoint,
AsyncIndexStats indexStats, AtomicBoolean stopFlag, IndexStatusListener listener, Clock clock) {
super(store, name, leaseTimeOut, checkpoint, indexStats, stopFlag);
this.listener = listener;
this.clock = clock;
}
@Override
protected void prepare(String afterCheckpoint) throws CommitFailedException {
listener.prePrepare();
super.prepare(afterCheckpoint);
listener.postPrepare();
}
@Override
public void indexUpdate() throws CommitFailedException {
listener.preIndexUpdate();
super.indexUpdate();
listener.postIndexUpdate();
}
@Override
public void traversedNode() throws CommitFailedException {
listener.preTraverseNode();
super.traversedNode();
listener.postTraverseNode();
}
@Override
void close() throws CommitFailedException {
listener.preClose();
super.close();
listener.postClose();
}
@Override
protected long getTime() {
return clock.getTime();
}
}
private abstract static class IndexStatusListener {
protected void prePrepare() {
}
protected void postPrepare() {
}
protected void preIndexUpdate() {
}
protected void postIndexUpdate() {
}
protected void preTraverseNode() {
}
protected void postTraverseNode() {
}
protected void preClose() {
}
protected void postClose() {
}
}
}
| OAK-5893 - Async index abort should work even during traversals without index updates
Given that traversedNode can be called in reindexing also the test
case should ensure that initial index update is done
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1796039 13f79535-47bb-0310-9956-ffa450edef68
| oak-it/src/test/java/org/apache/jackrabbit/oak/plugins/index/AsyncIndexUpdateLeaseTest.java | OAK-5893 - Async index abort should work even during traversals without index updates | <ide><path>ak-it/src/test/java/org/apache/jackrabbit/oak/plugins/index/AsyncIndexUpdateLeaseTest.java
<ide>
<ide> @Test
<ide> public void testLeaseUpdateAndNumberOfChanges() throws Exception {
<add> // take care of initial reindex before
<add> new AsyncIndexUpdate(name, store, provider).run();
<ide> final long lease = 50;
<ide> testContent(store, AsyncUpdateCallback.LEASE_CHECK_INTERVAL / 2);
<ide> Set<Long> leaseTimes = Sets.newHashSet(); |
|
Java | apache-2.0 | f2d122bd62394db030dd54634d26d82f17ed34fe | 0 | esaunders/autopsy,rcordovano/autopsy,APriestman/autopsy,dgrove727/autopsy,narfindustries/autopsy,dgrove727/autopsy,millmanorama/autopsy,karlmortensen/autopsy,esaunders/autopsy,APriestman/autopsy,mhmdfy/autopsy,millmanorama/autopsy,mhmdfy/autopsy,narfindustries/autopsy,APriestman/autopsy,esaunders/autopsy,karlmortensen/autopsy,narfindustries/autopsy,millmanorama/autopsy,APriestman/autopsy,rcordovano/autopsy,rcordovano/autopsy,millmanorama/autopsy,wschaeferB/autopsy,rcordovano/autopsy,rcordovano/autopsy,APriestman/autopsy,mhmdfy/autopsy,wschaeferB/autopsy,karlmortensen/autopsy,dgrove727/autopsy,wschaeferB/autopsy,rcordovano/autopsy,APriestman/autopsy,esaunders/autopsy,wschaeferB/autopsy,APriestman/autopsy,esaunders/autopsy,mhmdfy/autopsy,wschaeferB/autopsy,karlmortensen/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2011-2015 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.casemodule;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingWorker;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.util.actions.CallableSystemAction;
import org.openide.util.actions.Presenter;
/**
* The action to close the current Case. This class should be disabled on
* creation and it will be enabled on new case creation or case opened.
*/
public final class CaseCloseAction extends CallableSystemAction implements Presenter.Toolbar {
JButton toolbarButton = new JButton();
/**
* The constructor for this class
*/
public CaseCloseAction() {
putValue("iconBase", "org/sleuthkit/autopsy/images/close-icon.png"); // put the icon NON-NLS
putValue(Action.NAME, NbBundle.getMessage(CaseCloseAction.class, "CTL_CaseCloseAct")); // put the action Name
// set action of the toolbar button
toolbarButton.addActionListener(CaseCloseAction.this::actionPerformed);
this.setEnabled(false);
}
/**
* Closes the current opened case.
*
* @param e the action event for this method
*/
@Override
public void actionPerformed(ActionEvent e) {
if (Case.existsCurrentCase() == false) {
return;
}
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
try {
Case result = Case.getCurrentCase();
result.closeCase();
} catch (CaseActionException | IllegalStateException unused) {
// Already logged.
}
return null;
}
@Override
protected void done() {
StartupWindowProvider.getInstance().open();
}
}.execute();
}
/**
* This method does nothing. Use the "actionPerformed(ActionEvent e)"
* instead of this method.
*/
@Override
public void performAction() {
}
/**
* Gets the name of this action. This may be presented as an item in a menu.
*
* @return actionName
*/
@Override
public String getName() {
return NbBundle.getMessage(CaseCloseAction.class, "CTL_CaseCloseAct");
}
/**
* Gets the HelpCtx associated with implementing object
*
* @return HelpCtx or HelpCtx.DEFAULT_HELP
*/
@Override
public HelpCtx getHelpCtx() {
return HelpCtx.DEFAULT_HELP;
}
/**
* Returns the toolbar component of this action
*
* @return component the toolbar button
*/
@Override
public Component getToolbarPresenter() {
ImageIcon icon = new ImageIcon(getClass().getResource("btn_icon_close_case.png")); //NON-NLS
toolbarButton.setIcon(icon);
toolbarButton.setText(this.getName());
return toolbarButton;
}
/**
* Set this action to be enabled/disabled
*
* @param value whether to enable this action or not
*/
@Override
public void setEnabled(boolean value) {
super.setEnabled(value);
toolbarButton.setEnabled(value);
}
}
| Core/src/org/sleuthkit/autopsy/casemodule/CaseCloseAction.java | /*
* Autopsy Forensic Browser
*
* Copyright 2011-2015 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.casemodule;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingWorker;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.util.actions.CallableSystemAction;
import org.openide.util.actions.Presenter;
/**
* The action to close the current Case. This class should be disabled on
* creation and it will be enabled on new case creation or case opened.
*/
final class CaseCloseAction extends CallableSystemAction implements Presenter.Toolbar {
JButton toolbarButton = new JButton();
/**
* The constructor for this class
*/
public CaseCloseAction() {
putValue("iconBase", "org/sleuthkit/autopsy/images/close-icon.png"); // put the icon NON-NLS
putValue(Action.NAME, NbBundle.getMessage(CaseCloseAction.class, "CTL_CaseCloseAct")); // put the action Name
// set action of the toolbar button
toolbarButton.addActionListener(CaseCloseAction.this::actionPerformed);
this.setEnabled(false);
}
/**
* Closes the current opened case.
*
* @param e the action event for this method
*/
@Override
public void actionPerformed(ActionEvent e) {
if (Case.existsCurrentCase() == false) {
return;
}
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
try {
Case result = Case.getCurrentCase();
result.closeCase();
} catch (CaseActionException | IllegalStateException unused) {
// Already logged.
}
return null;
}
@Override
protected void done() {
StartupWindowProvider.getInstance().open();
}
}.execute();
}
/**
* This method does nothing. Use the "actionPerformed(ActionEvent e)"
* instead of this method.
*/
@Override
public void performAction() {
}
/**
* Gets the name of this action. This may be presented as an item in a menu.
*
* @return actionName
*/
@Override
public String getName() {
return NbBundle.getMessage(CaseCloseAction.class, "CTL_CaseCloseAct");
}
/**
* Gets the HelpCtx associated with implementing object
*
* @return HelpCtx or HelpCtx.DEFAULT_HELP
*/
@Override
public HelpCtx getHelpCtx() {
return HelpCtx.DEFAULT_HELP;
}
/**
* Returns the toolbar component of this action
*
* @return component the toolbar button
*/
@Override
public Component getToolbarPresenter() {
ImageIcon icon = new ImageIcon(getClass().getResource("btn_icon_close_case.png")); //NON-NLS
toolbarButton.setIcon(icon);
toolbarButton.setText(this.getName());
return toolbarButton;
}
/**
* Set this action to be enabled/disabled
*
* @param value whether to enable this action or not
*/
@Override
public void setEnabled(boolean value) {
super.setEnabled(value);
toolbarButton.setEnabled(value);
}
}
| Make CaseCloseAction public
| Core/src/org/sleuthkit/autopsy/casemodule/CaseCloseAction.java | Make CaseCloseAction public | <ide><path>ore/src/org/sleuthkit/autopsy/casemodule/CaseCloseAction.java
<ide> * The action to close the current Case. This class should be disabled on
<ide> * creation and it will be enabled on new case creation or case opened.
<ide> */
<del>final class CaseCloseAction extends CallableSystemAction implements Presenter.Toolbar {
<add>public final class CaseCloseAction extends CallableSystemAction implements Presenter.Toolbar {
<ide>
<ide> JButton toolbarButton = new JButton();
<ide> |
|
JavaScript | mit | e4e2d551f0d4ed164e82e2b11ec36c8df977d680 | 0 | 0x00evil/TiCachedImages,sukima/TiCachedImages,0x00evil/TiCachedImages,sukima/TiCachedImages | // FileLoader - A caching file downloader for Titanium
//
// Public Domain. Use, modify and distribute it any way you like. No attribution required.
//
// NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
//
// This is a reinvention of [David Geller's caching code][1]. It will download
// a file and cache it on the device allowing the cached version to be used
// instead of spawning repeated HTTP connections. It is based on the Promise/A+
// specifications and uses a modified version of [pinkySwear][2] to facilitate
// a promise based API for use in a Titanium project.
//
// ## Dependencies
// * None
//
// ## API
// Once required, the following methods are available:
//
// - `download()` - Attempt to download a file from a URL or offer a cached version.
// - `gc()` - Search the cache for any expired files and delete them (Garbage Collect).
//
// The `download()` method returns a [promise][3] object. This object can be
// used to attach callbacks to that you want to execute after the correct file
// path has been resolved (either by cache or downloaded). The callbacks are
// passed in a File object which has the following methods and properties:
//
// - `getFile()` - Returns a `Ti.FilesystemFile` object. Used to pass to a
// `ImageView.image`.
// - `getPath()` - Returns a string to the cached file. Used for properties
// that need a string not a file object (`TableViewRow.leftImage`)
// - `expired()` - Returns true/false for when the expired time has elapsed
// since this URL was last requested. By passing in true you will
// invalidate this file's cache forcing a download on next
// request.
// - `downloaded` - true if this URL was just downloaded, false if it was
// already in cached.
// - `is_cached` - true if this file has been cached or not.
//
// There are several others but these are the few you will need, if that. See more below.
//
// ## Promises
// The `download()` method returns a [pinkySwear][2] promise. You do not have
// to use promises if you do not want to. However I highly recommend their use.
// The internals are all managed via promises. If after reading this your still
// convinced to avoid them you can use callbacks like such:
//
// FileLoader.download({
// url: "http://example.com/image.png",
// onload: function(file) { imageView.image = file.getFile(); },
// onerror: function(error) { ... },
// ondatastream: function(progress) { ... }
// });
//
// That so not pretty, Let us promise to write better code:
//
// FileLoader.download("http://example.com/image.png")
// .then(function(file) { ... })
// .fail(function(error) { ... })
// .progress(function(progress) { ... });
//
// Much better. A promise is an object which will remain pending till an event
// assigns it a fulfilled value. Like an HTTP request sending it the
// responseData. When a promise is fulfilled or rejected the corresponding
// functions attached are called. The advantage with promises is that you can
// chain them:
//
// FileLoader.download("http://example.com/image.png")
// .then(function(file) { return file.getFile(); })
// .then(function(tiFile) { imageView.image = tiFile; });
//
// The modified pinkySwear in this file even offers two convenience methods for
// the above:
//
// FileLoader.download("http://example.com/image.png")
// .invoke("getFile")
// .then(function(tiFile) { imageView.image = tiFile; });
//
// With the modified pinkySwear promise you have the following methods at your
// disposal:
//
// - `then(fn)` - Attach callbacks (fulfilled, rejected, progress). Returns
// a new promise based on the return values / thrown
// exceptions of the callbacks.
// - `fail(fn)` - Same as `then(null, fn)`
// - `progress(fn)` - Same as `then(null, null, fn)`
// - `always(fn)` - Return a new promise which will resolve regardless if the
// former promise is fulfilled or rejected.
// - `fin(fn)` - Execute the function when the promise is fulfilled or
// rejected regardless. Returns the original promise to
// continue the chain.
// - `done()` - Any errors uncaught (or errors in the error function)
// will be rethrown. Ends the chain.
// - `get(prop)` - Same as `then(function(value) { return value[prop]; })`
// - `invoke(prop, args...)` -
// Same as `then(function(value) { return value[prop](args...); })`
//
// ## Configuration
//
// You can adjust the following variables either defined globals or in your
// `Alloy.CFG` namespace (Before your first `require()`):
//
// - `cache_property_key` - The `Ti.App.Property` key to use for storing the
// cache metadata.
// - `cache_expiration` - How long a cached file is considered expired since
// the last time it was requested.
// - `cache_directory` - The directory to save the cache files. On iOS the
// `applicationSupportDirectory` is prefixed. on all
// others the `applicationDataDirectory` is prefixed.
// - `cache_requests` - The number of simultaneous network requests allowed.
//
// [1]: http://developer.appcelerator.com/question/125483/how-to-create-a-generic-image-cache-sample-code#answer-218718
// [2]: https://github.com/timjansen/PinkySwear.js
// [3]: http://promises-aplus.github.io/promises-spec/
// Constants {{{1
// Load constants allowing them to be overwritten with configuration.
var HTTP_TIMEOUT = 10000;
var CACHE_METADATA_PROPERTY, EXPIRATION_TIME, CACHE_PATH_PREFIX, MAX_ASYNC_TASKS;
(function(global) {
var have_alloy = (typeof Alloy !== 'undefined' && Alloy !== null && Alloy.CFG);
function loadConfig(name) {
/* jshint eqnull:true */
if (have_alloy && Alloy.CFG[name] != null) {
return Alloy.CFG[name];
}
if (global[name] != null) {
return global[name];
}
}
CACHE_METADATA_PROPERTY = loadConfig("cache_property_key") || "file_loader_cache_metadata";
CACHE_PATH_PREFIX = loadConfig("cache_directory") || "cached_files";
EXPIRATION_TIME = loadConfig("cache_expiration") || 3600000; // 60 minutes
MAX_ASYNC_TASKS = loadConfig("cache_requests") || 10;
})(this);
// Metadata {{{1
var metadata = Ti.App.Properties.getObject(CACHE_METADATA_PROPERTY) || {};
function saveMetaData() {
Ti.App.Properties.setObject(CACHE_METADATA_PROPERTY, metadata);
}
// Cache path {{{1
// Make sure we have the directory to store files.
var cache_path = (function() {
var os = Ti.Platform.osname;
var data_dir = (os === "iphone" || os === "ipad") ?
Ti.Filesystem.applicationSupportDirectory :
Ti.Filesystem.applicationDataDirectory;
var cache_dir = Ti.Filesystem.getFile(data_dir, CACHE_PATH_PREFIX);
if (!cache_dir.exists()) {
cache_dir.createDirectory();
}
return cache_dir;
})();
// Class: File {{{1
// Constructor {{{2
function File(id) {
this.id = id;
var cache_data = metadata[this.id];
this.file_path = Ti.Filesystem.getFile(cache_path.resolve(), this.id);
if (cache_data) {
this.is_cached = this.exists();
this.last_used_at = cache_data.last_used_at;
this.md5 = cache_data.md5;
}
else {
this.is_cached = false;
this.last_used_at = 0;
this.md5 = null;
}
}
// File::updateLastUsedAt {{{2
File.prototype.updateLastUsedAt = function() {
this.last_used_at = new Date().getTime();
return this;
};
// File::save {{{2
File.prototype.save = function() {
metadata[this.id] = {
last_used_at: this.last_used_at,
md5: this.md5
};
saveMetaData();
this.is_cached = true;
return this;
};
// File::write {{{2
File.prototype.write = function(data) {
// A Titanium bug cause this to always return false. We need to manually
// check it exists. And assume it worked.
// (https://jira.appcelerator.org/browse/TIMOB-1658)
this.getFile().write(data);
this.md5 = File.getMD5(data);
// Ti.API.debug("Wrote " + this.getPath() + " (" + this.md5 + ")"); // DEBUG
return this.exists();
};
// File::exists {{{2
File.prototype.exists = function() {
return this.getFile().exists();
};
// File::expired {{{2
File.prototype.expired = function(invalidate) {
if (invalidate) {
this.last_used_at = 0;
this.save();
}
return ((new Date().getTime() - this.last_used_at) > EXPIRATION_TIME);
};
// File::expunge {{{2
File.prototype.expunge = function() {
this.getFile().deleteFile();
// Ti.API.debug("Expunged " + this.id); // DEBUG
delete metadata[this.id];
saveMetaData();
this.is_cached = false;
};
// File::getPath {{{2
File.prototype.getPath = function() {
return this.getFile().resolve();
};
// File::toString {{{2
File.prototype.toString = function() {
return "" + this.id + ": " +
(this.is_cached ? "cached" : "new") + " file" +
(this.pending ? " (pending)" : "") +
(this.downloaded ? " (downloaded)" : "") +
(this.expired() ? " (expired)" : "") +
(this.last_used_at ? ", Last used: " + this.last_used_at : "") +
(this.md5 ? ", MD5: " + this.md5 : "") +
" " + this.getPath();
};
// File.getFile {{{2
File.prototype.getFile = function() {
return this.file_path;
};
// File.getMD5 {{{2
File.getMD5 = function(data) {
return Ti.Utils.md5HexDigest(data);
};
// File.idFromUrl {{{2
File.idFromUrl = function(url) {
// Insanely simple conversion to keep id unique to the URL and prevent
// possible illegal file system characters and removes path separators.
// MD5 should be fast enough not that this is repeated so much.
return Ti.Utils.md5HexDigest(url);
};
// File.fromURL {{{2
File.fromURL = function(url) {
return new File(File.idFromUrl(url));
};
// FileLoader {{{1
var pending_tasks = {dispatch_queue:[]};
var FileLoader = {};
// requestDispatch (private) {{{2
function requestDispatch() {
var waitForDispatch = pinkySwear();
pending_tasks.dispatch_queue.push(waitForDispatch);
return waitForDispatch;
}
// dispatchNextTask (private) {{{2
function dispatchNextTask() {
var task;
if (pending_tasks.dispatch_queue.length < MAX_ASYNC_TASKS) {
task = pending_tasks.dispatch_queue.shift();
if (!task) { return; }
if (task.resolve) { task.resolve(); }
else { poorMansNextTick(task); }
}
}
// spawnHTTPClient (private) {{{2
function spawnHTTPClient(url, pinkyPromise) {
var http = Ti.Network.createHTTPClient({
onload: pinkyPromise.resolve,
onerror: pinkyPromise.reject,
ondatastream: pinkyPromise.notify,
timeout: HTTP_TIMEOUT
});
http.open("GET", url);
http.send();
}
// FileLoader.download - Attempt to download and cache URL {{{2
FileLoader.download = function(args) {
var waitingForPath;
var url = args.url || args;
var file = File.fromURL(url);
function attachCallbacks(promise) {
if (args.onload || args.onerror || args.ondatastream) {
return promise
.then(args.onload, args.onerror, args.ondatastream);
}
return promise;
}
if (pending_tasks[file.id]) {
// Ti.API.debug("Pending " + url + ": " + file); // DEBUG
return attachCallbacks(pending_tasks[file.id]);
}
if (file.is_cached && !file.expired()) {
file.updateLastUsedAt().save();
// Ti.API.debug("Cached " + url + ": " + file); // DEBUG
waitingForPath = pinkySwear();
waitingForPath(true, [file]);
return attachCallbacks(waitingForPath);
}
if (!Ti.Network.online) {
var offlinePromise = pinkySwear();
offlinePromise(false, ["Network offline"]);
return attachCallbacks(offlinePromise);
}
var waitingForDownload = requestDispatch()
.then(function() {
var waitForHttp = pinkySwear();
spawnHTTPClient(url, waitForHttp);
// Ti.API.debug("Downloading " + url + ": " + file); // DEBUG
return waitForHttp;
})
.get("source")
.get("responseData")
.then(function(data) {
if (!file.write(data)) {
throw new Error("Failed to save data from " + url + ": " + file);
}
file.downloaded = true;
file.updateLastUsedAt().save();
return file;
})
.fin(function() {
delete pending_tasks[file.id];
file.pending = false;
dispatchNextTask();
});
file.pending = true;
pending_tasks[file.id] = waitingForDownload;
dispatchNextTask();
return attachCallbacks(waitingForDownload);
};
// FileLoader.pruneStaleCache - (alias: gc) Remove stale cache files {{{2
FileLoader.pruneStaleCache = FileLoader.gc = function(force) {
var id, file;
for (id in metadata) {
file = new File(id);
if (force || file.expired()) {
file.expunge();
}
}
};
// Promise {{{1
// Promise is a minimalistic implementation of the Promise/A+ spec and is
// available at https://github.com/then/promise under the MIT License.
// This embeded version modified by Devin Weaver.
//
// Copyright (c) 2013 Forbes Lindesay
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
function asap(fn) { setTimeout(fn, 0); }
function Promise(fn) {
if (!(this instanceof Promise)) return new Promise(fn);
if (typeof fn !== 'function') throw new TypeError('not a function');
var state = null;
var value = null;
var progress_fns = null;
var deferreds = [];
var self = this;
this.then = function(onFulfilled, onRejected, onProgress) {
var newPromise = new Promise(function(resolve, reject) {
handle(new Handler(onFulfilled, onRejected, resolve, reject));
});
newPromise.progress = function(onProgress) {
self.progress(onProgress);
return newPromise;
};
if (typeof onProgress === 'function') self.progress(onProgress);
return newPromise;
};
function notify(v) {
function progressHandler(fn, v) {
if (typeof fn === 'function') fn.call(void 0, v);
}
if (progress_fns === null || state !== null) { return; }
for (var i = 0, len = progress_fns.length; i < len; i++)
asap(progressHandler(progress_fns[i], v));
}
function progress(onProgress) {
if (progress_fns === null) { progress_fns = []; }
progress_fns.push(onProgress);
}
this.progress = function(onProgress) {
progress(onProgress);
return this;
};
function handle(deferred) {
if (state === null) {
deferreds.push(deferred);
return;
}
asap(function() {
var cb = state ? deferred.onFulfilled : deferred.onRejected;
if (cb === null) {
(state ? deferred.resolve : deferred.reject)(value);
return;
}
var ret;
try {
ret = cb(value);
}
catch (e) {
deferred.reject(e);
return;
}
deferred.resolve(ret);
});
}
function resolve(newValue) {
try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then;
if (typeof then === 'function') {
doResolve(then.bind(newValue), resolve, reject);
return;
}
}
state = true;
value = newValue;
finale();
} catch (e) { reject(e); }
}
function reject(newValue) {
state = false;
value = newValue;
finale();
}
function finale() {
for (var i = 0, len = deferreds.length; i < len; i++)
handle(deferreds[i]);
deferreds = null;
}
doResolve(fn, resolve, reject, notify);
function Handler(onFulfilled, onRejected, resolve, reject){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.resolve = resolve;
this.reject = reject;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, onFulfilled, onRejected, onNotify) {
var done = false;
try {
fn(function (value) {
if (done) return;
done = true;
onFulfilled(value);
}, function (reason) {
if (done) return;
done = true;
onRejected(reason);
}, function (value) {
if (done) return;
onNotify(value);
});
} catch (ex) {
if (done) return;
done = true;
onRejected(ex);
}
}
}
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this;
self.then(null, function (err) {
asap(function () {
throw err;
});
});
};
Promise.prototype.get = function(prop) {
return this.then(function(obj) {
return obj[prop];
});
};
Promise.prototype.invoke = function(prop, values) {
return this.then(function(obj) {
return obj.apply(obj, values);
});
};
Promise.prototype.fin = function(onFinished) {
this.done(onFinished, onFinished);
return this;
};
Promise.defer = function() {
var resolver, rejecter, notifier;
var defer = {};
defer.promise = new Promise(function(resolve, reject, notify) {
defer.resolve = resolve;
defer.reject = reject;
defer.notify = notify;
});
return defer;
};
// }}}1
FileLoader.File = File;
FileLoader.Promise = Promise;
module.exports = FileLoader;
/* vim:set ts=2 sw=2 et fdm=marker: */
| file_loader.js | // FileLoader - A caching file downloader for Titanium
//
// Public Domain. Use, modify and distribute it any way you like. No attribution required.
//
// NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
//
// This is a reinvention of [David Geller's caching code][1]. It will download
// a file and cache it on the device allowing the cached version to be used
// instead of spawning repeated HTTP connections. It is based on the Promise/A+
// specifications and uses a modified version of [pinkySwear][2] to facilitate
// a promise based API for use in a Titanium project.
//
// ## Dependencies
// * None
//
// ## API
// Once required, the following methods are available:
//
// - `download()` - Attempt to download a file from a URL or offer a cached version.
// - `gc()` - Search the cache for any expired files and delete them (Garbage Collect).
//
// The `download()` method returns a [promise][3] object. This object can be
// used to attach callbacks to that you want to execute after the correct file
// path has been resolved (either by cache or downloaded). The callbacks are
// passed in a File object which has the following methods and properties:
//
// - `getFile()` - Returns a `Ti.FilesystemFile` object. Used to pass to a
// `ImageView.image`.
// - `getPath()` - Returns a string to the cached file. Used for properties
// that need a string not a file object (`TableViewRow.leftImage`)
// - `expired()` - Returns true/false for when the expired time has elapsed
// since this URL was last requested. By passing in true you will
// invalidate this file's cache forcing a download on next
// request.
// - `downloaded` - true if this URL was just downloaded, false if it was
// already in cached.
// - `is_cached` - true if this file has been cached or not.
//
// There are several others but these are the few you will need, if that. See more below.
//
// ## Promises
// The `download()` method returns a [pinkySwear][2] promise. You do not have
// to use promises if you do not want to. However I highly recommend their use.
// The internals are all managed via promises. If after reading this your still
// convinced to avoid them you can use callbacks like such:
//
// FileLoader.download({
// url: "http://example.com/image.png",
// onload: function(file) { imageView.image = file.getFile(); },
// onerror: function(error) { ... },
// ondatastream: function(progress) { ... }
// });
//
// That so not pretty, Let us promise to write better code:
//
// FileLoader.download("http://example.com/image.png")
// .then(function(file) { ... })
// .fail(function(error) { ... })
// .progress(function(progress) { ... });
//
// Much better. A promise is an object which will remain pending till an event
// assigns it a fulfilled value. Like an HTTP request sending it the
// responseData. When a promise is fulfilled or rejected the corresponding
// functions attached are called. The advantage with promises is that you can
// chain them:
//
// FileLoader.download("http://example.com/image.png")
// .then(function(file) { return file.getFile(); })
// .then(function(tiFile) { imageView.image = tiFile; });
//
// The modified pinkySwear in this file even offers two convenience methods for
// the above:
//
// FileLoader.download("http://example.com/image.png")
// .invoke("getFile")
// .then(function(tiFile) { imageView.image = tiFile; });
//
// With the modified pinkySwear promise you have the following methods at your
// disposal:
//
// - `then(fn)` - Attach callbacks (fulfilled, rejected, progress). Returns
// a new promise based on the return values / thrown
// exceptions of the callbacks.
// - `fail(fn)` - Same as `then(null, fn)`
// - `progress(fn)` - Same as `then(null, null, fn)`
// - `always(fn)` - Return a new promise which will resolve regardless if the
// former promise is fulfilled or rejected.
// - `fin(fn)` - Execute the function when the promise is fulfilled or
// rejected regardless. Returns the original promise to
// continue the chain.
// - `done()` - Any errors uncaught (or errors in the error function)
// will be rethrown. Ends the chain.
// - `get(prop)` - Same as `then(function(value) { return value[prop]; })`
// - `invoke(prop, args...)` -
// Same as `then(function(value) { return value[prop](args...); })`
//
// ## Configuration
//
// You can adjust the following variables either defined globals or in your
// `Alloy.CFG` namespace (Before your first `require()`):
//
// - `cache_property_key` - The `Ti.App.Property` key to use for storing the
// cache metadata.
// - `cache_expiration` - How long a cached file is considered expired since
// the last time it was requested.
// - `cache_directory` - The directory to save the cache files. On iOS the
// `applicationSupportDirectory` is prefixed. on all
// others the `applicationDataDirectory` is prefixed.
// - `cache_requests` - The number of simultaneous network requests allowed.
//
// [1]: http://developer.appcelerator.com/question/125483/how-to-create-a-generic-image-cache-sample-code#answer-218718
// [2]: https://github.com/timjansen/PinkySwear.js
// [3]: http://promises-aplus.github.io/promises-spec/
// Constants {{{1
// Load constants allowing them to be overwritten with configuration.
var HTTP_TIMEOUT = 10000;
var CACHE_METADATA_PROPERTY, EXPIRATION_TIME, CACHE_PATH_PREFIX, MAX_ASYNC_TASKS;
(function(global) {
var have_alloy = (typeof Alloy !== 'undefined' && Alloy !== null && Alloy.CFG);
function loadConfig(name) {
/* jshint eqnull:true */
if (have_alloy && Alloy.CFG[name] != null) {
return Alloy.CFG[name];
}
if (global[name] != null) {
return global[name];
}
}
CACHE_METADATA_PROPERTY = loadConfig("cache_property_key") || "file_loader_cache_metadata";
CACHE_PATH_PREFIX = loadConfig("cache_directory") || "cached_files";
EXPIRATION_TIME = loadConfig("cache_expiration") || 3600000; // 60 minutes
MAX_ASYNC_TASKS = loadConfig("cache_requests") || 10;
})(this);
// Metadata {{{1
var metadata = Ti.App.Properties.getObject(CACHE_METADATA_PROPERTY) || {};
function saveMetaData() {
Ti.App.Properties.setObject(CACHE_METADATA_PROPERTY, metadata);
}
// Cache path {{{1
// Make sure we have the directory to store files.
var cache_path = (function() {
var os = Ti.Platform.osname;
var data_dir = (os === "iphone" || os === "ipad") ?
Ti.Filesystem.applicationSupportDirectory :
Ti.Filesystem.applicationDataDirectory;
var cache_dir = Ti.Filesystem.getFile(data_dir, CACHE_PATH_PREFIX);
if (!cache_dir.exists()) {
cache_dir.createDirectory();
}
return cache_dir;
})();
// Class: File {{{1
// Constructor {{{2
function File(id) {
this.id = id;
var cache_data = metadata[this.id];
this.file_path = Ti.Filesystem.getFile(cache_path.resolve(), this.id);
if (cache_data) {
this.is_cached = this.exists();
this.last_used_at = cache_data.last_used_at;
this.md5 = cache_data.md5;
}
else {
this.is_cached = false;
this.last_used_at = 0;
this.md5 = null;
}
}
// File::updateLastUsedAt {{{2
File.prototype.updateLastUsedAt = function() {
this.last_used_at = new Date().getTime();
return this;
};
// File::save {{{2
File.prototype.save = function() {
metadata[this.id] = {
last_used_at: this.last_used_at,
md5: this.md5
};
saveMetaData();
this.is_cached = true;
return this;
};
// File::write {{{2
File.prototype.write = function(data) {
// A Titanium bug cause this to always return false. We need to manually
// check it exists. And assume it worked.
// (https://jira.appcelerator.org/browse/TIMOB-1658)
this.getFile().write(data);
this.md5 = File.getMD5(data);
// Ti.API.debug("Wrote " + this.getPath() + " (" + this.md5 + ")"); // DEBUG
return this.exists();
};
// File::exists {{{2
File.prototype.exists = function() {
return this.getFile().exists();
};
// File::expired {{{2
File.prototype.expired = function(invalidate) {
if (invalidate) {
this.last_used_at = 0;
this.save();
}
return ((new Date().getTime() - this.last_used_at) > EXPIRATION_TIME);
};
// File::expunge {{{2
File.prototype.expunge = function() {
this.getFile().deleteFile();
// Ti.API.debug("Expunged " + this.id); // DEBUG
delete metadata[this.id];
saveMetaData();
this.is_cached = false;
};
// File::getPath {{{2
File.prototype.getPath = function() {
return this.getFile().resolve();
};
// File::toString {{{2
File.prototype.toString = function() {
return "" + this.id + ": " +
(this.is_cached ? "cached" : "new") + " file" +
(this.pending ? " (pending)" : "") +
(this.downloaded ? " (downloaded)" : "") +
(this.expired() ? " (expired)" : "") +
(this.last_used_at ? ", Last used: " + this.last_used_at : "") +
(this.md5 ? ", MD5: " + this.md5 : "") +
" " + this.getPath();
};
// File.getFile {{{2
File.prototype.getFile = function() {
return this.file_path;
};
// File.getMD5 {{{2
File.getMD5 = function(data) {
return Ti.Utils.md5HexDigest(data);
};
// File.idFromUrl {{{2
File.idFromUrl = function(url) {
// Insanely simple conversion to keep id unique to the URL and prevent
// possible illegal file system characters and removes path separators.
// MD5 should be fast enough not that this is repeated so much.
return Ti.Utils.md5HexDigest(url);
};
// File.fromURL {{{2
File.fromURL = function(url) {
return new File(File.idFromUrl(url));
};
// FileLoader {{{1
var pending_tasks = {dispatch_queue:[]};
var FileLoader = {};
// requestDispatch (private) {{{2
function requestDispatch() {
var waitForDispatch = pinkySwear();
pending_tasks.dispatch_queue.push(waitForDispatch);
return waitForDispatch;
}
// dispatchNextTask (private) {{{2
function dispatchNextTask() {
var task;
if (pending_tasks.dispatch_queue.length < MAX_ASYNC_TASKS) {
task = pending_tasks.dispatch_queue.shift();
if (!task) { return; }
if (task.resolve) { task.resolve(); }
else { poorMansNextTick(task); }
}
}
// spawnHTTPClient (private) {{{2
function spawnHTTPClient(url, pinkyPromise) {
var http = Ti.Network.createHTTPClient({
onload: pinkyPromise.resolve,
onerror: pinkyPromise.reject,
ondatastream: pinkyPromise.notify,
timeout: HTTP_TIMEOUT
});
http.open("GET", url);
http.send();
}
// FileLoader.download - Attempt to download and cache URL {{{2
FileLoader.download = function(args) {
var waitingForPath;
var url = args.url || args;
var file = File.fromURL(url);
function attachCallbacks(promise) {
if (args.onload || args.onerror || args.ondatastream) {
return promise
.then(args.onload, args.onerror, args.ondatastream);
}
return promise;
}
if (pending_tasks[file.id]) {
// Ti.API.debug("Pending " + url + ": " + file); // DEBUG
return attachCallbacks(pending_tasks[file.id]);
}
if (file.is_cached && !file.expired()) {
file.updateLastUsedAt().save();
// Ti.API.debug("Cached " + url + ": " + file); // DEBUG
waitingForPath = pinkySwear();
waitingForPath(true, [file]);
return attachCallbacks(waitingForPath);
}
if (!Ti.Network.online) {
var offlinePromise = pinkySwear();
offlinePromise(false, ["Network offline"]);
return attachCallbacks(offlinePromise);
}
var waitingForDownload = requestDispatch()
.then(function() {
var waitForHttp = pinkySwear();
spawnHTTPClient(url, waitForHttp);
// Ti.API.debug("Downloading " + url + ": " + file); // DEBUG
return waitForHttp;
})
.get("source")
.get("responseData")
.then(function(data) {
if (!file.write(data)) {
throw new Error("Failed to save data from " + url + ": " + file);
}
file.downloaded = true;
file.updateLastUsedAt().save();
return file;
})
.fin(function() {
delete pending_tasks[file.id];
file.pending = false;
dispatchNextTask();
});
file.pending = true;
pending_tasks[file.id] = waitingForDownload;
dispatchNextTask();
return attachCallbacks(waitingForDownload);
};
// FileLoader.pruneStaleCache - (alias: gc) Remove stale cache files {{{2
FileLoader.pruneStaleCache = FileLoader.gc = function(force) {
var id, file;
for (id in metadata) {
file = new File(id);
if (force || file.expired()) {
file.expunge();
}
}
};
// Export File class {{{2
FileLoader.File = File;
// PinkySwear - Minimalistic implementation of the Promises/A+ spec {{{1
// Public Domain. Use, modify and distribute it any way you like. No attribution required.
// NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
// https://github.com/timjansen/PinkySwear.js
var pinkySwear = FileLoader.pinkySwear = (function() {
/* jshint eqnull:true */
function isFunction(f,o) { return typeof f == 'function'; }
function defer(callback) { setTimeout(callback, 0); }
function pinkySwear() {
var state; // undefined/null = pending, true = fulfilled, false = rejected
var values = []; // an array of values as arguments for the then() handlers
var deferred = []; // functions to call when set() is invoked
var progress_fns; // functions to call when notify() is invoked
var set = function promise(newState, newValues) {
if (state == null) {
state = newState;
values = newValues;
defer(function() {
for (var i = 0; i < deferred.length; i++)
deferred[i]();
});
}
};
set.then = function(onFulfilled, onRejected, onProgress) {
var newPromise = pinkySwear();
newPromise.progress = function(v) { set.progress(v); return newPromise; };
newPromise.notify = function(v) { set.notify(v); return newPromise; };
var callCallbacks = function() {
try {
var f = (state ? onFulfilled : onRejected);
if (isFunction(f)) {
var r = f.apply(null, values);
if (r && isFunction(r.then))
r.then(
function(value){newPromise(true, [value]);},
function(value){newPromise(false, [value]);},
function(value){newPromise.notify(value);}
);
else
newPromise(true, [r]);
}
else
newPromise(state, values);
}
catch (e) {
newPromise(false, [e]);
}
};
if (state != null)
defer(callCallbacks);
else
deferred.push(callCallbacks);
if (isFunction(onProgress))
set.progress(onProgress);
return newPromise;
};
set.notify = function(value) {
if (state == null)
defer(function() {
if (progress_fns != null)
for (var i = 0; i < progress_fns.length; i++)
progress_fns[i](value);
});
};
set.resolve = function(value) { set(true, [value]); };
set.reject = function(value) { set(false, [value]); };
set.progress = function(onProgress) {
if (progress_fns == null) { progress_fns = []; }
progress_fns.push(onProgress);
return set;
};
// always(func) is the same as then(func, func)
set.always = function(func) { return set.then(func, func); };
// fin(func) is like always() but doesn't modify the promise chain
set.fin = function(func) { set.then(func, func); return set; };
// error(func) is the same as then(0, func)
set.error = set.fail = function(func) { return set.then(0, func); };
function handleUncaughtExceptions() {
if (state === false) {
throw (values.length > 1) ? values : values[0];
}
}
set.done = function(onFulfilled, onRejected, onProgress) {
if (onFulfilled || onRejected || onProgress) {
set.then(onFulfilled, onRejected, onProgress).done();
return;
}
if (state != null)
defer(handleUncaughtExceptions);
else
deferred.push(handleUncaughtExceptions);
};
set.get = function(prop) {
return set.then(function(value) { return value[prop]; });
};
set.invoke = function(prop) {
var args = [].slice.call(arguments, 1) || [];
return set.then(function(value) { return value[prop].apply(value, args); });
};
return set;
}
return pinkySwear;
})();
// }}}1
module.exports = FileLoader;
/* vim:set ts=2 sw=2 et fdm=marker: */
| Complete replacement of pinkySwear to then/promise
| file_loader.js | Complete replacement of pinkySwear to then/promise | <ide><path>ile_loader.js
<ide> }
<ide> };
<ide>
<del>// Export File class {{{2
<del>FileLoader.File = File;
<del>
<del>// PinkySwear - Minimalistic implementation of the Promises/A+ spec {{{1
<del>// Public Domain. Use, modify and distribute it any way you like. No attribution required.
<del>// NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
<del>// https://github.com/timjansen/PinkySwear.js
<del>var pinkySwear = FileLoader.pinkySwear = (function() {
<del> /* jshint eqnull:true */
<del> function isFunction(f,o) { return typeof f == 'function'; }
<del> function defer(callback) { setTimeout(callback, 0); }
<del>
<del> function pinkySwear() {
<del> var state; // undefined/null = pending, true = fulfilled, false = rejected
<del> var values = []; // an array of values as arguments for the then() handlers
<del> var deferred = []; // functions to call when set() is invoked
<del> var progress_fns; // functions to call when notify() is invoked
<del>
<del> var set = function promise(newState, newValues) {
<del> if (state == null) {
<del> state = newState;
<del> values = newValues;
<del> defer(function() {
<del> for (var i = 0; i < deferred.length; i++)
<del> deferred[i]();
<del> });
<del> }
<del> };
<del>
<del> set.then = function(onFulfilled, onRejected, onProgress) {
<del> var newPromise = pinkySwear();
<del> newPromise.progress = function(v) { set.progress(v); return newPromise; };
<del> newPromise.notify = function(v) { set.notify(v); return newPromise; };
<del> var callCallbacks = function() {
<del> try {
<del> var f = (state ? onFulfilled : onRejected);
<del> if (isFunction(f)) {
<del> var r = f.apply(null, values);
<del> if (r && isFunction(r.then))
<del> r.then(
<del> function(value){newPromise(true, [value]);},
<del> function(value){newPromise(false, [value]);},
<del> function(value){newPromise.notify(value);}
<del> );
<del> else
<del> newPromise(true, [r]);
<del> }
<del> else
<del> newPromise(state, values);
<del> }
<del> catch (e) {
<del> newPromise(false, [e]);
<del> }
<del> };
<del> if (state != null)
<del> defer(callCallbacks);
<del> else
<del> deferred.push(callCallbacks);
<del> if (isFunction(onProgress))
<del> set.progress(onProgress);
<add>// Promise {{{1
<add>// Promise is a minimalistic implementation of the Promise/A+ spec and is
<add>// available at https://github.com/then/promise under the MIT License.
<add>// This embeded version modified by Devin Weaver.
<add>//
<add>// Copyright (c) 2013 Forbes Lindesay
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a copy
<add>// of this software and associated documentation files (the "Software"), to deal
<add>// in the Software without restriction, including without limitation the rights
<add>// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
<add>// copies of the Software, and to permit persons to whom the Software is
<add>// furnished to do so, subject to the following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included in
<add>// all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
<add>// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<add>// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
<add>// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
<add>// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
<add>// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
<add>// THE SOFTWARE.
<add>function asap(fn) { setTimeout(fn, 0); }
<add>
<add>function Promise(fn) {
<add> if (!(this instanceof Promise)) return new Promise(fn);
<add> if (typeof fn !== 'function') throw new TypeError('not a function');
<add> var state = null;
<add> var value = null;
<add> var progress_fns = null;
<add> var deferreds = [];
<add> var self = this;
<add>
<add> this.then = function(onFulfilled, onRejected, onProgress) {
<add> var newPromise = new Promise(function(resolve, reject) {
<add> handle(new Handler(onFulfilled, onRejected, resolve, reject));
<add> });
<add> newPromise.progress = function(onProgress) {
<add> self.progress(onProgress);
<ide> return newPromise;
<ide> };
<del>
<del> set.notify = function(value) {
<del> if (state == null)
<del> defer(function() {
<del> if (progress_fns != null)
<del> for (var i = 0; i < progress_fns.length; i++)
<del> progress_fns[i](value);
<del> });
<del> };
<del>
<del> set.resolve = function(value) { set(true, [value]); };
<del> set.reject = function(value) { set(false, [value]); };
<del>
<del> set.progress = function(onProgress) {
<del> if (progress_fns == null) { progress_fns = []; }
<del> progress_fns.push(onProgress);
<del> return set;
<del> };
<del>
<del> // always(func) is the same as then(func, func)
<del> set.always = function(func) { return set.then(func, func); };
<del>
<del> // fin(func) is like always() but doesn't modify the promise chain
<del> set.fin = function(func) { set.then(func, func); return set; };
<del>
<del> // error(func) is the same as then(0, func)
<del> set.error = set.fail = function(func) { return set.then(0, func); };
<del>
<del> function handleUncaughtExceptions() {
<del> if (state === false) {
<del> throw (values.length > 1) ? values : values[0];
<del> }
<del> }
<del>
<del> set.done = function(onFulfilled, onRejected, onProgress) {
<del> if (onFulfilled || onRejected || onProgress) {
<del> set.then(onFulfilled, onRejected, onProgress).done();
<add> if (typeof onProgress === 'function') self.progress(onProgress);
<add> return newPromise;
<add> };
<add>
<add> function notify(v) {
<add> function progressHandler(fn, v) {
<add> if (typeof fn === 'function') fn.call(void 0, v);
<add> }
<add> if (progress_fns === null || state !== null) { return; }
<add> for (var i = 0, len = progress_fns.length; i < len; i++)
<add> asap(progressHandler(progress_fns[i], v));
<add> }
<add>
<add> function progress(onProgress) {
<add> if (progress_fns === null) { progress_fns = []; }
<add> progress_fns.push(onProgress);
<add> }
<add>
<add> this.progress = function(onProgress) {
<add> progress(onProgress);
<add> return this;
<add> };
<add>
<add> function handle(deferred) {
<add> if (state === null) {
<add> deferreds.push(deferred);
<add> return;
<add> }
<add> asap(function() {
<add> var cb = state ? deferred.onFulfilled : deferred.onRejected;
<add> if (cb === null) {
<add> (state ? deferred.resolve : deferred.reject)(value);
<ide> return;
<ide> }
<del> if (state != null)
<del> defer(handleUncaughtExceptions);
<del> else
<del> deferred.push(handleUncaughtExceptions);
<del> };
<del>
<del> set.get = function(prop) {
<del> return set.then(function(value) { return value[prop]; });
<del> };
<del>
<del> set.invoke = function(prop) {
<del> var args = [].slice.call(arguments, 1) || [];
<del> return set.then(function(value) { return value[prop].apply(value, args); });
<del> };
<del>
<del> return set;
<del> }
<del>
<del> return pinkySwear;
<del>})();
<add> var ret;
<add> try {
<add> ret = cb(value);
<add> }
<add> catch (e) {
<add> deferred.reject(e);
<add> return;
<add> }
<add> deferred.resolve(ret);
<add> });
<add> }
<add>
<add> function resolve(newValue) {
<add> try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
<add> if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
<add> if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
<add> var then = newValue.then;
<add> if (typeof then === 'function') {
<add> doResolve(then.bind(newValue), resolve, reject);
<add> return;
<add> }
<add> }
<add> state = true;
<add> value = newValue;
<add> finale();
<add> } catch (e) { reject(e); }
<add> }
<add>
<add> function reject(newValue) {
<add> state = false;
<add> value = newValue;
<add> finale();
<add> }
<add>
<add> function finale() {
<add> for (var i = 0, len = deferreds.length; i < len; i++)
<add> handle(deferreds[i]);
<add> deferreds = null;
<add> }
<add>
<add> doResolve(fn, resolve, reject, notify);
<add>
<add> function Handler(onFulfilled, onRejected, resolve, reject){
<add> this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
<add> this.onRejected = typeof onRejected === 'function' ? onRejected : null;
<add> this.resolve = resolve;
<add> this.reject = reject;
<add> }
<add>
<add> /**
<add> * Take a potentially misbehaving resolver function and make sure
<add> * onFulfilled and onRejected are only called once.
<add> *
<add> * Makes no guarantees about asynchrony.
<add> */
<add> function doResolve(fn, onFulfilled, onRejected, onNotify) {
<add> var done = false;
<add> try {
<add> fn(function (value) {
<add> if (done) return;
<add> done = true;
<add> onFulfilled(value);
<add> }, function (reason) {
<add> if (done) return;
<add> done = true;
<add> onRejected(reason);
<add> }, function (value) {
<add> if (done) return;
<add> onNotify(value);
<add> });
<add> } catch (ex) {
<add> if (done) return;
<add> done = true;
<add> onRejected(ex);
<add> }
<add> }
<add>}
<add>
<add>Promise.prototype.done = function (onFulfilled, onRejected) {
<add> var self = arguments.length ? this.then.apply(this, arguments) : this;
<add> self.then(null, function (err) {
<add> asap(function () {
<add> throw err;
<add> });
<add> });
<add>};
<add>
<add>Promise.prototype.get = function(prop) {
<add> return this.then(function(obj) {
<add> return obj[prop];
<add> });
<add>};
<add>
<add>Promise.prototype.invoke = function(prop, values) {
<add> return this.then(function(obj) {
<add> return obj.apply(obj, values);
<add> });
<add>};
<add>
<add>Promise.prototype.fin = function(onFinished) {
<add> this.done(onFinished, onFinished);
<add> return this;
<add>};
<add>
<add>Promise.defer = function() {
<add> var resolver, rejecter, notifier;
<add> var defer = {};
<add>
<add> defer.promise = new Promise(function(resolve, reject, notify) {
<add> defer.resolve = resolve;
<add> defer.reject = reject;
<add> defer.notify = notify;
<add> });
<add>
<add> return defer;
<add>};
<ide> // }}}1
<ide>
<del>module.exports = FileLoader;
<add>FileLoader.File = File;
<add>FileLoader.Promise = Promise;
<add>module.exports = FileLoader;
<ide> /* vim:set ts=2 sw=2 et fdm=marker: */ |
|
JavaScript | mit | 45e167d6a9d36470a2c087487a6cd008ae8359c2 | 0 | atom-minimap/minimap | 'use strict'
import { Emitter, CompositeDisposable } from 'atom'
import MinimapElement from './minimap-element'
import Minimap from './minimap'
import config from './config.json'
import * as PluginManagement from './plugin-management'
import { treeSitterWarning } from './performance-monitor'
import DOMStylesReader from './dom-styles-reader'
export { default as config } from './config.json'
export * from './plugin-management'
export { default as Minimap } from './minimap'
/**
* The `Minimap` package provides an eagle-eye view of text buffers.
*
* It also provides API for plugin packages that want to interact with the
* minimap and be available to the user through the minimap settings.
*/
/**
* The activation state of the package.
*
* @type {boolean}
* @access private
*/
let active = false
/**
* The toggle state of the package.
*
* @type {boolean}
* @access private
*/
let toggled = false
/**
* The `Map` where Minimap instances are stored with the text editor they
* target as key.
*
* @type {Map}
* @access private
*/
let editorsMinimaps = null
/**
* The composite disposable that stores the package's subscriptions.
*
* @type {CompositeDisposable}
* @access private
*/
let subscriptions = null
/**
* The disposable that stores the package's commands subscription.
*
* @type {Disposable}
* @access private
*/
let subscriptionsOfCommands = null
/**
* The package's events emitter.
*
* @type {Emitter}
* @access private
*/
export const emitter = new Emitter()
/**
DOMStylesReader cache used for storing token colors
*/
export let domStylesReader = null
/**
* Activates the minimap package.
*/
export function activate () {
if (active) { return }
subscriptionsOfCommands = atom.commands.add('atom-workspace', {
'minimap:toggle': () => {
toggle()
},
'minimap:generate-coffee-plugin': async () => {
await generatePlugin('coffee')
},
'minimap:generate-javascript-plugin': async () => {
await generatePlugin('javascript')
},
'minimap:generate-babel-plugin': async () => {
await generatePlugin('babel')
}
})
editorsMinimaps = new Map()
domStylesReader = new DOMStylesReader()
subscriptions = new CompositeDisposable()
active = true
if (atom.config.get('minimap.autoToggle')) { toggle() }
}
/**
* Returns a {MinimapElement} for the passed-in model if it's a {Minimap}.
*
* @param {Minimap} model the model for which returning a view
* @return {MinimapElement}
*/
export function minimapViewProvider (model) {
if (model instanceof Minimap) {
const element = new MinimapElement()
element.setModel(model)
return element
}
}
/**
* Deactivates the minimap package.
*/
export function deactivate () {
if (!active) { return }
PluginManagement.deactivateAllPlugins()
if (editorsMinimaps) {
editorsMinimaps.forEach((value, key) => {
value.destroy()
editorsMinimaps.delete(key)
})
}
subscriptions.dispose()
subscriptions = null
subscriptionsOfCommands.dispose()
subscriptionsOfCommands = null
editorsMinimaps = undefined
domStylesReader.invalidateDOMStylesCache()
toggled = false
active = false
}
export function getConfigSchema () {
return config || atom.packages.getLoadedPackage('minimap').metadata.configSchema
}
/**
* Toggles the minimap display.
*/
export function toggle () {
if (!active) { return }
if (toggled) {
toggled = false
if (editorsMinimaps) {
editorsMinimaps.forEach((minimap, key) => {
minimap.destroy()
editorsMinimaps.delete(key)
})
}
subscriptions.dispose()
} else {
toggled = true
initSubscriptions()
}
domStylesReader.invalidateDOMStylesCache()
}
/**
* Opens the plugin generation view.
*
* @param {string} template the name of the template to use
*/
async function generatePlugin (template) {
const { default: MinimapPluginGeneratorElement } = await import('./minimap-plugin-generator-element')
const view = new MinimapPluginGeneratorElement()
view.template = template
view.attach()
}
/**
* Registers a callback to listen to the `did-activate` event of the package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidActivate (callback) {
return emitter.on('did-activate', callback)
}
/**
* Registers a callback to listen to the `did-deactivate` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidDeactivate (callback) {
return emitter.on('did-deactivate', callback)
}
/**
* Registers a callback to listen to the `did-create-minimap` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidCreateMinimap (callback) {
return emitter.on('did-create-minimap', callback)
}
/**
* Registers a callback to listen to the `did-add-plugin` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidAddPlugin (callback) {
return emitter.on('did-add-plugin', callback)
}
/**
* Registers a callback to listen to the `did-remove-plugin` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidRemovePlugin (callback) {
return emitter.on('did-remove-plugin', callback)
}
/**
* Registers a callback to listen to the `did-activate-plugin` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidActivatePlugin (callback) {
return emitter.on('did-activate-plugin', callback)
}
/**
* Registers a callback to listen to the `did-deactivate-plugin` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidDeactivatePlugin (callback) {
return emitter.on('did-deactivate-plugin', callback)
}
/**
* Registers a callback to listen to the `did-change-plugin-order` event of
* the package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidChangePluginOrder (callback) {
return emitter.on('did-change-plugin-order', callback)
}
/**
* Returns the `Minimap` class
*
* @return {Function} the `Minimap` class constructor
*/
export function minimapClass () {
return Minimap
}
/**
* Returns the `Minimap` object associated to the passed-in
* `TextEditorElement`.
*
* @param {TextEditorElement} editorElement a text editor element
* @return {Minimap} the associated minimap
*/
export function minimapForEditorElement (editorElement) {
if (!editorElement) { return }
return minimapForEditor(editorElement.getModel())
}
/**
* Returns the `Minimap` object associated to the passed-in
* `TextEditor`.
*
* @param {TextEditor} textEditor a text editor
* @return {Minimap} the associated minimap
*/
export function minimapForEditor (textEditor) {
if (!textEditor) { return }
if (!editorsMinimaps) { return }
let minimap = editorsMinimaps.get(textEditor)
if (!minimap) {
minimap = new Minimap({ textEditor })
editorsMinimaps.set(textEditor, minimap)
const editorSubscription = textEditor.onDidDestroy(() => {
const minimaps = editorsMinimaps
if (minimaps) { minimaps.delete(textEditor) }
editorSubscription.dispose()
})
}
return minimap
}
/**
* Returns a new stand-alone {Minimap} for the passed-in `TextEditor`.
*
* @param {TextEditor} textEditor a text editor instance to create
* a minimap for
* @return {Minimap} a new stand-alone Minimap for the passed-in editor
*/
export function standAloneMinimapForEditor (textEditor) {
if (!textEditor) { return }
return new Minimap({
textEditor,
standAlone: true
})
}
/**
* Returns the `Minimap` associated to the active `TextEditor`.
*
* @return {Minimap} the active Minimap
*/
export function getActiveMinimap () {
return minimapForEditor(atom.workspace.getActiveTextEditor())
}
/**
* Calls a function for each present and future minimaps.
*
* @param {function(minimap:Minimap):void} iterator a function to call with
* the existing and future
* minimaps
* @return {Disposable} a disposable to unregister the observer
*/
export function observeMinimaps (iterator) {
if (!iterator) { return }
if (editorsMinimaps) {
editorsMinimaps.forEach((minimap) => { iterator(minimap) })
}
return onDidCreateMinimap((minimap) => { iterator(minimap) })
}
/**
* Registers to the `observeTextEditors` method.
*
* @access private
*/
function initSubscriptions () {
subscriptions.add(
atom.workspace.observeTextEditors((textEditor) => {
const minimap = minimapForEditor(textEditor)
const minimapElement = atom.views.getView(minimap)
emitter.emit('did-create-minimap', minimap)
minimapElement.attach()
}),
// empty color cache if the theme changes
atom.themes.onDidChangeActiveThemes(() => {
domStylesReader.invalidateDOMStylesCache()
editorsMinimaps.forEach((minimap) => { atom.views.getView(minimap).requestForcedUpdate() })
}),
treeSitterWarning()
)
}
// The public exports included in the service:
const MinimapServiceV1 = {
minimapViewProvider,
getConfigSchema,
onDidActivate,
onDidDeactivate,
onDidCreateMinimap,
onDidAddPlugin,
onDidRemovePlugin,
onDidActivatePlugin,
onDidDeactivatePlugin,
onDidChangePluginOrder,
minimapClass,
minimapForEditorElement,
minimapForEditor,
standAloneMinimapForEditor,
getActiveMinimap,
observeMinimaps,
registerPlugin: PluginManagement.registerPlugin,
unregisterPlugin: PluginManagement.unregisterPlugin,
togglePluginActivation: PluginManagement.togglePluginActivation,
deactivateAllPlugins: PluginManagement.deactivateAllPlugins,
activatePlugin: PluginManagement.activatePlugin,
deactivatePlugin: PluginManagement.deactivatePlugin,
getPluginsOrder: PluginManagement.getPluginsOrder
}
/**
* Returns the Minimap main module instance.
*
* @return {Main} The Minimap main module instance.
*/
export function provideMinimapServiceV1 () { return MinimapServiceV1 }
| lib/main.js | 'use strict'
import { Emitter, CompositeDisposable } from 'atom'
import MinimapElement from './minimap-element'
import Minimap from './minimap'
import config from './config.json'
import * as PluginManagement from './plugin-management'
import { treeSitterWarning } from './performance-monitor'
import DOMStylesReader from './dom-styles-reader'
export { default as config } from './config.json'
export * from './plugin-management'
export { default as Minimap } from './minimap'
/**
* The `Minimap` package provides an eagle-eye view of text buffers.
*
* It also provides API for plugin packages that want to interact with the
* minimap and be available to the user through the minimap settings.
*/
/**
* The activation state of the package.
*
* @type {boolean}
* @access private
*/
let active = false
/**
* The toggle state of the package.
*
* @type {boolean}
* @access private
*/
let toggled = false
/**
* The `Map` where Minimap instances are stored with the text editor they
* target as key.
*
* @type {Map}
* @access private
*/
let editorsMinimaps = null
/**
* The composite disposable that stores the package's subscriptions.
*
* @type {CompositeDisposable}
* @access private
*/
let subscriptions = null
/**
* The disposable that stores the package's commands subscription.
*
* @type {Disposable}
* @access private
*/
let subscriptionsOfCommands = null
/**
* The package's events emitter.
*
* @type {Emitter}
* @access private
*/
export const emitter = new Emitter()
/**
DOMStylesReader cache used for storing token colors
*/
export let domStylesReader = null
/**
* Activates the minimap package.
*/
export function activate () {
if (active) { return }
subscriptionsOfCommands = atom.commands.add('atom-workspace', {
'minimap:toggle': () => {
toggle()
},
'minimap:generate-coffee-plugin': async () => {
await generatePlugin('coffee')
},
'minimap:generate-javascript-plugin': async () => {
await generatePlugin('javascript')
},
'minimap:generate-babel-plugin': async () => {
await generatePlugin('babel')
}
})
editorsMinimaps = new Map()
domStylesReader = new DOMStylesReader()
subscriptions = new CompositeDisposable()
active = true
if (atom.config.get('minimap.autoToggle')) { toggle() }
}
/**
* Returns a {MinimapElement} for the passed-in model if it's a {Minimap}.
*
* @param {Minimap} model the model for which returning a view
* @return {MinimapElement}
*/
export function minimapViewProvider (model) {
if (model instanceof Minimap) {
const element = new MinimapElement()
element.setModel(model)
return element
}
}
/**
* Deactivates the minimap package.
*/
export function deactivate () {
if (!active) { return }
PluginManagement.deactivateAllPlugins()
if (editorsMinimaps) {
editorsMinimaps.forEach((value, key) => {
value.destroy()
editorsMinimaps.delete(key)
})
}
subscriptions.dispose()
subscriptions = null
subscriptionsOfCommands.dispose()
subscriptionsOfCommands = null
editorsMinimaps = undefined
domStylesReader.invalidateDOMStylesCache()
toggled = false
active = false
}
export function getConfigSchema () {
return config || atom.packages.getLoadedPackage('minimap').metadata.configSchema
}
/**
* Toggles the minimap display.
*/
export function toggle () {
if (!active) { return }
if (toggled) {
toggled = false
if (editorsMinimaps) {
editorsMinimaps.forEach((value, key) => {
value.destroy()
editorsMinimaps.delete(key)
})
}
subscriptions.dispose()
} else {
toggled = true
initSubscriptions()
}
domStylesReader.invalidateDOMStylesCache()
}
/**
* Opens the plugin generation view.
*
* @param {string} template the name of the template to use
*/
async function generatePlugin (template) {
const { default: MinimapPluginGeneratorElement } = await import('./minimap-plugin-generator-element')
const view = new MinimapPluginGeneratorElement()
view.template = template
view.attach()
}
/**
* Registers a callback to listen to the `did-activate` event of the package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidActivate (callback) {
return emitter.on('did-activate', callback)
}
/**
* Registers a callback to listen to the `did-deactivate` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidDeactivate (callback) {
return emitter.on('did-deactivate', callback)
}
/**
* Registers a callback to listen to the `did-create-minimap` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidCreateMinimap (callback) {
return emitter.on('did-create-minimap', callback)
}
/**
* Registers a callback to listen to the `did-add-plugin` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidAddPlugin (callback) {
return emitter.on('did-add-plugin', callback)
}
/**
* Registers a callback to listen to the `did-remove-plugin` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidRemovePlugin (callback) {
return emitter.on('did-remove-plugin', callback)
}
/**
* Registers a callback to listen to the `did-activate-plugin` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidActivatePlugin (callback) {
return emitter.on('did-activate-plugin', callback)
}
/**
* Registers a callback to listen to the `did-deactivate-plugin` event of the
* package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidDeactivatePlugin (callback) {
return emitter.on('did-deactivate-plugin', callback)
}
/**
* Registers a callback to listen to the `did-change-plugin-order` event of
* the package.
*
* @param {function(event:Object):void} callback the callback function
* @return {Disposable} a disposable to stop listening to the event
*/
export function onDidChangePluginOrder (callback) {
return emitter.on('did-change-plugin-order', callback)
}
/**
* Returns the `Minimap` class
*
* @return {Function} the `Minimap` class constructor
*/
export function minimapClass () {
return Minimap
}
/**
* Returns the `Minimap` object associated to the passed-in
* `TextEditorElement`.
*
* @param {TextEditorElement} editorElement a text editor element
* @return {Minimap} the associated minimap
*/
export function minimapForEditorElement (editorElement) {
if (!editorElement) { return }
return minimapForEditor(editorElement.getModel())
}
/**
* Returns the `Minimap` object associated to the passed-in
* `TextEditor`.
*
* @param {TextEditor} textEditor a text editor
* @return {Minimap} the associated minimap
*/
export function minimapForEditor (textEditor) {
if (!textEditor) { return }
if (!editorsMinimaps) { return }
let minimap = editorsMinimaps.get(textEditor)
if (!minimap) {
minimap = new Minimap({ textEditor })
editorsMinimaps.set(textEditor, minimap)
const editorSubscription = textEditor.onDidDestroy(() => {
const minimaps = editorsMinimaps
if (minimaps) { minimaps.delete(textEditor) }
editorSubscription.dispose()
})
}
return minimap
}
/**
* Returns a new stand-alone {Minimap} for the passed-in `TextEditor`.
*
* @param {TextEditor} textEditor a text editor instance to create
* a minimap for
* @return {Minimap} a new stand-alone Minimap for the passed-in editor
*/
export function standAloneMinimapForEditor (textEditor) {
if (!textEditor) { return }
return new Minimap({
textEditor,
standAlone: true
})
}
/**
* Returns the `Minimap` associated to the active `TextEditor`.
*
* @return {Minimap} the active Minimap
*/
export function getActiveMinimap () {
return minimapForEditor(atom.workspace.getActiveTextEditor())
}
/**
* Calls a function for each present and future minimaps.
*
* @param {function(minimap:Minimap):void} iterator a function to call with
* the existing and future
* minimaps
* @return {Disposable} a disposable to unregister the observer
*/
export function observeMinimaps (iterator) {
if (!iterator) { return }
if (editorsMinimaps) {
editorsMinimaps.forEach((minimap) => { iterator(minimap) })
}
return onDidCreateMinimap((minimap) => { iterator(minimap) })
}
/**
* Registers to the `observeTextEditors` method.
*
* @access private
*/
function initSubscriptions () {
subscriptions.add(
atom.workspace.observeTextEditors((textEditor) => {
const minimap = minimapForEditor(textEditor)
const minimapElement = atom.views.getView(minimap)
emitter.emit('did-create-minimap', minimap)
minimapElement.attach()
}),
// empty color cache if the theme changes
atom.themes.onDidChangeActiveThemes(() => {
domStylesReader.invalidateDOMStylesCache()
editorsMinimaps.forEach((minimap) => { atom.views.getView(minimap).requestForcedUpdate() })
}),
treeSitterWarning()
)
}
// The public exports included in the service:
const MinimapServiceV1 = {
minimapViewProvider,
getConfigSchema,
onDidActivate,
onDidDeactivate,
onDidCreateMinimap,
onDidAddPlugin,
onDidRemovePlugin,
onDidActivatePlugin,
onDidDeactivatePlugin,
onDidChangePluginOrder,
minimapClass,
minimapForEditorElement,
minimapForEditor,
standAloneMinimapForEditor,
getActiveMinimap,
observeMinimaps,
registerPlugin: PluginManagement.registerPlugin,
unregisterPlugin: PluginManagement.unregisterPlugin,
togglePluginActivation: PluginManagement.togglePluginActivation,
deactivateAllPlugins: PluginManagement.deactivateAllPlugins,
activatePlugin: PluginManagement.activatePlugin,
deactivatePlugin: PluginManagement.deactivatePlugin,
getPluginsOrder: PluginManagement.getPluginsOrder
}
/**
* Returns the Minimap main module instance.
*
* @return {Main} The Minimap main module instance.
*/
export function provideMinimapServiceV1 () { return MinimapServiceV1 }
| chore: rename value to minimap [skip ci]
| lib/main.js | chore: rename value to minimap [skip ci] | <ide><path>ib/main.js
<ide> toggled = false
<ide>
<ide> if (editorsMinimaps) {
<del> editorsMinimaps.forEach((value, key) => {
<del> value.destroy()
<add> editorsMinimaps.forEach((minimap, key) => {
<add> minimap.destroy()
<ide> editorsMinimaps.delete(key)
<ide> })
<ide> } |
|
Java | bsd-3-clause | abd61cdad55f92ac5ab07ab6c97aafe3adef0e1f | 0 | cerebro/ggp-base,cerebro/ggp-base | package util.match;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import external.JSON.JSONArray;
import external.JSON.JSONException;
import external.JSON.JSONObject;
import util.crypto.SignableJSON;
import util.crypto.BaseCryptography.EncodedKeyPair;
import util.game.Game;
import util.game.RemoteGameRepository;
import util.gdl.factory.GdlFactory;
import util.gdl.factory.exceptions.GdlFormatException;
import util.gdl.grammar.GdlSentence;
import util.statemachine.Move;
import util.statemachine.Role;
import util.symbol.factory.SymbolFactory;
import util.symbol.factory.exceptions.SymbolFormatException;
import util.symbol.grammar.SymbolList;
/**
* Match encapsulates all of the information relating to a single match.
* A match is a single play through a game, with a complete history that
* lists what move each player made at each step through the match. This
* also includes other relevant metadata about the match, including some
* unique identifiers, configuration information, and so on.
*
* NOTE: Match objects created by a player, representing state read from
* a server, are not completely filled out. For example, they only get an
* ephemeral Game object, which has a rulesheet but no key or metadata.
* Gamers which do not derive from StateMachineGamer also do not keep any
* information on what states have been observed, because (somehow) they
* are representing games without using state machines. In general, these
* player-created Match objects shouldn't be sent out into the ecosystem.
*
* @author Sam
*/
public final class Match
{
private final String matchId;
private final String randomToken;
private final String spectatorAuthToken;
private final int playClock;
private final int startClock;
private final Date startTime;
private final Game theGame;
private final List<String> theRoleNames; // TODO: remove this
private final List<List<GdlSentence>> moveHistory;
private final List<Set<GdlSentence>> stateHistory;
private final List<List<String>> errorHistory;
private final List<Date> stateTimeHistory;
private boolean isCompleted;
private final List<Integer> goalValues;
private EncodedKeyPair theCryptographicKeys;
private List<String> thePlayerNamesFromHost;
public Match(String matchId, int startClock, int playClock, Game theGame)
{
this.matchId = matchId;
this.startClock = startClock;
this.playClock = playClock;
this.theGame = theGame;
this.startTime = new Date();
this.randomToken = getRandomString(32);
this.spectatorAuthToken = getRandomString(12);
this.isCompleted = false;
this.theRoleNames = new ArrayList<String>();
for(Role r : Role.computeRoles(theGame.getRules())) {
this.theRoleNames.add(r.getName().getName().toString());
}
this.moveHistory = new ArrayList<List<GdlSentence>>();
this.stateHistory = new ArrayList<Set<GdlSentence>>();
this.stateTimeHistory = new ArrayList<Date>();
this.errorHistory = new ArrayList<List<String>>();
this.goalValues = new ArrayList<Integer>();
}
public Match(String theJSON, Game theGame) throws JSONException, SymbolFormatException, GdlFormatException {
JSONObject theMatchObject = new JSONObject(theJSON);
this.matchId = theMatchObject.getString("matchId");
this.startClock = theMatchObject.getInt("startClock");
this.playClock = theMatchObject.getInt("playClock");
if (theGame == null) {
this.theGame = RemoteGameRepository.loadSingleGame(theMatchObject.getString("gameMetaURL"));
if (this.theGame == null) {
throw new RuntimeException("Could not find metadata for game referenced in Match object: " + theMatchObject.getString("gameMetaURL"));
}
} else {
this.theGame = theGame;
}
this.startTime = new Date(theMatchObject.getLong("startTime"));
this.randomToken = theMatchObject.getString("randomToken");
this.spectatorAuthToken = null;
this.isCompleted = theMatchObject.getBoolean("isCompleted");
this.theRoleNames = new ArrayList<String>();
if (theMatchObject.has("gameRoleNames")) {
JSONArray theNames = theMatchObject.getJSONArray("gameRoleNames");
for (int i = 0; i < theNames.length(); i++) {
this.theRoleNames.add(theNames.getString(i));
}
} else {
for(Role r : Role.computeRoles(this.theGame.getRules())) {
this.theRoleNames.add(r.getName().getName().toString());
}
}
this.moveHistory = new ArrayList<List<GdlSentence>>();
this.stateHistory = new ArrayList<Set<GdlSentence>>();
this.stateTimeHistory = new ArrayList<Date>();
this.errorHistory = new ArrayList<List<String>>();
JSONArray theMoves = theMatchObject.getJSONArray("moves");
for (int i = 0; i < theMoves.length(); i++) {
List<GdlSentence> theMove = new ArrayList<GdlSentence>();
JSONArray moveElements = theMoves.getJSONArray(i);
for (int j = 0; j < moveElements.length(); j++) {
theMove.add((GdlSentence)GdlFactory.create(moveElements.getString(j)));
}
moveHistory.add(theMove);
}
JSONArray theStates = theMatchObject.getJSONArray("states");
for (int i = 0; i < theStates.length(); i++) {
Set<GdlSentence> theState = new HashSet<GdlSentence>();
SymbolList stateElements = (SymbolList) SymbolFactory.create(theStates.getString(i));
for (int j = 0; j < stateElements.size(); j++)
{
theState.add((GdlSentence)GdlFactory.create("( true " + stateElements.get(j).toString() + " )"));
}
stateHistory.add(theState);
}
JSONArray theStateTimes = theMatchObject.getJSONArray("stateTimes");
for (int i = 0; i < theStateTimes.length(); i++) {
this.stateTimeHistory.add(new Date(theStateTimes.getLong(i)));
}
if (theMatchObject.has("errors")) {
JSONArray theErrors = theMatchObject.getJSONArray("errors");
for (int i = 0; i < theErrors.length(); i++) {
List<String> theMoveErrors = new ArrayList<String>();
JSONArray errorElements = theErrors.getJSONArray(i);
for (int j = 0; j < errorElements.length(); j++)
{
theMoveErrors.add(errorElements.getString(j));
}
errorHistory.add(theMoveErrors);
}
}
this.goalValues = new ArrayList<Integer>();
try {
JSONArray theGoalValues = theMatchObject.getJSONArray("goalValues");
for (int i = 0; i < theGoalValues.length(); i++) {
this.goalValues.add(theGoalValues.getInt(i));
}
} catch (JSONException e) {}
// TODO: Add a way to recover cryptographic public keys and signatures.
// Or, perhaps loading a match into memory for editing should strip those?
if (theMatchObject.has("playerNamesFromHost")) {
thePlayerNamesFromHost = new ArrayList<String>();
JSONArray thePlayerNames = theMatchObject.getJSONArray("playerNamesFromHost");
for (int i = 0; i < thePlayerNames.length(); i++) {
thePlayerNamesFromHost.add(thePlayerNames.getString(i));
}
}
}
/* Mutators */
public void setCryptographicKeys(EncodedKeyPair k) {
this.theCryptographicKeys = k;
}
public void setPlayerNamesFromHost(List<String> thePlayerNames) {
this.thePlayerNamesFromHost = thePlayerNames;
}
public void appendMoves(List<GdlSentence> moves) {
moveHistory.add(moves);
}
public void appendMoves2(List<Move> moves) {
// NOTE: This is appendMoves2 because it Java can't handle two
// appendMove methods that both take List objects with different
// templatized parameters.
if (moves.get(0) instanceof Move) {
List<GdlSentence> theMoves = new ArrayList<GdlSentence>();
for(Move m : moves) {
theMoves.add(m.getContents());
}
appendMoves(theMoves);
}
}
public void appendState(Set<GdlSentence> state) {
stateHistory.add(state);
stateTimeHistory.add(new Date());
}
public void appendErrors(List<String> errors) {
errorHistory.add(errors);
}
public void appendNoErrors() {
List<String> theNoErrors = new ArrayList<String>();
for (int i = 0; i < this.theRoleNames.size(); i++) {
theNoErrors.add("");
}
errorHistory.add(theNoErrors);
}
public void markCompleted(List<Integer> theGoalValues) {
this.isCompleted = true;
if (theGoalValues != null) {
this.goalValues.addAll(theGoalValues);
}
}
/* Complex accessors */
public String toJSON() {
JSONObject theJSON = new JSONObject();
try {
theJSON.put("matchId", matchId);
theJSON.put("randomToken", randomToken);
theJSON.put("startTime", startTime.getTime());
theJSON.put("gameMetaURL", getGameRepositoryURL());
theJSON.put("isCompleted", isCompleted);
theJSON.put("states", new JSONArray(renderArrayAsJSON(renderStateHistory(stateHistory), true)));
theJSON.put("moves", new JSONArray(renderArrayAsJSON(renderMoveHistory(moveHistory), false)));
theJSON.put("stateTimes", new JSONArray(renderArrayAsJSON(stateTimeHistory, false)));
if (errorHistory.size() > 0) {
theJSON.put("errors", new JSONArray(renderArrayAsJSON(renderErrorHistory(errorHistory), false)));
}
if (goalValues.size() > 0) {
theJSON.put("goalValues", goalValues);
}
theJSON.put("startClock", startClock);
theJSON.put("playClock", playClock);
if (thePlayerNamesFromHost != null) {
theJSON.put("playerNamesFromHost", thePlayerNamesFromHost);
}
} catch (JSONException e) {
return null;
}
if (theCryptographicKeys != null) {
try {
SignableJSON.signJSON(theJSON, theCryptographicKeys.thePublicKey, theCryptographicKeys.thePrivateKey);
if (!SignableJSON.isSignedJSON(theJSON)) {
throw new Exception("Could not recognize signed match: " + theJSON);
}
if (!SignableJSON.verifySignedJSON(theJSON)) {
throw new Exception("Could not verify signed match: " + theJSON);
}
} catch (Exception e) {
System.err.println(e);
theJSON.remove("matchHostPK");
theJSON.remove("matchHostSignature");
}
}
return theJSON.toString();
}
public List<GdlSentence> getMostRecentMoves() {
if (moveHistory.size() == 0)
return null;
return moveHistory.get(moveHistory.size()-1);
}
public Set<GdlSentence> getMostRecentState() {
if (stateHistory.size() == 0)
return null;
return stateHistory.get(stateHistory.size()-1);
}
public String getGameRepositoryURL() {
return getGame().getRepositoryURL();
}
public String toString() {
return toJSON();
}
/* Simple accessors */
public String getMatchId() {
return matchId;
}
public String getRandomToken() {
return randomToken;
}
public String getSpectatorAuthToken() {
return spectatorAuthToken;
}
public Game getGame() {
return theGame;
}
public List<List<GdlSentence>> getMoveHistory() {
return moveHistory;
}
public List<Set<GdlSentence>> getStateHistory() {
return stateHistory;
}
public List<Date> getStateTimeHistory() {
return stateTimeHistory;
}
public List<List<String>> getErrorHistory() {
return errorHistory;
}
public int getPlayClock() {
return playClock;
}
public int getStartClock() {
return startClock;
}
public Date getStartTime() {
return startTime;
}
public boolean isCompleted() {
return isCompleted;
}
public List<Integer> getGoalValues() {
return goalValues;
}
/* Static methods */
public static String getRandomString(int nLength) {
Random theGenerator = new Random();
String theString = "";
for (int i = 0; i < nLength; i++) {
int nVal = theGenerator.nextInt(62);
if (nVal < 26) theString += (char)('a' + nVal);
else if (nVal < 52) theString += (char)('A' + (nVal-26));
else if (nVal < 62) theString += (char)('0' + (nVal-52));
}
return theString;
}
private static String renderArrayAsJSON(List<?> theList, boolean useQuotes) {
String s = "[";
for (int i = 0; i < theList.size(); i++) {
Object o = theList.get(i);
// AppEngine-specific, not needed yet: if (o instanceof Text) o = ((Text)o).getValue();
if (o instanceof Date) o = ((Date)o).getTime();
if (useQuotes) s += "\"";
s += o.toString();
if (useQuotes) s += "\"";
if (i < theList.size() - 1)
s += ", ";
}
return s + "]";
}
private static List<String> renderStateHistory(List<Set<GdlSentence>> stateHistory) {
List<String> renderedStates = new ArrayList<String>();
for (Set<GdlSentence> aState : stateHistory) {
renderedStates.add(renderStateAsSymbolList(aState));
}
return renderedStates;
}
private static List<String> renderMoveHistory(List<List<GdlSentence>> moveHistory) {
List<String> renderedMoves = new ArrayList<String>();
for (List<GdlSentence> aMove : moveHistory) {
renderedMoves.add(renderArrayAsJSON(aMove, true));
}
return renderedMoves;
}
private static List<String> renderErrorHistory(List<List<String>> errorHistory) {
List<String> renderedErrors = new ArrayList<String>();
for (List<String> anError : errorHistory) {
renderedErrors.add(renderArrayAsJSON(anError, true));
}
return renderedErrors;
}
private static String renderStateAsSymbolList(Set<GdlSentence> theState) {
// Strip out the TRUE proposition, since those are implied for states.
String s = "( ";
for (GdlSentence sent : theState) {
String sentString = sent.toString();
s += sentString.substring(6, sentString.length()-2).trim() + " ";
}
return s + ")";
}
} | ggp-base/src/util/match/Match.java | package util.match;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import external.JSON.JSONArray;
import external.JSON.JSONException;
import external.JSON.JSONObject;
import util.crypto.SignableJSON;
import util.crypto.BaseCryptography.EncodedKeyPair;
import util.game.Game;
import util.game.RemoteGameRepository;
import util.gdl.factory.GdlFactory;
import util.gdl.factory.exceptions.GdlFormatException;
import util.gdl.grammar.GdlSentence;
import util.statemachine.Move;
import util.statemachine.Role;
import util.symbol.factory.SymbolFactory;
import util.symbol.factory.exceptions.SymbolFormatException;
import util.symbol.grammar.SymbolList;
/**
* Match encapsulates all of the information relating to a single match.
* A match is a single play through a game, with a complete history that
* lists what move each player made at each step through the match. This
* also includes other relevant metadata about the match, including some
* unique identifiers, configuration information, and so on.
*
* NOTE: Match objects created by a player, representing state read from
* a server, are not completely filled out. For example, they only get an
* ephemeral Game object, which has a rulesheet but no key or metadata.
* Gamers which do not derive from StateMachineGamer also do not keep any
* information on what states have been observed, because (somehow) they
* are representing games without using state machines. In general, these
* player-created Match objects shouldn't be sent out into the ecosystem.
*
* @author Sam
*/
public final class Match
{
private final String matchId;
private final String randomToken;
private final String spectatorAuthToken;
private final int playClock;
private final int startClock;
private final Date startTime;
private final Game theGame;
private final List<String> theRoleNames;
private final List<List<GdlSentence>> moveHistory;
private final List<Set<GdlSentence>> stateHistory;
private final List<List<String>> errorHistory;
private final List<Date> stateTimeHistory;
private boolean isCompleted;
private final List<Integer> goalValues;
private EncodedKeyPair theCryptographicKeys;
private List<String> thePlayerNamesFromHost;
public Match(String matchId, int startClock, int playClock, Game theGame)
{
this.matchId = matchId;
this.startClock = startClock;
this.playClock = playClock;
this.theGame = theGame;
this.startTime = new Date();
this.randomToken = getRandomString(32);
this.spectatorAuthToken = getRandomString(12);
this.isCompleted = false;
this.theRoleNames = new ArrayList<String>();
for(Role r : Role.computeRoles(theGame.getRules())) {
this.theRoleNames.add(r.getName().getName().toString());
}
this.moveHistory = new ArrayList<List<GdlSentence>>();
this.stateHistory = new ArrayList<Set<GdlSentence>>();
this.stateTimeHistory = new ArrayList<Date>();
this.errorHistory = new ArrayList<List<String>>();
this.goalValues = new ArrayList<Integer>();
}
public Match(String theJSON, Game theGame) throws JSONException, SymbolFormatException, GdlFormatException {
JSONObject theMatchObject = new JSONObject(theJSON);
this.matchId = theMatchObject.getString("matchId");
this.startClock = theMatchObject.getInt("startClock");
this.playClock = theMatchObject.getInt("playClock");
if (theGame == null) {
this.theGame = RemoteGameRepository.loadSingleGame(theMatchObject.getString("gameMetaURL"));
if (this.theGame == null) {
throw new RuntimeException("Could not find metadata for game referenced in Match object: " + theMatchObject.getString("gameMetaURL"));
}
} else {
this.theGame = theGame;
}
this.startTime = new Date(theMatchObject.getLong("startTime"));
this.randomToken = theMatchObject.getString("randomToken");
this.spectatorAuthToken = null;
this.isCompleted = theMatchObject.getBoolean("isCompleted");
this.theRoleNames = new ArrayList<String>();
if (theMatchObject.has("gameRoleNames")) {
JSONArray theNames = theMatchObject.getJSONArray("gameRoleNames");
for (int i = 0; i < theNames.length(); i++) {
this.theRoleNames.add(theNames.getString(i));
}
} else {
for(Role r : Role.computeRoles(this.theGame.getRules())) {
this.theRoleNames.add(r.getName().getName().toString());
}
}
this.moveHistory = new ArrayList<List<GdlSentence>>();
this.stateHistory = new ArrayList<Set<GdlSentence>>();
this.stateTimeHistory = new ArrayList<Date>();
this.errorHistory = new ArrayList<List<String>>();
JSONArray theMoves = theMatchObject.getJSONArray("moves");
for (int i = 0; i < theMoves.length(); i++) {
List<GdlSentence> theMove = new ArrayList<GdlSentence>();
JSONArray moveElements = theMoves.getJSONArray(i);
for (int j = 0; j < moveElements.length(); j++) {
theMove.add((GdlSentence)GdlFactory.create(moveElements.getString(j)));
}
moveHistory.add(theMove);
}
JSONArray theStates = theMatchObject.getJSONArray("states");
for (int i = 0; i < theStates.length(); i++) {
Set<GdlSentence> theState = new HashSet<GdlSentence>();
SymbolList stateElements = (SymbolList) SymbolFactory.create(theStates.getString(i));
for (int j = 0; j < stateElements.size(); j++)
{
theState.add((GdlSentence)GdlFactory.create("( true " + stateElements.get(j).toString() + " )"));
}
stateHistory.add(theState);
}
JSONArray theStateTimes = theMatchObject.getJSONArray("stateTimes");
for (int i = 0; i < theStateTimes.length(); i++) {
this.stateTimeHistory.add(new Date(theStateTimes.getLong(i)));
}
if (theMatchObject.has("errors")) {
JSONArray theErrors = theMatchObject.getJSONArray("errors");
for (int i = 0; i < theErrors.length(); i++) {
List<String> theMoveErrors = new ArrayList<String>();
JSONArray errorElements = theErrors.getJSONArray(i);
for (int j = 0; j < errorElements.length(); j++)
{
theMoveErrors.add(errorElements.getString(j));
}
errorHistory.add(theMoveErrors);
}
}
this.goalValues = new ArrayList<Integer>();
try {
JSONArray theGoalValues = theMatchObject.getJSONArray("goalValues");
for (int i = 0; i < theGoalValues.length(); i++) {
this.goalValues.add(theGoalValues.getInt(i));
}
} catch (JSONException e) {}
// TODO: Add a way to recover cryptographic public keys and signatures.
// Or, perhaps loading a match into memory for editing should strip those?
if (theMatchObject.has("playerNamesFromHost")) {
thePlayerNamesFromHost = new ArrayList<String>();
JSONArray thePlayerNames = theMatchObject.getJSONArray("playerNamesFromHost");
for (int i = 0; i < thePlayerNames.length(); i++) {
thePlayerNamesFromHost.add(thePlayerNames.getString(i));
}
}
}
/* Mutators */
public void setCryptographicKeys(EncodedKeyPair k) {
this.theCryptographicKeys = k;
}
public void setPlayerNamesFromHost(List<String> thePlayerNames) {
this.thePlayerNamesFromHost = thePlayerNames;
}
public void appendMoves(List<GdlSentence> moves) {
moveHistory.add(moves);
}
public void appendMoves2(List<Move> moves) {
// NOTE: This is appendMoves2 because it Java can't handle two
// appendMove methods that both take List objects with different
// templatized parameters.
if (moves.get(0) instanceof Move) {
List<GdlSentence> theMoves = new ArrayList<GdlSentence>();
for(Move m : moves) {
theMoves.add(m.getContents());
}
appendMoves(theMoves);
}
}
public void appendState(Set<GdlSentence> state) {
stateHistory.add(state);
stateTimeHistory.add(new Date());
}
public void appendErrors(List<String> errors) {
errorHistory.add(errors);
}
public void appendNoErrors() {
List<String> theNoErrors = new ArrayList<String>();
for (int i = 0; i < this.theRoleNames.size(); i++) {
theNoErrors.add("");
}
errorHistory.add(theNoErrors);
}
public void markCompleted(List<Integer> theGoalValues) {
this.isCompleted = true;
if (theGoalValues != null) {
this.goalValues.addAll(theGoalValues);
}
}
/* Complex accessors */
public String toJSON() {
JSONObject theJSON = new JSONObject();
try {
theJSON.put("matchId", matchId);
theJSON.put("randomToken", randomToken);
theJSON.put("startTime", startTime.getTime());
theJSON.put("gameName", getGameName());
theJSON.put("gameMetaURL", getGameRepositoryURL());
theJSON.put("gameRoleNames", new JSONArray(renderArrayAsJSON(theRoleNames, true)));
theJSON.put("isCompleted", isCompleted);
theJSON.put("states", new JSONArray(renderArrayAsJSON(renderStateHistory(stateHistory), true)));
theJSON.put("moves", new JSONArray(renderArrayAsJSON(renderMoveHistory(moveHistory), false)));
theJSON.put("stateTimes", new JSONArray(renderArrayAsJSON(stateTimeHistory, false)));
if (errorHistory.size() > 0) {
theJSON.put("errors", new JSONArray(renderArrayAsJSON(renderErrorHistory(errorHistory), false)));
}
if (goalValues.size() > 0) {
theJSON.put("goalValues", goalValues);
}
theJSON.put("startClock", startClock);
theJSON.put("playClock", playClock);
if (thePlayerNamesFromHost != null) {
theJSON.put("playerNamesFromHost", thePlayerNamesFromHost);
}
} catch (JSONException e) {
return null;
}
if (theCryptographicKeys != null) {
try {
SignableJSON.signJSON(theJSON, theCryptographicKeys.thePublicKey, theCryptographicKeys.thePrivateKey);
if (!SignableJSON.isSignedJSON(theJSON)) {
throw new Exception("Could not recognize signed match: " + theJSON);
}
if (!SignableJSON.verifySignedJSON(theJSON)) {
throw new Exception("Could not verify signed match: " + theJSON);
}
} catch (Exception e) {
System.err.println(e);
theJSON.remove("matchHostPK");
theJSON.remove("matchHostSignature");
}
}
return theJSON.toString();
}
public List<GdlSentence> getMostRecentMoves() {
if (moveHistory.size() == 0)
return null;
return moveHistory.get(moveHistory.size()-1);
}
public Set<GdlSentence> getMostRecentState() {
if (stateHistory.size() == 0)
return null;
return stateHistory.get(stateHistory.size()-1);
}
public String getGameName() {
return getGame().getName();
}
public String getGameRepositoryURL() {
return getGame().getRepositoryURL();
}
public String toString() {
return toJSON();
}
/* Simple accessors */
public String getMatchId() {
return matchId;
}
public String getRandomToken() {
return randomToken;
}
public String getSpectatorAuthToken() {
return spectatorAuthToken;
}
public Game getGame() {
return theGame;
}
public List<List<GdlSentence>> getMoveHistory() {
return moveHistory;
}
public List<Set<GdlSentence>> getStateHistory() {
return stateHistory;
}
public List<Date> getStateTimeHistory() {
return stateTimeHistory;
}
public List<List<String>> getErrorHistory() {
return errorHistory;
}
public int getPlayClock() {
return playClock;
}
public int getStartClock() {
return startClock;
}
public Date getStartTime() {
return startTime;
}
public List<String> getRoleNames() {
return theRoleNames;
}
public boolean isCompleted() {
return isCompleted;
}
public List<Integer> getGoalValues() {
return goalValues;
}
/* Static methods */
public static String getRandomString(int nLength) {
Random theGenerator = new Random();
String theString = "";
for (int i = 0; i < nLength; i++) {
int nVal = theGenerator.nextInt(62);
if (nVal < 26) theString += (char)('a' + nVal);
else if (nVal < 52) theString += (char)('A' + (nVal-26));
else if (nVal < 62) theString += (char)('0' + (nVal-52));
}
return theString;
}
private static String renderArrayAsJSON(List<?> theList, boolean useQuotes) {
String s = "[";
for (int i = 0; i < theList.size(); i++) {
Object o = theList.get(i);
// AppEngine-specific, not needed yet: if (o instanceof Text) o = ((Text)o).getValue();
if (o instanceof Date) o = ((Date)o).getTime();
if (useQuotes) s += "\"";
s += o.toString();
if (useQuotes) s += "\"";
if (i < theList.size() - 1)
s += ", ";
}
return s + "]";
}
private static List<String> renderStateHistory(List<Set<GdlSentence>> stateHistory) {
List<String> renderedStates = new ArrayList<String>();
for (Set<GdlSentence> aState : stateHistory) {
renderedStates.add(renderStateAsSymbolList(aState));
}
return renderedStates;
}
private static List<String> renderMoveHistory(List<List<GdlSentence>> moveHistory) {
List<String> renderedMoves = new ArrayList<String>();
for (List<GdlSentence> aMove : moveHistory) {
renderedMoves.add(renderArrayAsJSON(aMove, true));
}
return renderedMoves;
}
private static List<String> renderErrorHistory(List<List<String>> errorHistory) {
List<String> renderedErrors = new ArrayList<String>();
for (List<String> anError : errorHistory) {
renderedErrors.add(renderArrayAsJSON(anError, true));
}
return renderedErrors;
}
private static String renderStateAsSymbolList(Set<GdlSentence> theState) {
// Strip out the TRUE proposition, since those are implied for states.
String s = "( ";
for (GdlSentence sent : theState) {
String sentString = sent.toString();
s += sentString.substring(6, sentString.length()-2).trim() + " ";
}
return s + ")";
}
} | Stop publishing the game names and game role names, since that information should be derivable from the game metadata URL.
git-svn-id: 4739e81c2fe647bfb539b919360e2c658e6121ea@379 716a755e-b13f-cedc-210d-596dafc6fb9b
| ggp-base/src/util/match/Match.java | Stop publishing the game names and game role names, since that information should be derivable from the game metadata URL. | <ide><path>gp-base/src/util/match/Match.java
<ide> private final int startClock;
<ide> private final Date startTime;
<ide> private final Game theGame;
<del> private final List<String> theRoleNames;
<add> private final List<String> theRoleNames; // TODO: remove this
<ide> private final List<List<GdlSentence>> moveHistory;
<ide> private final List<Set<GdlSentence>> stateHistory;
<ide> private final List<List<String>> errorHistory;
<ide> theJSON.put("matchId", matchId);
<ide> theJSON.put("randomToken", randomToken);
<ide> theJSON.put("startTime", startTime.getTime());
<del> theJSON.put("gameName", getGameName());
<ide> theJSON.put("gameMetaURL", getGameRepositoryURL());
<del> theJSON.put("gameRoleNames", new JSONArray(renderArrayAsJSON(theRoleNames, true)));
<ide> theJSON.put("isCompleted", isCompleted);
<ide> theJSON.put("states", new JSONArray(renderArrayAsJSON(renderStateHistory(stateHistory), true)));
<ide> theJSON.put("moves", new JSONArray(renderArrayAsJSON(renderMoveHistory(moveHistory), false)));
<ide> return stateHistory.get(stateHistory.size()-1);
<ide> }
<ide>
<del> public String getGameName() {
<del> return getGame().getName();
<del> }
<del>
<ide> public String getGameRepositoryURL() {
<ide> return getGame().getRepositoryURL();
<ide> }
<ide>
<ide> public Date getStartTime() {
<ide> return startTime;
<del> }
<del>
<del> public List<String> getRoleNames() {
<del> return theRoleNames;
<ide> }
<ide>
<ide> public boolean isCompleted() { |
|
Java | apache-2.0 | error: pathspec 'modules/citrus-http/src/test/java/com/consol/citrus/http/message/HttpMessageTest.java' did not match any file(s) known to git
| 50957086d3f849f7936d46b99214f8bc78a8c64d | 1 | christophd/citrus,christophd/citrus | /*
* Copyright 2018 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.http.message;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.servlet.http.Cookie;
import static org.mockito.Mockito.mock;
public class HttpMessageTest {
private HttpMessage httpMessage;
@BeforeMethod
public void setUp(){
httpMessage = new HttpMessage();
}
@Test
public void testSetCookies() {
//GIVEN
final Cookie cookie = mock(Cookie.class);
final Cookie[] cookies = new Cookie[]{cookie};
//WHEN
httpMessage.setCookies(cookies);
//THEN
Assert.assertTrue(httpMessage.getCookies().contains(cookie));
}
@Test
public void testSetCookiesOverwritesOldCookies() {
//GIVEN
httpMessage.setCookies(new Cookie[]{
mock(Cookie.class),
mock(Cookie.class)});
final Cookie expectedCookie = mock(Cookie.class);
final Cookie[] cookies = new Cookie[]{expectedCookie};
//WHEN
httpMessage.setCookies(cookies);
//THEN
Assert.assertTrue(httpMessage.getCookies().contains(expectedCookie));
Assert.assertEquals(httpMessage.getCookies().size(), 1);
}
} | modules/citrus-http/src/test/java/com/consol/citrus/http/message/HttpMessageTest.java | (#569) Added tests for the root cause of the issue
| modules/citrus-http/src/test/java/com/consol/citrus/http/message/HttpMessageTest.java | (#569) Added tests for the root cause of the issue | <ide><path>odules/citrus-http/src/test/java/com/consol/citrus/http/message/HttpMessageTest.java
<add>/*
<add> * Copyright 2018 the original author or authors
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package com.consol.citrus.http.message;
<add>
<add>import org.testng.Assert;
<add>import org.testng.annotations.BeforeMethod;
<add>import org.testng.annotations.Test;
<add>
<add>import javax.servlet.http.Cookie;
<add>
<add>import static org.mockito.Mockito.mock;
<add>
<add>public class HttpMessageTest {
<add>
<add> private HttpMessage httpMessage;
<add>
<add> @BeforeMethod
<add> public void setUp(){
<add> httpMessage = new HttpMessage();
<add> }
<add>
<add> @Test
<add> public void testSetCookies() {
<add>
<add> //GIVEN
<add> final Cookie cookie = mock(Cookie.class);
<add> final Cookie[] cookies = new Cookie[]{cookie};
<add>
<add> //WHEN
<add> httpMessage.setCookies(cookies);
<add>
<add> //THEN
<add> Assert.assertTrue(httpMessage.getCookies().contains(cookie));
<add> }
<add>
<add> @Test
<add> public void testSetCookiesOverwritesOldCookies() {
<add>
<add> //GIVEN
<add> httpMessage.setCookies(new Cookie[]{
<add> mock(Cookie.class),
<add> mock(Cookie.class)});
<add>
<add> final Cookie expectedCookie = mock(Cookie.class);
<add> final Cookie[] cookies = new Cookie[]{expectedCookie};
<add>
<add> //WHEN
<add> httpMessage.setCookies(cookies);
<add>
<add> //THEN
<add> Assert.assertTrue(httpMessage.getCookies().contains(expectedCookie));
<add> Assert.assertEquals(httpMessage.getCookies().size(), 1);
<add> }
<add>} |
|
JavaScript | mit | 9fa5030349a88baaeabbddafe6c8a611621dd458 | 0 | ModelSEED/ModelSEED-UI,ModelSEED/ModelSEED-UI,ModelSEED/ModelSEED-UI,ModelSEED/ModelSEED-UI | /*
* auth.js
* Angular.js module for using authentication services
*
* Authors:
* https://github.com/nconrad
*
*/
angular.module('Auth', [])
.service('Auth', ['$state', '$http', 'config', '$window',
function($state, $http, config, $window) {
var self = this;
this.user;
this.token;
var auth = getAuthStatus();
// if previously authenticated, set user/token
if (auth) {
this.user = auth.user_id;
this.token = auth.token;
// set auth method used
if (this.token.indexOf('rast.nmpdr.org') !== -1)
this.method == 'rast';
else if (this.token.indexOf('user.patric.org') !== -1)
this.method == 'patric';
}
console.log('token', this.token);
console.log('using service:', config.services.auth_url)
/**
* [Authentication against RAST]
* @param {[string]} user [rast username]
* @param {[string]} pass [rast password]
* @return {[object]} [rast auth object]
*/
this.login = function(user, pass) {
var data = {
user_id: user,
password: pass,
status: 1,
cookie:1,
fields: "name,user_id,token"
};
return $http({method: "POST",
url: config.services.auth_url,
data: $.param(data),
}).success(function(res) {
// store auth object
$window.localStorage.setItem('auth', JSON.stringify(res));
self.user = res.user_id;
self.token = res.token;
return res;
});
}
/**
* [Authentication against PATRIC]
* @param {[string]} user [patric username]
* @param {[string]} pass [patric password]
* @return {[object]} [patric user/pass token]
*/
this.loginPatric = function(user, pass) {
var data = {username: user, password: pass};
return $http({method: "POST",
url: config.services.patric_auth_url,
data: $.param(data),
}).success(function(token) {
var user_id = token.split('|')[0].replace('un=', '');
var obj = {user_id: user_id, token: token};
// store username/token
$window.localStorage.setItem('auth', JSON.stringify(obj) );
self.user = obj.user_id;
self.token = JSON.stringify(obj.token);
return obj;
});
}
this.logout = function() {
$window.localStorage.removeItem('auth');
$state.transitionTo('main.home', {}, { reload: true, inherit: true, notify: false })
.then(function() {
$window.location.reload();
});
}
this.isAuthenticated = function() {
return (self.user && getAuthStatus()) ? true : false;
}
this.loginMethod = function(method) {
if (method === 'patric')
return {
name: 'PATRIC',
newAccountURL: 'https://user.patricbrc.org/register/',
forgotPasswordUrl: 'https://user.patricbrc.org/reset_password'
};
return {
name: 'RAST',
newAccountURL: 'http://rast.nmpdr.org/?page=Register',
forgotPasswordUrl: 'http://rast.nmpdr.org/?page=RequestNewPassword'
};
}
function getAuthStatus() {
return JSON.parse( localStorage.getItem('auth') );
}
function storageEventHandler(e) {
// if logout has happened, logout every tab.
if (e.key === 'auth' && !e.newValue) self.logout()
}
// listen for storage change across tabs/windows
$window.addEventListener('storage', storageEventHandler);
}]);
| app/services/auth.js | /*
* auth.js
* Angular.js module for using authentication services
*
* Authors:
* https://github.com/nconrad
*
*/
angular.module('Auth', [])
.service('Auth', ['$state', '$http', 'config', '$window',
function($state, $http, config, $window) {
var self = this;
this.user;
this.token;
var auth = getAuthStatus();
// if previously authenticated, set user/token
if (auth) {
this.user = auth.user_id;
this.token = auth.token;
// set auth method used
if (this.token.indexOf('rast.nmpdr.org') !== -1)
this.method == 'rast';
else if (this.token.indexOf('user.patric.org') !== -1)
this.method == 'patric';
}
console.log('token', this.token);
console.log('using service:', config.services.auth_url)
/**
* [Authentication against RAST]
* @param {[string]} user [rast username]
* @param {[string]} pass [rast password]
* @return {[object]} [rast auth object]
*/
this.login = function(user, pass) {
var data = {
user_id: user,
password: pass,
status: 1,
cookie:1,
fields: "name,user_id,token"
};
return $http({method: "POST",
url: config.services.auth_url,
data: $.param(data),
}).success(function(res) {
// store auth object
$window.localStorage.setItem('auth', JSON.stringify(res));
self.user = res.user_id;
self.token = res.token;
return res;
});
}
/**
* [Authentication against PATRIC]
* @param {[string]} user [patric username]
* @param {[string]} pass [patric password]
* @return {[object]} [patric user/pass token]
*/
this.loginPatric = function(user, pass) {
var data = {username: user, password: pass};
return $http({method: "POST",
url: config.services.patric_auth_url,
data: $.param(data),
}).success(function(token) {
var user_id = token.split('|')[0].replace('un=', '');
var obj = {user_id: user_id, token: token};
// store username/token
$window.localStorage.setItem('auth', JSON.stringify(obj) );
self.user = obj.user_id;
self.token = JSON.stringify(obj.token);
return obj;
});
}
this.logout = function() {
$window.localStorage.removeItem('auth');
$window.location.reload();
}
this.isAuthenticated = function() {
return (self.user && getAuthStatus()) ? true : false;
}
this.loginMethod = function(method) {
if (method === 'patric')
return {
name: 'PATRIC',
newAccountURL: 'https://user.patricbrc.org/register/',
forgotPasswordUrl: 'https://user.patricbrc.org/reset_password'
};
return {
name: 'RAST',
newAccountURL: 'http://rast.nmpdr.org/?page=Register',
forgotPasswordUrl: 'http://rast.nmpdr.org/?page=RequestNewPassword'
};
}
function getAuthStatus() {
return JSON.parse( localStorage.getItem('auth') );
}
function storageEventHandler(e) {
// if logout has happened, logout every tab.
if (e.key === 'auth' && !e.newValue) self.logout()
}
// listen for storage change across tabs/windows
$window.addEventListener('storage', storageEventHandler);
}]);
| redirect to home after logout
| app/services/auth.js | redirect to home after logout | <ide><path>pp/services/auth.js
<ide>
<ide> this.logout = function() {
<ide> $window.localStorage.removeItem('auth');
<del> $window.location.reload();
<add> $state.transitionTo('main.home', {}, { reload: true, inherit: true, notify: false })
<add> .then(function() {
<add> $window.location.reload();
<add> });
<ide> }
<ide>
<ide> this.isAuthenticated = function() {
<ide> return {
<ide> name: 'PATRIC',
<ide> newAccountURL: 'https://user.patricbrc.org/register/',
<del> forgotPasswordUrl: 'https://user.patricbrc.org/reset_password'
<add> forgotPasswordUrl: 'https://user.patricbrc.org/reset_password'
<ide> };
<ide>
<ide> return { |
|
Java | apache-2.0 | 54525ffaed5e8925d97657a622532a00a0006347 | 0 | GerritCodeReview/plugins_reviewnotes | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.reviewnotes;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.data.LabelType;
import com.google.gerrit.common.data.LabelTypes;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ApprovalsUtil;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.account.AccountCache;
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.config.AnonymousCowardName;
import com.google.gerrit.server.config.CanonicalWebUrl;
import com.google.gerrit.server.git.LockFailureException;
import com.google.gerrit.server.git.NotesBranchUtil;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gerrit.server.query.change.InternalChangeQuery;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.NullProgressMonitor;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.ProgressMonitor;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.notes.NoteMap;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
class CreateReviewNotes {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
interface Factory {
CreateReviewNotes create(ReviewDb reviewDb, Project.NameKey project, Repository git);
}
private static final String REFS_NOTES_REVIEW = "refs/notes/review";
private final PersonIdent gerritServerIdent;
private final AccountCache accountCache;
private final String anonymousCowardName;
private final LabelTypes labelTypes;
private final ApprovalsUtil approvalsUtil;
private final ChangeNotes.Factory notesFactory;
private final NotesBranchUtil.Factory notesBranchUtilFactory;
private final Provider<InternalChangeQuery> queryProvider;
private final String canonicalWebUrl;
private final ReviewDb reviewDb;
private final Project.NameKey project;
private final Repository git;
private ObjectInserter inserter;
private NoteMap reviewNotes;
private StringBuilder message;
@Inject
CreateReviewNotes(
@GerritPersonIdent PersonIdent gerritIdent,
AccountCache accountCache,
@AnonymousCowardName String anonymousCowardName,
ProjectCache projectCache,
ApprovalsUtil approvalsUtil,
ChangeNotes.Factory notesFactory,
NotesBranchUtil.Factory notesBranchUtilFactory,
Provider<InternalChangeQuery> queryProvider,
@Nullable @CanonicalWebUrl String canonicalWebUrl,
@Assisted ReviewDb reviewDb,
@Assisted Project.NameKey project,
@Assisted Repository git) {
this.gerritServerIdent = gerritIdent;
this.accountCache = accountCache;
this.anonymousCowardName = anonymousCowardName;
ProjectState projectState = projectCache.get(project);
if (projectState == null) {
logger.atSevere().log(
"Could not obtain available labels for project %s."
+ " Expect missing labels in its review notes.",
project.get());
this.labelTypes = new LabelTypes(Collections.<LabelType>emptyList());
} else {
this.labelTypes = projectState.getLabelTypes();
}
this.approvalsUtil = approvalsUtil;
this.notesFactory = notesFactory;
this.notesBranchUtilFactory = notesBranchUtilFactory;
this.queryProvider = queryProvider;
this.canonicalWebUrl = canonicalWebUrl;
this.reviewDb = reviewDb;
this.project = project;
this.git = git;
}
void createNotes(
String branch, ObjectId oldObjectId, ObjectId newObjectId, ProgressMonitor monitor)
throws OrmException, IOException {
if (ObjectId.zeroId().equals(newObjectId)) {
return;
}
try (RevWalk rw = new RevWalk(git)) {
try {
RevCommit n = rw.parseCommit(newObjectId);
rw.markStart(n);
if (n.getParentCount() == 1 && n.getParent(0).equals(oldObjectId)) {
rw.markUninteresting(rw.parseCommit(oldObjectId));
} else {
markUninteresting(git, branch, rw, oldObjectId);
}
} catch (Exception e) {
logger.atSevere().withCause(e).log(e.getMessage());
return;
}
if (monitor == null) {
monitor = NullProgressMonitor.INSTANCE;
}
for (RevCommit c : rw) {
PatchSet ps = loadPatchSet(c, branch);
if (ps != null) {
ChangeNotes notes = notesFactory.create(reviewDb, project, ps.getId().getParentKey());
ObjectId content = createNoteContent(notes, ps);
if (content != null) {
monitor.update(1);
getNotes().set(c, content);
getMessage().append("* ").append(c.getShortMessage()).append("\n");
}
} else {
logger.atFine().log(
"no note for this commit since it is a direct push %s", c.getName().substring(0, 7));
}
}
}
}
void createNotes(List<ChangeNotes> notes, ProgressMonitor monitor)
throws OrmException, IOException {
try (RevWalk rw = new RevWalk(git)) {
if (monitor == null) {
monitor = NullProgressMonitor.INSTANCE;
}
for (ChangeNotes cn : notes) {
monitor.update(1);
PatchSet ps = reviewDb.patchSets().get(cn.getChange().currentPatchSetId());
ObjectId commitId = ObjectId.fromString(ps.getRevision().get());
RevCommit commit = rw.parseCommit(commitId);
getNotes().set(commitId, createNoteContent(cn, ps));
getMessage().append("* ").append(commit.getShortMessage()).append("\n");
}
}
}
void commitNotes() throws LockFailureException, IOException {
try {
if (reviewNotes == null) {
return;
}
message.insert(0, "Update notes for submitted changes\n\n");
notesBranchUtilFactory
.create(project, git, inserter)
.commitAllNotes(reviewNotes, REFS_NOTES_REVIEW, gerritServerIdent, message.toString());
} finally {
if (inserter != null) {
inserter.close();
}
}
}
private void markUninteresting(Repository git, String branch, RevWalk rw, ObjectId oldObjectId)
throws IOException {
for (Ref r : git.getRefDatabase().getRefs()) {
try {
if (r.getName().equals(branch)) {
if (!ObjectId.zeroId().equals(oldObjectId)) {
// For the updated branch the oldObjectId is the tip of uninteresting
// commit history
rw.markUninteresting(rw.parseCommit(oldObjectId));
}
} else if (r.getName().startsWith(Constants.R_HEADS)
|| r.getName().startsWith(Constants.R_TAGS)) {
rw.markUninteresting(rw.parseCommit(r.getObjectId()));
}
} catch (IncorrectObjectTypeException e) {
// skip if not parseable as a commit
} catch (MissingObjectException e) {
// skip if not parseable as a commit
} catch (IOException e) {
// skip if not parseable as a commit
}
}
}
private ObjectId createNoteContent(ChangeNotes notes, PatchSet ps)
throws OrmException, IOException {
HeaderFormatter fmt = new HeaderFormatter(gerritServerIdent.getTimeZone(), anonymousCowardName);
if (ps != null) {
try {
createCodeReviewNote(notes, ps, fmt);
return getInserter().insert(Constants.OBJ_BLOB, fmt.toString().getBytes("UTF-8"));
} catch (NoSuchChangeException e) {
throw new IOException(e);
}
}
return null;
}
private PatchSet loadPatchSet(RevCommit c, String destBranch) throws OrmException {
String hash = c.name();
for (ChangeData cd : queryProvider.get().byBranchCommit(project.get(), destBranch, hash)) {
for (PatchSet ps : cd.patchSets()) {
if (ps.getRevision().matches(hash)) {
return ps;
}
}
}
return null; // TODO: createNoCodeReviewNote(branch, c, fmt);
}
private void createCodeReviewNote(ChangeNotes notes, PatchSet ps, HeaderFormatter fmt)
throws OrmException, NoSuchChangeException {
// This races with the label normalization/writeback done by MergeOp. It may
// repeat some work, but results should be identical except in the case of
// an additional race with a permissions change.
// TODO(dborowitz): These will eventually be stamped in the ChangeNotes at
// commit time so we will be able to skip this normalization step.
Change change = notes.getChange();
PatchSetApproval submit = null;
for (PatchSetApproval a : approvalsUtil.byPatchSet(reviewDb, notes, ps.getId(), null, null)) {
if (a.getValue() == 0) {
// Ignore 0 values.
} else if (a.isLegacySubmit()) {
submit = a;
} else {
LabelType type = labelTypes.byLabel(a.getLabelId());
if (type != null) {
fmt.appendApproval(
type,
a.getValue(),
a.getAccountId(),
accountCache.get(a.getAccountId()).map(AccountState::getAccount));
}
}
}
if (submit != null) {
fmt.appendSubmittedBy(
submit.getAccountId(),
accountCache.get(submit.getAccountId()).map(AccountState::getAccount));
fmt.appendSubmittedAt(submit.getGranted());
}
if (canonicalWebUrl != null) {
fmt.appendReviewedOn(canonicalWebUrl, ps.getId().getParentKey());
}
fmt.appendProject(project.get());
fmt.appendBranch(change.getDest().get());
}
private ObjectInserter getInserter() {
if (inserter == null) {
inserter = git.newObjectInserter();
}
return inserter;
}
private NoteMap getNotes() {
if (reviewNotes == null) {
reviewNotes = NoteMap.newEmptyMap();
}
return reviewNotes;
}
private StringBuilder getMessage() {
if (message == null) {
message = new StringBuilder();
}
return message;
}
}
| src/main/java/com/googlesource/gerrit/plugins/reviewnotes/CreateReviewNotes.java | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.reviewnotes;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.data.LabelType;
import com.google.gerrit.common.data.LabelTypes;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ApprovalsUtil;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.account.AccountCache;
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.config.AnonymousCowardName;
import com.google.gerrit.server.config.CanonicalWebUrl;
import com.google.gerrit.server.git.LockFailureException;
import com.google.gerrit.server.git.NotesBranchUtil;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gerrit.server.query.change.InternalChangeQuery;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.NullProgressMonitor;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.ProgressMonitor;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.notes.NoteMap;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
class CreateReviewNotes {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
interface Factory {
CreateReviewNotes create(ReviewDb reviewDb, Project.NameKey project, Repository git);
}
private static final String REFS_NOTES_REVIEW = "refs/notes/review";
private final PersonIdent gerritServerIdent;
private final AccountCache accountCache;
private final String anonymousCowardName;
private final LabelTypes labelTypes;
private final ApprovalsUtil approvalsUtil;
private final ChangeNotes.Factory notesFactory;
private final NotesBranchUtil.Factory notesBranchUtilFactory;
private final Provider<InternalChangeQuery> queryProvider;
private final String canonicalWebUrl;
private final ReviewDb reviewDb;
private final Project.NameKey project;
private final Repository git;
private ObjectInserter inserter;
private NoteMap reviewNotes;
private StringBuilder message;
@Inject
CreateReviewNotes(
@GerritPersonIdent PersonIdent gerritIdent,
AccountCache accountCache,
@AnonymousCowardName String anonymousCowardName,
ProjectCache projectCache,
ApprovalsUtil approvalsUtil,
ChangeNotes.Factory notesFactory,
NotesBranchUtil.Factory notesBranchUtilFactory,
Provider<InternalChangeQuery> queryProvider,
@Nullable @CanonicalWebUrl String canonicalWebUrl,
@Assisted ReviewDb reviewDb,
@Assisted Project.NameKey project,
@Assisted Repository git) {
this.gerritServerIdent = gerritIdent;
this.accountCache = accountCache;
this.anonymousCowardName = anonymousCowardName;
ProjectState projectState = projectCache.get(project);
if (projectState == null) {
logger.atSevere().log(
"Could not obtain available labels for project %s."
+ " Expect missing labels in its review notes.",
project.get());
this.labelTypes = new LabelTypes(Collections.<LabelType>emptyList());
} else {
this.labelTypes = projectState.getLabelTypes();
}
this.approvalsUtil = approvalsUtil;
this.notesFactory = notesFactory;
this.notesBranchUtilFactory = notesBranchUtilFactory;
this.queryProvider = queryProvider;
this.canonicalWebUrl = canonicalWebUrl;
this.reviewDb = reviewDb;
this.project = project;
this.git = git;
}
void createNotes(
String branch, ObjectId oldObjectId, ObjectId newObjectId, ProgressMonitor monitor)
throws OrmException, IOException {
if (ObjectId.zeroId().equals(newObjectId)) {
return;
}
try (RevWalk rw = new RevWalk(git)) {
try {
RevCommit n = rw.parseCommit(newObjectId);
rw.markStart(n);
if (n.getParentCount() == 1 && n.getParent(0).equals(oldObjectId)) {
rw.markUninteresting(rw.parseCommit(oldObjectId));
} else {
markUninteresting(git, branch, rw, oldObjectId);
}
} catch (Exception e) {
logger.atSevere().withCause(e).log(e.getMessage());
return;
}
if (monitor == null) {
monitor = NullProgressMonitor.INSTANCE;
}
for (RevCommit c : rw) {
PatchSet ps = loadPatchSet(c, branch);
if (ps != null) {
ChangeNotes notes = notesFactory.create(reviewDb, project, ps.getId().getParentKey());
ObjectId content = createNoteContent(notes, ps);
if (content != null) {
monitor.update(1);
getNotes().set(c, content);
getMessage().append("* ").append(c.getShortMessage()).append("\n");
}
} else {
logger.atFine().log(
"no note for this commit since it is a direct push %s", c.getName().substring(0, 7));
}
}
}
}
void createNotes(List<ChangeNotes> notes, ProgressMonitor monitor)
throws OrmException, IOException {
try (RevWalk rw = new RevWalk(git)) {
if (monitor == null) {
monitor = NullProgressMonitor.INSTANCE;
}
for (ChangeNotes cn : notes) {
monitor.update(1);
PatchSet ps = reviewDb.patchSets().get(cn.getChange().currentPatchSetId());
ObjectId commitId = ObjectId.fromString(ps.getRevision().get());
RevCommit commit = rw.parseCommit(commitId);
getNotes().set(commitId, createNoteContent(cn, ps));
getMessage().append("* ").append(commit.getShortMessage()).append("\n");
}
}
}
void commitNotes() throws LockFailureException, IOException {
try {
if (reviewNotes == null) {
return;
}
message.insert(0, "Update notes for submitted changes\n\n");
notesBranchUtilFactory
.create(project, git, inserter)
.commitAllNotes(reviewNotes, REFS_NOTES_REVIEW, gerritServerIdent, message.toString());
} finally {
if (inserter != null) {
inserter.close();
}
}
}
private void markUninteresting(Repository git, String branch, RevWalk rw, ObjectId oldObjectId) {
for (Ref r : git.getAllRefs().values()) {
try {
if (r.getName().equals(branch)) {
if (!ObjectId.zeroId().equals(oldObjectId)) {
// For the updated branch the oldObjectId is the tip of uninteresting
// commit history
rw.markUninteresting(rw.parseCommit(oldObjectId));
}
} else if (r.getName().startsWith(Constants.R_HEADS)
|| r.getName().startsWith(Constants.R_TAGS)) {
rw.markUninteresting(rw.parseCommit(r.getObjectId()));
}
} catch (IncorrectObjectTypeException e) {
// skip if not parseable as a commit
} catch (MissingObjectException e) {
// skip if not parseable as a commit
} catch (IOException e) {
// skip if not parseable as a commit
}
}
}
private ObjectId createNoteContent(ChangeNotes notes, PatchSet ps)
throws OrmException, IOException {
HeaderFormatter fmt = new HeaderFormatter(gerritServerIdent.getTimeZone(), anonymousCowardName);
if (ps != null) {
try {
createCodeReviewNote(notes, ps, fmt);
return getInserter().insert(Constants.OBJ_BLOB, fmt.toString().getBytes("UTF-8"));
} catch (NoSuchChangeException e) {
throw new IOException(e);
}
}
return null;
}
private PatchSet loadPatchSet(RevCommit c, String destBranch) throws OrmException {
String hash = c.name();
for (ChangeData cd : queryProvider.get().byBranchCommit(project.get(), destBranch, hash)) {
for (PatchSet ps : cd.patchSets()) {
if (ps.getRevision().matches(hash)) {
return ps;
}
}
}
return null; // TODO: createNoCodeReviewNote(branch, c, fmt);
}
private void createCodeReviewNote(ChangeNotes notes, PatchSet ps, HeaderFormatter fmt)
throws OrmException, NoSuchChangeException {
// This races with the label normalization/writeback done by MergeOp. It may
// repeat some work, but results should be identical except in the case of
// an additional race with a permissions change.
// TODO(dborowitz): These will eventually be stamped in the ChangeNotes at
// commit time so we will be able to skip this normalization step.
Change change = notes.getChange();
PatchSetApproval submit = null;
for (PatchSetApproval a : approvalsUtil.byPatchSet(reviewDb, notes, ps.getId(), null, null)) {
if (a.getValue() == 0) {
// Ignore 0 values.
} else if (a.isLegacySubmit()) {
submit = a;
} else {
LabelType type = labelTypes.byLabel(a.getLabelId());
if (type != null) {
fmt.appendApproval(
type,
a.getValue(),
a.getAccountId(),
accountCache.get(a.getAccountId()).map(AccountState::getAccount));
}
}
}
if (submit != null) {
fmt.appendSubmittedBy(
submit.getAccountId(),
accountCache.get(submit.getAccountId()).map(AccountState::getAccount));
fmt.appendSubmittedAt(submit.getGranted());
}
if (canonicalWebUrl != null) {
fmt.appendReviewedOn(canonicalWebUrl, ps.getId().getParentKey());
}
fmt.appendProject(project.get());
fmt.appendBranch(change.getDest().get());
}
private ObjectInserter getInserter() {
if (inserter == null) {
inserter = git.newObjectInserter();
}
return inserter;
}
private NoteMap getNotes() {
if (reviewNotes == null) {
reviewNotes = NoteMap.newEmptyMap();
}
return reviewNotes;
}
private StringBuilder getMessage() {
if (message == null) {
message = new StringBuilder();
}
return message;
}
}
| CreateReviewNotes: Don't use deprecated Repository.getAllRefs
Change-Id: I867c5003185c9b41c5182b8d05e9db2d9dae2cfa
| src/main/java/com/googlesource/gerrit/plugins/reviewnotes/CreateReviewNotes.java | CreateReviewNotes: Don't use deprecated Repository.getAllRefs | <ide><path>rc/main/java/com/googlesource/gerrit/plugins/reviewnotes/CreateReviewNotes.java
<ide> }
<ide> }
<ide>
<del> private void markUninteresting(Repository git, String branch, RevWalk rw, ObjectId oldObjectId) {
<del> for (Ref r : git.getAllRefs().values()) {
<add> private void markUninteresting(Repository git, String branch, RevWalk rw, ObjectId oldObjectId)
<add> throws IOException {
<add> for (Ref r : git.getRefDatabase().getRefs()) {
<ide> try {
<ide> if (r.getName().equals(branch)) {
<ide> if (!ObjectId.zeroId().equals(oldObjectId)) { |
|
Java | apache-2.0 | 93392b44773e28a4eb12a0b7840890db977c0c21 | 0 | TeamTyro/color-maze-game | /* MazeGame Class
* By Tyler Compton for Team Tyro
*
* This is a very simple and minimal map game. It's official name is
* "Color Maze Game."
*/
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import sql.InfoPackage;
import threads.SendData;
import etc.Constants;
import etc.ErrorReport;
import etc.MazeMap;
public class MazeGame extends Applet {
private static final long serialVersionUID = 1L;
private static int[][] map; // Universal map array
private static int [] recActions; // Stores all the keys pressed. [DIR_RIGHT,UP,DOWN,LEFT]
private static int currentAction; // Keeps track of which part of recActions your using. Basically just a counter for recActions
private static int rCurrentAction; // Replay current action, just for replaying
private static int operation; // The phase of the test. 0= moving around, playing game. 1= Replaying the game 2= Finished with testing, sending data.
private static java.util.Date startDate, endDate; // Actual day, time, milliseconds that you played the game.
private static String sTime, eTime, tTime;
private static boolean [] keyRefresh; //Makes sure that holding a button won't machine-gun it. [true=its up, and can be pressed. False=it's being pressed]
private static int pX, pY; // Player x and y (within the map array)
private static boolean xFlash;
private static int xFlashClock;
Canvas display_parent;
boolean running;
Thread gameThread, sendThread;
int cirTheta, cirRadius;
boolean cirInc;
boolean showDiagonal = true;
/** Function startLWJGL()
* Executes LWJGL's startup methods.
*/
public void startLWJGL() {
gameThread = new Thread() {
public void run() {
running = true;
try {
Display.setParent(display_parent);
Display.create();
initGL();
} catch(LWJGLException ex) {
ErrorReport e = new ErrorReport(ex.getMessage());
e.makeFile();
return;
}
mainLoop();
}
};
gameThread.start();
}
/** Function stopLWJGL
* Stops the game thread.
*/
public void stopLWJGL() {
running = false;
try {
gameThread.join();
} catch(InterruptedException ex) {
ErrorReport e = new ErrorReport(ex.getMessage());
e.makeFile();
}
}
/** Function start()
* Placeholder for the expected start() method in applets.
*/
public void start() {
}
/** Function stop()
* Placeholder for the expected stop() method in applets.
*/
public void stop() {
}
/** Function destroy()
* Destroys the canvas.
*/
public void destroy() {
remove(display_parent);
super.destroy();
}
/** Function init()
* Initializes the canvas and global variables
*/
public void init() {
System.out.printf("TestGame V0.8.0\n");
setLayout(new BorderLayout());
try {
display_parent = new Canvas() {
private static final long serialVersionUID = 1L;
public final void addNotify() {
super.addNotify();
startLWJGL();
}
public final void removeNotify() {
stopLWJGL();
super.removeNotify();
}
};
display_parent.setSize(600,600);
add(display_parent);
display_parent.setFocusable(true);
display_parent.requestFocus();
display_parent.setIgnoreRepaint(true);
setVisible(true);
} catch(Exception ex) {
ErrorReport e = new ErrorReport(ex.getMessage());
e.makeFile();
throw new RuntimeException("Unable to create display!");
}
xFlashClock = 0;
map = makeMaze();
pX = Constants.MAP_WIDTH/2;
pY = 0;
keyRefresh = new boolean [6];
recActions = new int [500];
operation = 3;
currentAction = 0;
cirTheta = 0;
cirRadius = 0;
cirInc = true;
MazeMap maze = new MazeMap();
maze.loadConstMap("cbbbccccccccbbbbcccccbbbbbbcbbbbcbbbcbsbccbcbbbbcccbccc" +
"bccccbbbbcbcbbbcbbbcbbbbbcbcbbbcbcccbbbbbcccccccccbbbbbbbcbbbbbbb" +
"bbbcbbbbccccccccccbcbbbbbbbbbcbbbcccbbbbcccbbcccccccbbbbcbccccbcc" +
"cbcbbbbcbbbbbbcbcbcbbbbcbwcccbcbcbcbbbbcbbbbcbbbcbcbbbbcccccccccc" +
"ccbbbb");
for(int x=0; x<Constants.MAP_WIDTH; x++) {
for(int y=0; y<Constants.MAP_HEIGHT; y++) {
map[x][y] = maze.getSpace(x,y);
if(map[x][y] == Constants.MAP_START) {
pX = x;
pY = y;
}
}
}
}
/** Function initGL()
* Calls OpenGL initialization functions.
*/
protected void initGL() {
// Init OpenGL
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(-300, 300, -300, 300, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
/** Function begin()
* Sets up OpenGL and lwjgl and contains the main loop.
*/
private void mainLoop() {
// Start main loop
while(running) {
// Clears screen and depth buffer
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
// Rendering
render();
if(operation == 0) {
// Testing in progress
checkKeys();
if(map[pX][pY] == Constants.MAP_WIN) {
endDate = new java.util.Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("hh:mm:ss.SSS");
eTime = sdf.format(endDate);
SendData sender = new SendData(packUp(sTime, eTime, recActions));
sendThread = new Thread(sender);
sendThread.start();
operation = 2;
}
} else if(operation == 1) {
// Replay debug feature
if(rCurrentAction < currentAction) {
replayGame(recActions, rCurrentAction);
rCurrentAction++;
}
} else if(operation == 2) {
// Pending send
if(!sendThread.isAlive()) {
System.out.printf("Finished sending... Bringing to success page.\n");
try {
getAppletContext().showDocument(new URL(getCodeBase()+"thanks.php?time=" + tTime ),"_top");
} catch (MalformedURLException ex) {
System.out.println(ex.getMessage());
}
operation = 4;
} else {
if(cirTheta >= 360) {
cirTheta = 0;
} else {
cirTheta++;
}
if(cirRadius >= 300) {
cirInc = false;
} else if(cirRadius <= 0) {
cirInc = true;
}
if(cirInc) {
cirRadius++;
} else {
cirRadius--;
}
double cirX, cirY;
GL11.glColor3f(1,1,1);
for(int j=0; j<8; j++) {
double cTheta = cirTheta + (j*45);
if(cTheta > 360) {
cTheta = cTheta-360;
}
cirX = cirRadius * Math.sin(cTheta*(3.14159f/180));
cirY = cirRadius * Math.cos(cTheta*(3.14159f/180));
GL11.glBegin(GL11.GL_TRIANGLE_FAN);
GL11.glVertex2d(cirX,cirY);
for (int i=0; i<360*4; i++)
{
double x2 = cirX+Math.sin((double)(i/4)*(3.14159/180))*20;
double y2 = cirY+Math.cos((double)(i/4)*(3.14159/180))*20;
GL11.glVertex2d(x2,y2);
}
GL11.glEnd();
}
}
} else if(operation == 3) {
// Wait for user to start testing
GL11.glColor4d(0.0, 0.0, 0.0, 0.5);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(-300, 300);
GL11.glVertex2f( 300, 300);
GL11.glVertex2f( 300, -300);
GL11.glVertex2f(-300, -300);
GL11.glEnd();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(-20, 20); GL11.glTexCoord2d(0, 1);
GL11.glVertex2f( 20, 20); GL11.glTexCoord2d(1, 1);
GL11.glVertex2f( 20,-20); GL11.glTexCoord2d(1, 0);
GL11.glVertex2f(-20,-20); GL11.glTexCoord2d(0, 0);
GL11.glEnd();
if(Mouse.isButtonDown(0)) {
operation = 0;
startDate = new java.util.Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("hh:mm:ss.SSS");
sTime = sdf.format(startDate);
}
} else if(operation == 4) {
// Everything's finished. Shut up and sit quietly
}
if(xFlashClock > 0) {
xFlashClock--;
if(xFlashClock % 300 == 0) {
xFlash = !xFlash;
}
}
Display.update();
}
Display.destroy();
}
/** Function replayGame(int [] s_recActions, int s_length)
* Replays the set of actions from the array s_recActions to the point
* specified by int s_length.
*/
private void replayGame(int [] s_recActions, int s_length) {
switch(s_recActions[s_length]) {
case Constants.DIR_DOWN:
pY++;
break;
case Constants.DIR_UP:
pY--;
break;
case Constants.DIR_RIGHT:
pX++;
break;
case Constants.DIR_LEFT:
pX--;
break;
}
try {
Thread.sleep(100);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/** Function render()
* Draws all visible objects.
*/
private void render() {
int x, y; // Bottom left corner coordinates (for readability)
// Left box
x = -300;
y = -100;
setColor(pX-1, pY, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Right box
x = 100;
y = -100;
setColor(pX+1, pY, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Up box
x = -100;
y = 100;
setColor(pX, pY-1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Down box
x = -100;
y = -300;
setColor(pX, pY+1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
if(showDiagonal) {
// Top-Left box
x = -300;
y = 100;
setColor(pX-1, pY-1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Top-Right box
x = 100;
y = 100;
setColor(pX+1, pY-1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Bottom-Left box
x = -300;
y = -300;
setColor(pX-1, pY+1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Bottom-Right box
x = 100;
y = -300;
setColor(pX+1, pY+1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
}
// Center box
x = -100;
y = -100;
setColor(pX, pY, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Player
x = -50;
y = -50;
GL11.glColor3f(1,1,1);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+100,y +0);
GL11.glVertex2f(x+100,y+100);
GL11.glVertex2f(x +0,y+100);
GL11.glEnd();
if(xFlash) {
GL11.glColor3f(1, 0, 0);
GL11.glBegin(GL11.GL_POLYGON);
GL11.glVertex2f(x+ 80, y+100);
GL11.glVertex2f(x+100, y+100);
GL11.glVertex2f(x+100, y+ 80);
GL11.glVertex2f(x+ 20, y+ 0);
GL11.glVertex2f(x+ 0, y+ 0);
GL11.glVertex2f(x+ 0, y+ 20);
GL11.glEnd();
GL11.glBegin(GL11.GL_POLYGON);
GL11.glVertex2f(x+ 0, y+ 80);
GL11.glVertex2f(x+ 0, y+100);
GL11.glVertex2f(x+ 20, y+100);
GL11.glVertex2f(x+100, y+ 20);
GL11.glVertex2f(x+100, y+ 0);
GL11.glVertex2f(x+ 80, y+ 0);
GL11.glEnd();
}
}
/** Function setColor(int x, int y, int [][] tmap)
* Returns a fitting color based on what is on the given
* coordinates on the given map.
*/
private void setColor(int x, int y, int [][] tmap) {
if(x<0 || y<0 || x>Constants.MAP_WIDTH-1 || y>Constants.MAP_HEIGHT-1) {
GL11.glColor3f(1,0,0);
return;
}
switch(tmap[x][y]) {
case Constants.MAP_BLOCK:
GL11.glColor3f(1,0,0);
break;
case Constants.MAP_SPACE:
GL11.glColor3f(0,0,1);
break;
case Constants.MAP_WIN:
GL11.glColor3f(0,1,0);
break;
case Constants.MAP_START:
GL11.glColor3f(0,0,1);
break;
}
}
/** Function checkKeys()
* Reads for key input and acts accordingly. More specifically,
* the player is moved from arrow key presses.
*/
private void checkKeys() {
// Check for "Up" key
if(Keyboard.isKeyDown(Keyboard.KEY_UP) && keyRefresh[Constants.DIR_UP]) {
if(movePlayer(Constants.DIR_UP, pX, pY, map)) {
pY--;
recActions[currentAction] = Constants.DIR_UP;
currentAction++;
} else if(xFlashClock <= 0) {
xFlashClock = 1000;
}
keyRefresh[Constants.DIR_UP] = false;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_UP)) {
keyRefresh[Constants.DIR_UP] = true;
}
// Check for "Down" key
if(Keyboard.isKeyDown(Keyboard.KEY_DOWN) && keyRefresh[Constants.DIR_DOWN]) {
if(movePlayer(Constants.DIR_DOWN, pX, pY, map)) {
pY++;
recActions[currentAction] = Constants.DIR_DOWN;
currentAction++;
} else if(xFlashClock <= 0) {
xFlashClock = 1000;
}
keyRefresh[Constants.DIR_DOWN] = false;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
keyRefresh[Constants.DIR_DOWN] = true;
}
// Check for "Left" key
if(Keyboard.isKeyDown(Keyboard.KEY_LEFT) && keyRefresh[Constants.DIR_LEFT]) {
if(movePlayer(Constants.DIR_LEFT, pX, pY, map)) {
pX--;
recActions[currentAction] = Constants.DIR_LEFT;
currentAction++;
} else if(xFlashClock <= 0) {
xFlashClock = 1000;
}
keyRefresh[Constants.DIR_LEFT] = false;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {
keyRefresh[Constants.DIR_LEFT] = true;
}
// Check for "Right" key
if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT) && keyRefresh[Constants.DIR_RIGHT]) {
if(movePlayer(Constants.DIR_RIGHT, pX, pY, map)) {
pX++;
recActions[currentAction] = Constants.DIR_RIGHT;
currentAction++;
} else if(xFlashClock <= 0) {
xFlashClock = 1000;
}
keyRefresh[Constants.DIR_RIGHT] = false;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
keyRefresh[Constants.DIR_RIGHT] = true;
}
}
/** Function movePlayer(int dir, int x, int y, int [][] tmap)
* Checks move requests for validity. Returns true if no
* obstructions would keep the player from moving in that direction.
*/
private boolean movePlayer(int dir, int x, int y, int [][] tmap) {
switch(dir) {
case Constants.DIR_UP:
if(y>0) {
if(tmap[x][y-1] != Constants.MAP_BLOCK) {
return true;
} else {
return false;
}
} else {
return false;
}
// break;
case Constants.DIR_DOWN:
if(y<Constants.MAP_HEIGHT-1) {
if(tmap[x][y+1] != Constants.MAP_BLOCK) {
return true;
} else {
return false;
}
} else {
return false;
}
// break;
case Constants.DIR_LEFT:
if(x>0) {
if(tmap[x-1][y] != Constants.MAP_BLOCK) {
return true;
} else {
return false;
}
} else {
return false;
}
case Constants.DIR_RIGHT:
if(x<Constants.MAP_HEIGHT-1) {
if(tmap[x+1][y] != Constants.MAP_BLOCK) {
return true;
} else {
return false;
}
} else {
return false;
}
default:
System.out.printf("Error: Unexpected direction in movePlayer.\n");
}
return false;
}
/** Method InfoPackage packUp(java.util.Date sD, java.util.Date eD, int[] a)
* sD startDate
* eD endDate
* a=recActions*
*/
private InfoPackage packUp(String sTime, String eTime, int[] a) {
InfoPackage out = new InfoPackage();
out.setTimes(sTime, eTime);
out.setActions(a);
return out;
}
/** Function makeMaze()
* Initiates the maze.
*/
private int[][] makeMaze() {
int [][] out = new int [Constants.MAP_WIDTH][Constants.MAP_HEIGHT];
for(int x=0; x<Constants.MAP_WIDTH; x++) {
for(int y=0; y<Constants.MAP_HEIGHT; y++) {
out[x][y] = Constants.MAP_BLOCK;
}
}
return out;
}
}
| ColorMazeGame/src/MazeGame.java | /* MazeGame Class
* By Tyler Compton for Team Tyro
*
* This is a very simple and minimal map game. It's official name is
* "Color Maze Game."
*/
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import sql.InfoPackage;
import threads.SendData;
import etc.Constants;
import etc.ErrorReport;
import etc.MazeMap;
public class MazeGame extends Applet {
private static final long serialVersionUID = 1L;
private static int[][] map; // Universal map array
private static int [] recActions; // Stores all the keys pressed. [DIR_RIGHT,UP,DOWN,LEFT]
private static int currentAction; // Keeps track of which part of recActions your using. Basically just a counter for recActions
private static int rCurrentAction; // Replay current action, just for replaying
private static int operation; // The phase of the test. 0= moving around, playing game. 1= Replaying the game 2= Finished with testing, sending data.
private static java.util.Date startDate, endDate; // Actual day, time, milliseconds that you played the game.
private static String sTime, eTime, tTime;
private static boolean [] keyRefresh; //Makes sure that holding a button won't machine-gun it. [true=its up, and can be pressed. False=it's being pressed]
private static int pX, pY; // Player x and y (within the map array)
private static boolean xFlash;
private static int xFlashClock;
Canvas display_parent;
boolean running;
Thread gameThread, sendThread;
boolean showDiagonal = true;
/** Function startLWJGL()
* Executes LWJGL's startup methods.
*/
public void startLWJGL() {
gameThread = new Thread() {
public void run() {
running = true;
try {
Display.setParent(display_parent);
Display.create();
initGL();
} catch(LWJGLException ex) {
ErrorReport e = new ErrorReport(ex.getMessage());
e.makeFile();
return;
}
mainLoop();
}
};
gameThread.start();
}
/** Function stopLWJGL
* Stops the game thread.
*/
public void stopLWJGL() {
running = false;
try {
gameThread.join();
} catch(InterruptedException ex) {
ErrorReport e = new ErrorReport(ex.getMessage());
e.makeFile();
}
}
/** Function start()
* Placeholder for the expected start() method in applets.
*/
public void start() {
}
/** Function stop()
* Placeholder for the expected stop() method in applets.
*/
public void stop() {
}
/** Function destroy()
* Destroys the canvas.
*/
public void destroy() {
remove(display_parent);
super.destroy();
}
/** Function init()
* Initializes the canvas and global variables
*/
public void init() {
System.out.printf("TestGame V0.8.0\n");
setLayout(new BorderLayout());
try {
display_parent = new Canvas() {
private static final long serialVersionUID = 1L;
public final void addNotify() {
super.addNotify();
startLWJGL();
}
public final void removeNotify() {
stopLWJGL();
super.removeNotify();
}
};
display_parent.setSize(600,600);
add(display_parent);
display_parent.setFocusable(true);
display_parent.requestFocus();
display_parent.setIgnoreRepaint(true);
setVisible(true);
} catch(Exception ex) {
ErrorReport e = new ErrorReport(ex.getMessage());
e.makeFile();
throw new RuntimeException("Unable to create display!");
}
xFlashClock = 0;
map = makeMaze();
pX = Constants.MAP_WIDTH/2;
pY = 0;
keyRefresh = new boolean [6];
recActions = new int [500];
operation = 3;
currentAction = 0;
MazeMap maze = new MazeMap();
maze.loadConstMap("cbbbccccccccbbbbcccccbbbbbbcbbbbcbbbcbsbccbcbbbbcccbccc" +
"bccccbbbbcbcbbbcbbbcbbbbbcbcbbbcbcccbbbbbcccccccccbbbbbbbcbbbbbbb" +
"bbbcbbbbccccccccccbcbbbbbbbbbcbbbcccbbbbcccbbcccccccbbbbcbccccbcc" +
"cbcbbbbcbbbbbbcbcbcbbbbcbwcccbcbcbcbbbbcbbbbcbbbcbcbbbbcccccccccc" +
"ccbbbb");
for(int x=0; x<Constants.MAP_WIDTH; x++) {
for(int y=0; y<Constants.MAP_HEIGHT; y++) {
map[x][y] = maze.getSpace(x,y);
if(map[x][y] == Constants.MAP_START) {
pX = x;
pY = y;
}
}
}
}
/** Function initGL()
* Calls OpenGL initialization functions.
*/
protected void initGL() {
// Init OpenGL
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(-300, 300, -300, 300, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
/** Function begin()
* Sets up OpenGL and lwjgl and contains the main loop.
*/
private void mainLoop() {
// Start main loop
while(running) {
// Clears screen and depth buffer
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
// Rendering
render();
if(operation == 0) {
// Testing in progress
checkKeys();
if(map[pX][pY] == Constants.MAP_WIN) {
endDate = new java.util.Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("hh:mm:ss.SSS");
eTime = sdf.format(endDate);
SendData sender = new SendData(packUp(sTime, eTime, recActions));
sendThread = new Thread(sender);
sendThread.start();
operation = 2;
}
} else if(operation == 1) {
// Replay debug feature
if(rCurrentAction < currentAction) {
replayGame(recActions, rCurrentAction);
rCurrentAction++;
}
} else if(operation == 2) {
// Pending send
if(!sendThread.isAlive()) {
System.out.printf("Finished sending... Bringing to success page.\n");
try {
getAppletContext().showDocument(new URL(getCodeBase()+"thanks.php?time=" + tTime ),"_top");
} catch (MalformedURLException ex) {
System.out.println(ex.getMessage());
}
operation = 4;
}
} else if(operation == 3) {
// Wait for user to start testing
GL11.glColor4d(0.0, 0.0, 0.0, 0.5);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(-300, 300);
GL11.glVertex2f( 300, 300);
GL11.glVertex2f( 300, -300);
GL11.glVertex2f(-300, -300);
GL11.glEnd();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(-20, 20); GL11.glTexCoord2d(0, 1);
GL11.glVertex2f( 20, 20); GL11.glTexCoord2d(1, 1);
GL11.glVertex2f( 20,-20); GL11.glTexCoord2d(1, 0);
GL11.glVertex2f(-20,-20); GL11.glTexCoord2d(0, 0);
GL11.glEnd();
if(Mouse.isButtonDown(0)) {
operation = 0;
startDate = new java.util.Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("hh:mm:ss.SSS");
sTime = sdf.format(startDate);
}
} else if(operation == 4) {
// Everything's finished. Shut up and sit quietly
}
if(xFlashClock > 0) {
xFlashClock--;
if(xFlashClock % 300 == 0) {
xFlash = !xFlash;
}
}
Display.update();
}
Display.destroy();
}
/** Function replayGame(int [] s_recActions, int s_length)
* Replays the set of actions from the array s_recActions to the point
* specified by int s_length.
*/
private void replayGame(int [] s_recActions, int s_length) {
switch(s_recActions[s_length]) {
case Constants.DIR_DOWN:
pY++;
break;
case Constants.DIR_UP:
pY--;
break;
case Constants.DIR_RIGHT:
pX++;
break;
case Constants.DIR_LEFT:
pX--;
break;
}
try {
Thread.sleep(100);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/** Function render()
* Draws all visible objects.
*/
private void render() {
int x, y; // Bottom left corner coordinates (for readability)
// Left box
x = -300;
y = -100;
setColor(pX-1, pY, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Right box
x = 100;
y = -100;
setColor(pX+1, pY, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Up box
x = -100;
y = 100;
setColor(pX, pY-1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Down box
x = -100;
y = -300;
setColor(pX, pY+1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
if(showDiagonal) {
// Top-Left box
x = -300;
y = 100;
setColor(pX-1, pY-1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Top-Right box
x = 100;
y = 100;
setColor(pX+1, pY-1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Bottom-Left box
x = -300;
y = -300;
setColor(pX-1, pY+1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Bottom-Right box
x = 100;
y = -300;
setColor(pX+1, pY+1, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
}
// Center box
x = -100;
y = -100;
setColor(pX, pY, map);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+200,y +0);
GL11.glVertex2f(x+200,y+200);
GL11.glVertex2f(x +0,y+200);
GL11.glEnd();
// Player
x = -50;
y = -50;
GL11.glColor3f(1,1,1);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(x ,y );
GL11.glVertex2f(x+100,y +0);
GL11.glVertex2f(x+100,y+100);
GL11.glVertex2f(x +0,y+100);
GL11.glEnd();
if(xFlash) {
GL11.glColor3f(1, 0, 0);
GL11.glBegin(GL11.GL_POLYGON);
GL11.glVertex2f(x+ 80, y+100);
GL11.glVertex2f(x+100, y+100);
GL11.glVertex2f(x+100, y+ 80);
GL11.glVertex2f(x+ 20, y+ 0);
GL11.glVertex2f(x+ 0, y+ 0);
GL11.glVertex2f(x+ 0, y+ 20);
GL11.glEnd();
GL11.glBegin(GL11.GL_POLYGON);
GL11.glVertex2f(x+ 0, y+ 80);
GL11.glVertex2f(x+ 0, y+100);
GL11.glVertex2f(x+ 20, y+100);
GL11.glVertex2f(x+100, y+ 20);
GL11.glVertex2f(x+100, y+ 0);
GL11.glVertex2f(x+ 80, y+ 0);
GL11.glEnd();
}
}
/** Function setColor(int x, int y, int [][] tmap)
* Returns a fitting color based on what is on the given
* coordinates on the given map.
*/
private void setColor(int x, int y, int [][] tmap) {
if(x<0 || y<0 || x>Constants.MAP_WIDTH-1 || y>Constants.MAP_HEIGHT-1) {
GL11.glColor3f(1,0,0);
return;
}
switch(tmap[x][y]) {
case Constants.MAP_BLOCK:
GL11.glColor3f(1,0,0);
break;
case Constants.MAP_SPACE:
GL11.glColor3f(0,0,1);
break;
case Constants.MAP_WIN:
GL11.glColor3f(0,1,0);
break;
case Constants.MAP_START:
GL11.glColor3f(0,0,1);
break;
}
}
/** Function checkKeys()
* Reads for key input and acts accordingly. More specifically,
* the player is moved from arrow key presses.
*/
private void checkKeys() {
// Check for "Up" key
if(Keyboard.isKeyDown(Keyboard.KEY_UP) && keyRefresh[Constants.DIR_UP]) {
if(movePlayer(Constants.DIR_UP, pX, pY, map)) {
pY--;
recActions[currentAction] = Constants.DIR_UP;
currentAction++;
} else if(xFlashClock <= 0) {
xFlashClock = 1000;
}
keyRefresh[Constants.DIR_UP] = false;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_UP)) {
keyRefresh[Constants.DIR_UP] = true;
}
// Check for "Down" key
if(Keyboard.isKeyDown(Keyboard.KEY_DOWN) && keyRefresh[Constants.DIR_DOWN]) {
if(movePlayer(Constants.DIR_DOWN, pX, pY, map)) {
pY++;
recActions[currentAction] = Constants.DIR_DOWN;
currentAction++;
} else if(xFlashClock <= 0) {
xFlashClock = 1000;
}
keyRefresh[Constants.DIR_DOWN] = false;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
keyRefresh[Constants.DIR_DOWN] = true;
}
// Check for "Left" key
if(Keyboard.isKeyDown(Keyboard.KEY_LEFT) && keyRefresh[Constants.DIR_LEFT]) {
if(movePlayer(Constants.DIR_LEFT, pX, pY, map)) {
pX--;
recActions[currentAction] = Constants.DIR_LEFT;
currentAction++;
} else if(xFlashClock <= 0) {
xFlashClock = 1000;
}
keyRefresh[Constants.DIR_LEFT] = false;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {
keyRefresh[Constants.DIR_LEFT] = true;
}
// Check for "Right" key
if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT) && keyRefresh[Constants.DIR_RIGHT]) {
if(movePlayer(Constants.DIR_RIGHT, pX, pY, map)) {
pX++;
recActions[currentAction] = Constants.DIR_RIGHT;
currentAction++;
} else if(xFlashClock <= 0) {
xFlashClock = 1000;
}
keyRefresh[Constants.DIR_RIGHT] = false;
} else if(!Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
keyRefresh[Constants.DIR_RIGHT] = true;
}
}
/** Function movePlayer(int dir, int x, int y, int [][] tmap)
* Checks move requests for validity. Returns true if no
* obstructions would keep the player from moving in that direction.
*/
private boolean movePlayer(int dir, int x, int y, int [][] tmap) {
switch(dir) {
case Constants.DIR_UP:
if(y>0) {
if(tmap[x][y-1] != Constants.MAP_BLOCK) {
return true;
} else {
return false;
}
} else {
return false;
}
// break;
case Constants.DIR_DOWN:
if(y<Constants.MAP_HEIGHT-1) {
if(tmap[x][y+1] != Constants.MAP_BLOCK) {
return true;
} else {
return false;
}
} else {
return false;
}
// break;
case Constants.DIR_LEFT:
if(x>0) {
if(tmap[x-1][y] != Constants.MAP_BLOCK) {
return true;
} else {
return false;
}
} else {
return false;
}
case Constants.DIR_RIGHT:
if(x<Constants.MAP_HEIGHT-1) {
if(tmap[x+1][y] != Constants.MAP_BLOCK) {
return true;
} else {
return false;
}
} else {
return false;
}
default:
System.out.printf("Error: Unexpected direction in movePlayer.\n");
}
return false;
}
/** Method InfoPackage packUp(java.util.Date sD, java.util.Date eD, int[] a)
* sD startDate
* eD endDate
* a=recActions*
*/
private InfoPackage packUp(String sTime, String eTime, int[] a) {
InfoPackage out = new InfoPackage();
out.setTimes(sTime, eTime);
out.setActions(a);
return out;
}
/** Function makeMaze()
* Initiates the maze.
*/
private int[][] makeMaze() {
int [][] out = new int [Constants.MAP_WIDTH][Constants.MAP_HEIGHT];
for(int x=0; x<Constants.MAP_WIDTH; x++) {
for(int y=0; y<Constants.MAP_HEIGHT; y++) {
out[x][y] = Constants.MAP_BLOCK;
}
}
return out;
}
}
| Add loading orbs. | ColorMazeGame/src/MazeGame.java | Add loading orbs. | <ide><path>olorMazeGame/src/MazeGame.java
<ide> boolean running;
<ide> Thread gameThread, sendThread;
<ide>
<add> int cirTheta, cirRadius;
<add> boolean cirInc;
<add>
<ide> boolean showDiagonal = true;
<ide>
<ide> /** Function startLWJGL()
<ide> operation = 3;
<ide>
<ide> currentAction = 0;
<add>
<add> cirTheta = 0;
<add> cirRadius = 0;
<add> cirInc = true;
<ide>
<ide> MazeMap maze = new MazeMap();
<ide>
<ide> }
<ide>
<ide> operation = 4;
<add> } else {
<add> if(cirTheta >= 360) {
<add> cirTheta = 0;
<add> } else {
<add> cirTheta++;
<add> }
<add>
<add> if(cirRadius >= 300) {
<add> cirInc = false;
<add> } else if(cirRadius <= 0) {
<add> cirInc = true;
<add> }
<add> if(cirInc) {
<add> cirRadius++;
<add> } else {
<add> cirRadius--;
<add> }
<add> double cirX, cirY;
<add> GL11.glColor3f(1,1,1);
<add> for(int j=0; j<8; j++) {
<add> double cTheta = cirTheta + (j*45);
<add> if(cTheta > 360) {
<add> cTheta = cTheta-360;
<add> }
<add> cirX = cirRadius * Math.sin(cTheta*(3.14159f/180));
<add> cirY = cirRadius * Math.cos(cTheta*(3.14159f/180));
<add>
<add> GL11.glBegin(GL11.GL_TRIANGLE_FAN);
<add> GL11.glVertex2d(cirX,cirY);
<add>
<add> for (int i=0; i<360*4; i++)
<add> {
<add> double x2 = cirX+Math.sin((double)(i/4)*(3.14159/180))*20;
<add> double y2 = cirY+Math.cos((double)(i/4)*(3.14159/180))*20;
<add> GL11.glVertex2d(x2,y2);
<add> }
<add>
<add> GL11.glEnd();
<add> }
<ide> }
<ide> } else if(operation == 3) {
<ide> // Wait for user to start testing |
|
Java | agpl-3.0 | 7c50f94af5aedf4e4ae7be1fb53b1689a4a89b1d | 0 | duncte123/SkyBot,duncte123/SkyBot,duncte123/SkyBot,duncte123/SkyBot | /*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 - 2018 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32"
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot.audio;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason;
import lavalink.client.player.IPlayer;
import lavalink.client.player.event.AudioEventAdapterWrapped;
import ml.duncte123.skybot.commands.music.RadioCommand;
import ml.duncte123.skybot.objects.RadioStream;
import ml.duncte123.skybot.utils.AirUtils;
import ml.duncte123.skybot.utils.MessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class TrackScheduler extends AudioEventAdapterWrapped {
private static final Logger logger = LoggerFactory.getLogger(TrackScheduler.class);
public final Queue<AudioTrack> queue;
private final IPlayer player;
private final GuildMusicManager guildMusicManager;
private boolean repeating = false;
private boolean repeatPlayList = false;
/**
* This instantiates our player
*
* @param player Our audio player
*/
TrackScheduler(IPlayer player, GuildMusicManager guildMusicManager) {
this.player = player;
this.queue = new LinkedList<>();
this.guildMusicManager = guildMusicManager;
}
/**
* Queue a track
*
* @param track The {@link AudioTrack AudioTrack} to queue
*/
public void queue(AudioTrack track) {
if (player.getPlayingTrack() != null) {
queue.offer(track);
} else {
player.playTrack(track);
}
}
/**
* Starts the next track
*/
public void nextTrack() {
if (queue.peek() != null) {
AudioTrack nextTrack = queue.poll();
if (nextTrack != null) {
player.playTrack(nextTrack);
announceNextTrack(nextTrack);
}
} else if (player.getPlayingTrack() != null)
player.stopTrack();
}
/**
* Gets run when a track ends
*
* @param player The {@link AudioPlayer AudioTrack} for that guild
* @param track The {@link AudioTrack AudioTrack} that ended
* @param endReason Why did this track end?
*/
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
@SuppressWarnings("UnnecessaryLocalVariable") AudioTrack lastTrack = track;
logger.debug("track ended");
if (endReason.mayStartNext) {
logger.debug("can start");
if (repeating) {
logger.debug("repeating");
if (!repeatPlayList) {
this.player.playTrack(lastTrack.makeClone());
announceNextTrack(lastTrack, true);
} else {
logger.debug("a playlist.....");
nextTrack();
//Offer it to the queue to prevent the player from playing it
queue.offer(lastTrack.makeClone());
MessageUtils.sendMsg(guildMusicManager.latestChannel, "Repeating the playlist");
}
} else {
logger.debug("starting next track");
nextTrack();
}
}
}
@Override
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
MessageUtils.sendMsg(guildMusicManager.latestChannel, "Something went wrong while playing the track, please contact the devs if this happens a lot.\n" +
"Details: " + exception);
}
/**
* This will tell you if the player is repeating
*
* @return true if the player is set to repeat
*/
public boolean isRepeating() {
return repeating;
}
/**
* tell the player if needs to repeat
*
* @param repeating if the player needs to repeat
*/
public void setRepeating(boolean repeating) {
this.repeating = repeating;
}
/**
* This will tell you if the player is repeating playlists
*
* @return true if the player is set to repeat playlists
*/
public boolean isRepeatingPlaylists() {
return repeatPlayList;
}
/**
* tell the player if needs to repeat playlists
*
* @param repeatingPlaylists if the player needs to repeat playlists
*/
public void setRepeatingPlaylists(boolean repeatingPlaylists) {
this.repeatPlayList = repeatingPlaylists;
}
/**
* Shuffles the player
*/
public void shuffle() {
Collections.shuffle((List<?>) queue);
}
private void announceNextTrack(AudioTrack track) {
announceNextTrack(track, false);
}
private void announceNextTrack(AudioTrack track, boolean repeated) {
if (guildMusicManager.guildSettings.isAnnounceTracks()) {
String title = track.getInfo().title;
if (track.getInfo().isStream) {
Optional<RadioStream> stream = ((RadioCommand) AirUtils.COMMAND_MANAGER.getCommand("radio"))
.getRadioStreams().stream().filter(s -> s.getUrl().equals(track.getInfo().uri)).findFirst();
if (stream.isPresent())
title = stream.get().getName();
}
MessageUtils.sendMsg(guildMusicManager.latestChannel, "Now playing: " + title + (repeated ? " (repeated)" : ""));
}
}
}
| src/main/java/ml/duncte123/skybot/audio/TrackScheduler.java | /*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 - 2018 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32"
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot.audio;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason;
import lavalink.client.player.IPlayer;
import lavalink.client.player.event.AudioEventAdapterWrapped;
import ml.duncte123.skybot.commands.music.RadioCommand;
import ml.duncte123.skybot.objects.RadioStream;
import ml.duncte123.skybot.utils.AirUtils;
import ml.duncte123.skybot.utils.MessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class TrackScheduler extends AudioEventAdapterWrapped {
private static final Logger logger = LoggerFactory.getLogger(TrackScheduler.class);
public final Queue<AudioTrack> queue;
private final IPlayer player;
private final GuildMusicManager guildMusicManager;
private boolean repeating = false;
private boolean repeatPlayList = false;
/**
* This instantiates our player
*
* @param player Our audio player
*/
TrackScheduler(IPlayer player, GuildMusicManager guildMusicManager) {
this.player = player;
this.queue = new LinkedList<>();
this.guildMusicManager = guildMusicManager;
}
/**
* Queue a track
*
* @param track The {@link AudioTrack AudioTrack} to queue
*/
public void queue(AudioTrack track) {
if (player.getPlayingTrack() != null) {
queue.offer(track);
} else {
player.playTrack(track);
}
}
/**
* Starts the next track
*/
public void nextTrack() {
if (queue.peek() != null) {
AudioTrack nextTrack = queue.poll();
if (nextTrack != null) {
player.playTrack(nextTrack);
announceNextTrack(nextTrack);
}
} else if (player.getPlayingTrack() != null)
player.stopTrack();
}
/**
* Gets run when a track ends
*
* @param player The {@link AudioPlayer AudioTrack} for that guild
* @param track The {@link AudioTrack AudioTrack} that ended
* @param endReason Why did this track end?
*/
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
@SuppressWarnings("UnnecessaryLocalVariable") AudioTrack lastTrack = track;
logger.debug("track ended");
if (endReason.mayStartNext) {
logger.debug("can start");
if (repeating) {
logger.debug("repeating");
if (!repeatPlayList) {
this.player.playTrack(lastTrack.makeClone());
announceNextTrack(lastTrack, true);
} else {
logger.debug("a playlist.....");
nextTrack();
//Offer it to the queue to prevent the player from playing it
queue.offer(lastTrack.makeClone());
MessageUtils.sendMsg(guildMusicManager.latestChannel, "Repeating the playlist");
}
} else {
logger.debug("starting next track");
nextTrack();
}
}
}
/**
* This will tell you if the player is repeating
*
* @return true if the player is set to repeat
*/
public boolean isRepeating() {
return repeating;
}
/**
* tell the player if needs to repeat
*
* @param repeating if the player needs to repeat
*/
public void setRepeating(boolean repeating) {
this.repeating = repeating;
}
/**
* This will tell you if the player is repeating playlists
*
* @return true if the player is set to repeat playlists
*/
public boolean isRepeatingPlaylists() {
return repeatPlayList;
}
/**
* tell the player if needs to repeat playlists
*
* @param repeatingPlaylists if the player needs to repeat playlists
*/
public void setRepeatingPlaylists(boolean repeatingPlaylists) {
this.repeatPlayList = repeatingPlaylists;
}
/**
* Shuffles the player
*/
public void shuffle() {
Collections.shuffle((List<?>) queue);
}
private void announceNextTrack(AudioTrack track) {
announceNextTrack(track, false);
}
private void announceNextTrack(AudioTrack track, boolean repeated) {
if (guildMusicManager.guildSettings.isAnnounceTracks()) {
String title = track.getInfo().title;
if (track.getInfo().isStream) {
Optional<RadioStream> stream = ((RadioCommand) AirUtils.COMMAND_MANAGER.getCommand("radio"))
.getRadioStreams().stream().filter(s -> s.getUrl().equals(track.getInfo().uri)).findFirst();
if (stream.isPresent())
title = stream.get().getName();
}
MessageUtils.sendMsg(guildMusicManager.latestChannel, "Now playing: " + title + (repeated ? " (repeated)" : ""));
}
}
}
| Add listeer for stuck tracks
| src/main/java/ml/duncte123/skybot/audio/TrackScheduler.java | Add listeer for stuck tracks | <ide><path>rc/main/java/ml/duncte123/skybot/audio/TrackScheduler.java
<ide> package ml.duncte123.skybot.audio;
<ide>
<ide> import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
<add>import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
<ide> import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
<ide> import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason;
<ide> import lavalink.client.player.IPlayer;
<ide> }
<ide> }
<ide>
<add> @Override
<add> public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
<add> MessageUtils.sendMsg(guildMusicManager.latestChannel, "Something went wrong while playing the track, please contact the devs if this happens a lot.\n" +
<add> "Details: " + exception);
<add> }
<add>
<ide> /**
<ide> * This will tell you if the player is repeating
<ide> * |
|
Java | apache-2.0 | 82af47d4e150fe4ecfc5620da530a60b892a65af | 0 | dotta/async-http-client,Aulust/async-http-client,Aulust/async-http-client,bomgar/async-http-client | /*
* Copyright 2010-2013 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.asynchttpclient;
import static org.asynchttpclient.util.HttpUtils.*;
import static org.asynchttpclient.util.MiscUtils.isNonEmpty;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders;
import java.io.File;
import java.io.InputStream;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.asynchttpclient.channel.NameResolver;
import org.asynchttpclient.channel.pool.ConnectionPoolPartitioning;
import org.asynchttpclient.cookie.Cookie;
import org.asynchttpclient.proxy.ProxyServer;
import org.asynchttpclient.request.body.generator.BodyGenerator;
import org.asynchttpclient.request.body.generator.ReactiveStreamsBodyGenerator;
import org.asynchttpclient.request.body.multipart.Part;
import org.asynchttpclient.uri.Uri;
import org.asynchttpclient.util.UriEncoder;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Builder for {@link Request}
*
* @param <T> the builder type
*/
public abstract class RequestBuilderBase<T extends RequestBuilderBase<T>> {
private final static Logger LOGGER = LoggerFactory.getLogger(RequestBuilderBase.class);
private static final Uri DEFAULT_REQUEST_URL = Uri.create("http://localhost");
// builder only fields
protected UriEncoder uriEncoder;
protected List<Param> queryParams;
protected SignatureCalculator signatureCalculator;
// request fields
protected String method;
protected Uri uri;
protected InetAddress address;
protected InetAddress localAddress;
protected HttpHeaders headers = new DefaultHttpHeaders();
protected ArrayList<Cookie> cookies;
protected byte[] byteData;
protected List<byte[]> compositeByteData;
protected String stringData;
protected ByteBuffer byteBufferData;
protected InputStream streamData;
protected BodyGenerator bodyGenerator;
protected List<Param> formParams;
protected List<Part> bodyParts;
protected String virtualHost;
protected long contentLength = -1;
protected ProxyServer proxyServer;
protected Realm realm;
protected File file;
protected Boolean followRedirect;
protected int requestTimeout;
protected long rangeOffset;
protected Charset charset;
protected ConnectionPoolPartitioning connectionPoolPartitioning = ConnectionPoolPartitioning.PerHostConnectionPoolPartitioning.INSTANCE;
protected NameResolver nameResolver = NameResolver.JdkNameResolver.INSTANCE;
protected RequestBuilderBase(String method, boolean disableUrlEncoding) {
this.method = method;
this.uriEncoder = UriEncoder.uriEncoder(disableUrlEncoding);
}
protected RequestBuilderBase(Request prototype) {
this(prototype, false);
}
protected RequestBuilderBase(Request prototype, boolean disableUrlEncoding) {
this.method = prototype.getMethod();
this.uriEncoder = UriEncoder.uriEncoder(disableUrlEncoding);
this.uri = prototype.getUri();
this.address = prototype.getAddress();
this.localAddress = prototype.getLocalAddress();
this.headers.add(prototype.getHeaders());
if (isNonEmpty(prototype.getCookies())) {
this.cookies = new ArrayList<>(prototype.getCookies());
}
this.byteData = prototype.getByteData();
this.compositeByteData = prototype.getCompositeByteData();
this.stringData = prototype.getStringData();
this.byteBufferData = prototype.getByteBufferData();
this.streamData = prototype.getStreamData();
this.bodyGenerator = prototype.getBodyGenerator();
if (isNonEmpty(prototype.getFormParams())) {
this.formParams = new ArrayList<>(prototype.getFormParams());
}
if (isNonEmpty(prototype.getBodyParts())) {
this.bodyParts = new ArrayList<>(prototype.getBodyParts());
}
this.virtualHost = prototype.getVirtualHost();
this.contentLength = prototype.getContentLength();
this.proxyServer = prototype.getProxyServer();
this.realm = prototype.getRealm();
this.file = prototype.getFile();
this.followRedirect = prototype.getFollowRedirect();
this.requestTimeout = prototype.getRequestTimeout();
this.rangeOffset = prototype.getRangeOffset();
this.charset = prototype.getCharset();
this.connectionPoolPartitioning = prototype.getConnectionPoolPartitioning();
this.nameResolver = prototype.getNameResolver();
}
@SuppressWarnings("unchecked")
private T asDerivedType() {
return (T) this;
}
public T setUrl(String url) {
return setUri(Uri.create(url));
}
public T setUri(Uri uri) {
this.uri = uri;
return asDerivedType();
}
public T setAddress(InetAddress address) {
this.address = address;
return asDerivedType();
}
public T setLocalAddress(InetAddress address) {
this.localAddress = address;
return asDerivedType();
}
public T setVirtualHost(String virtualHost) {
this.virtualHost = virtualHost;
return asDerivedType();
}
public T setHeader(CharSequence name, String value) {
this.headers.set(name, value);
return asDerivedType();
}
public T addHeader(CharSequence name, String value) {
if (value == null) {
LOGGER.warn("Value was null, set to \"\"");
value = "";
}
this.headers.add(name, value);
return asDerivedType();
}
public T setHeaders(HttpHeaders headers) {
this.headers = headers == null ? new DefaultHttpHeaders() : headers;
return asDerivedType();
}
public T setHeaders(Map<String, Collection<String>> headers) {
this.headers = new DefaultHttpHeaders();
if (headers != null) {
for (Map.Entry<String, Collection<String>> entry : headers.entrySet()) {
String headerName = entry.getKey();
this.headers.add(headerName, entry.getValue());
}
}
return asDerivedType();
}
public T setContentLength(int contentLength) {
this.contentLength = contentLength;
return asDerivedType();
}
private void lazyInitCookies() {
if (this.cookies == null)
this.cookies = new ArrayList<>(3);
}
public T setCookies(Collection<Cookie> cookies) {
this.cookies = new ArrayList<>(cookies);
return asDerivedType();
}
public T addCookie(Cookie cookie) {
lazyInitCookies();
this.cookies.add(cookie);
return asDerivedType();
}
public T addOrReplaceCookie(Cookie cookie) {
String cookieKey = cookie.getName();
boolean replace = false;
int index = 0;
lazyInitCookies();
for (Cookie c : this.cookies) {
if (c.getName().equals(cookieKey)) {
replace = true;
break;
}
index++;
}
if (replace)
this.cookies.set(index, cookie);
else
this.cookies.add(cookie);
return asDerivedType();
}
public void resetCookies() {
if (this.cookies != null)
this.cookies.clear();
}
public void resetQuery() {
queryParams = null;
this.uri = this.uri.withNewQuery(null);
}
public void resetFormParams() {
this.formParams = null;
}
public void resetNonMultipartData() {
this.byteData = null;
this.compositeByteData = null;
this.byteBufferData = null;
this.stringData = null;
this.streamData = null;
this.bodyGenerator = null;
this.contentLength = -1;
}
public void resetMultipartData() {
this.bodyParts = null;
}
public T setBody(File file) {
this.file = file;
return asDerivedType();
}
private void resetBody() {
resetFormParams();
resetNonMultipartData();
resetMultipartData();
}
public T setBody(byte[] data) {
resetBody();
this.byteData = data;
return asDerivedType();
}
public T setBody(List<byte[]> data) {
resetBody();
this.compositeByteData = data;
return asDerivedType();
}
public T setBody(String data) {
resetBody();
this.stringData = data;
return asDerivedType();
}
public T setBody(ByteBuffer data) {
resetBody();
this.byteBufferData = data;
return asDerivedType();
}
public T setBody(InputStream stream) {
resetBody();
this.streamData = stream;
return asDerivedType();
}
public T setBody(Publisher<ByteBuffer> publisher) {
return setBody(new ReactiveStreamsBodyGenerator(publisher));
}
public T setBody(BodyGenerator bodyGenerator) {
this.bodyGenerator = bodyGenerator;
return asDerivedType();
}
public T addQueryParam(String name, String value) {
if (queryParams == null)
queryParams = new ArrayList<>(1);
queryParams.add(new Param(name, value));
return asDerivedType();
}
public T addQueryParams(List<Param> params) {
if (queryParams == null)
queryParams = params;
else
queryParams.addAll(params);
return asDerivedType();
}
public T setQueryParams(Map<String, List<String>> map) {
return setQueryParams(Param.map2ParamList(map));
}
public T setQueryParams(List<Param> params) {
// reset existing query
if (isNonEmpty(this.uri.getQuery()))
this.uri = this.uri.withNewQuery(null);
queryParams = params;
return asDerivedType();
}
public T addFormParam(String name, String value) {
resetNonMultipartData();
resetMultipartData();
if (this.formParams == null)
this.formParams = new ArrayList<>(1);
this.formParams.add(new Param(name, value));
return asDerivedType();
}
public T setFormParams(Map<String, List<String>> map) {
return setFormParams(Param.map2ParamList(map));
}
public T setFormParams(List<Param> params) {
resetNonMultipartData();
resetMultipartData();
this.formParams = params;
return asDerivedType();
}
public T addBodyPart(Part bodyPart) {
resetFormParams();
resetNonMultipartData();
if (this.bodyParts == null)
this.bodyParts = new ArrayList<>();
this.bodyParts.add(bodyPart);
return asDerivedType();
}
public T setBodyParts(List<Part> bodyParts) {
this.bodyParts = new ArrayList<>(bodyParts);
return asDerivedType();
}
public T setProxyServer(ProxyServer proxyServer) {
this.proxyServer = proxyServer;
return asDerivedType();
}
public T setProxyServer(ProxyServer.Builder proxyServerBuilder) {
this.proxyServer = proxyServerBuilder.build();
return asDerivedType();
}
public T setRealm(Realm realm) {
this.realm = realm;
return asDerivedType();
}
public T setFollowRedirect(boolean followRedirect) {
this.followRedirect = followRedirect;
return asDerivedType();
}
public T setRequestTimeout(int requestTimeout) {
this.requestTimeout = requestTimeout;
return asDerivedType();
}
public T setRangeOffset(long rangeOffset) {
this.rangeOffset = rangeOffset;
return asDerivedType();
}
public T setMethod(String method) {
this.method = method;
return asDerivedType();
}
public T setCharset(Charset charset) {
this.charset = charset;
return asDerivedType();
}
public T setConnectionPoolPartitioning(ConnectionPoolPartitioning connectionPoolPartitioning) {
this.connectionPoolPartitioning = connectionPoolPartitioning;
return asDerivedType();
}
public T setNameResolver(NameResolver nameResolver) {
this.nameResolver = nameResolver;
return asDerivedType();
}
public T setSignatureCalculator(SignatureCalculator signatureCalculator) {
this.signatureCalculator = signatureCalculator;
return asDerivedType();
}
private RequestBuilderBase<?> executeSignatureCalculator() {
if (signatureCalculator == null)
return this;
// build a first version of the request, without signatureCalculator in play
RequestBuilder rb = new RequestBuilder(this.method);
// make copy of mutable collections so we don't risk affecting
// original RequestBuilder
// call setFormParams first as it resets other fields
if (this.formParams != null)
rb.setFormParams(this.formParams);
if (this.headers != null)
rb.headers.add(this.headers);
if (this.cookies != null)
rb.setCookies(this.cookies);
if (this.bodyParts != null)
rb.setBodyParts(this.bodyParts);
// copy all other fields
// but rb.signatureCalculator, that's the whole point here
rb.uriEncoder = this.uriEncoder;
rb.queryParams = this.queryParams;
rb.uri = this.uri;
rb.address = this.address;
rb.localAddress = this.localAddress;
rb.byteData = this.byteData;
rb.compositeByteData = this.compositeByteData;
rb.stringData = this.stringData;
rb.byteBufferData = this.byteBufferData;
rb.streamData = this.streamData;
rb.bodyGenerator = this.bodyGenerator;
rb.virtualHost = this.virtualHost;
rb.contentLength = this.contentLength;
rb.proxyServer = this.proxyServer;
rb.realm = this.realm;
rb.file = this.file;
rb.followRedirect = this.followRedirect;
rb.requestTimeout = this.requestTimeout;
rb.rangeOffset = this.rangeOffset;
rb.charset = this.charset;
rb.connectionPoolPartitioning = this.connectionPoolPartitioning;
rb.nameResolver = this.nameResolver;
Request unsignedRequest = rb.build();
signatureCalculator.calculateAndAddSignature(unsignedRequest, rb);
return rb;
}
private Charset computeCharset() {
if (this.charset == null) {
try {
final String contentType = this.headers.get(HttpHeaders.Names.CONTENT_TYPE);
if (contentType != null) {
final Charset charset = parseCharset(contentType);
if (charset != null) {
// ensure that if charset is provided with the
// Content-Type header,
// we propagate that down to the charset of the Request
// object
return charset;
}
}
} catch (Throwable e) {
// NoOp -- we can't fix the Content-Type or charset from here
}
}
return this.charset;
}
private long computeRequestContentLength() {
if (this.contentLength < 0 && this.streamData == null) {
// can't concatenate content-length
final String contentLength = this.headers.get(HttpHeaders.Names.CONTENT_LENGTH);
if (contentLength != null) {
try {
return Long.parseLong(contentLength);
} catch (NumberFormatException e) {
// NoOp -- we won't specify length so it will be chunked?
}
}
}
return this.contentLength;
}
private Uri computeUri() {
Uri tempUri = this.uri;
if (tempUri == null) {
LOGGER.debug("setUrl hasn't been invoked. Using {}", DEFAULT_REQUEST_URL);
tempUri = DEFAULT_REQUEST_URL;
} else {
validateSupportedScheme(tempUri);
}
return uriEncoder.encode(tempUri, queryParams);
}
public Request build() {
RequestBuilderBase<?> rb = executeSignatureCalculator();
Uri finalUri = rb.computeUri();
Charset finalCharset = rb.computeCharset();
long finalContentLength = rb.computeRequestContentLength();
// make copies of mutable internal collections
List<Cookie> cookiesCopy = rb.cookies == null ? Collections.emptyList() : new ArrayList<>(rb.cookies);
List<Param> formParamsCopy = rb.formParams == null ? Collections.emptyList() : new ArrayList<>(rb.formParams);
List<Part> bodyPartsCopy = rb.bodyParts == null ? Collections.emptyList() : new ArrayList<>(rb.bodyParts);
return new DefaultRequest(rb.method,//
finalUri,//
rb.address,//
rb.localAddress,//
rb.headers,//
cookiesCopy,//
rb.byteData,//
rb.compositeByteData,//
rb.stringData,//
rb.byteBufferData,//
rb.streamData,//
rb.bodyGenerator,//
formParamsCopy,//
bodyPartsCopy,//
rb.virtualHost,//
finalContentLength,//
rb.proxyServer,//
rb.realm,//
rb.file,//
rb.followRedirect,//
rb.requestTimeout,//
rb.rangeOffset,//
finalCharset,//
rb.connectionPoolPartitioning,//
rb.nameResolver);
}
}
| client/src/main/java/org/asynchttpclient/RequestBuilderBase.java | /*
* Copyright 2010-2013 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.asynchttpclient;
import static org.asynchttpclient.util.HttpUtils.*;
import static org.asynchttpclient.util.MiscUtils.isNonEmpty;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders;
import java.io.File;
import java.io.InputStream;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.asynchttpclient.channel.NameResolver;
import org.asynchttpclient.channel.pool.ConnectionPoolPartitioning;
import org.asynchttpclient.cookie.Cookie;
import org.asynchttpclient.proxy.ProxyServer;
import org.asynchttpclient.request.body.generator.BodyGenerator;
import org.asynchttpclient.request.body.generator.ReactiveStreamsBodyGenerator;
import org.asynchttpclient.request.body.multipart.Part;
import org.asynchttpclient.uri.Uri;
import org.asynchttpclient.util.UriEncoder;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Builder for {@link Request}
*
* @param <T> the builder type
*/
public abstract class RequestBuilderBase<T extends RequestBuilderBase<T>> {
private final static Logger LOGGER = LoggerFactory.getLogger(RequestBuilderBase.class);
private static final Uri DEFAULT_REQUEST_URL = Uri.create("http://localhost");
// builder only fields
protected UriEncoder uriEncoder;
protected List<Param> queryParams;
protected SignatureCalculator signatureCalculator;
// request fields
protected String method;
protected Uri uri;
protected InetAddress address;
protected InetAddress localAddress;
protected HttpHeaders headers = new DefaultHttpHeaders();
protected ArrayList<Cookie> cookies;
protected byte[] byteData;
protected List<byte[]> compositeByteData;
protected String stringData;
protected ByteBuffer byteBufferData;
protected InputStream streamData;
protected BodyGenerator bodyGenerator;
protected List<Param> formParams;
protected List<Part> bodyParts;
protected String virtualHost;
protected long contentLength = -1;
protected ProxyServer proxyServer;
protected Realm realm;
protected File file;
protected Boolean followRedirect;
protected int requestTimeout;
protected long rangeOffset;
protected Charset charset;
protected ConnectionPoolPartitioning connectionPoolPartitioning = ConnectionPoolPartitioning.PerHostConnectionPoolPartitioning.INSTANCE;
protected NameResolver nameResolver = NameResolver.JdkNameResolver.INSTANCE;
protected RequestBuilderBase(String method, boolean disableUrlEncoding) {
this.method = method;
this.uriEncoder = UriEncoder.uriEncoder(disableUrlEncoding);
}
protected RequestBuilderBase(Request prototype) {
this(prototype, false);
}
protected RequestBuilderBase(Request prototype, boolean disableUrlEncoding) {
this.method = prototype.getMethod();
this.uriEncoder = UriEncoder.uriEncoder(disableUrlEncoding);
this.uri = prototype.getUri();
this.address = prototype.getAddress();
this.localAddress = prototype.getLocalAddress();
this.headers.add(prototype.getHeaders());
this.cookies = new ArrayList<Cookie>(prototype.getCookies());
this.byteData = prototype.getByteData();
this.compositeByteData = prototype.getCompositeByteData();
this.stringData = prototype.getStringData();
this.byteBufferData = prototype.getByteBufferData();
this.streamData = prototype.getStreamData();
this.bodyGenerator = prototype.getBodyGenerator();
this.formParams = prototype.getFormParams();
this.bodyParts = prototype.getBodyParts();
this.virtualHost = prototype.getVirtualHost();
this.contentLength = prototype.getContentLength();
this.proxyServer = prototype.getProxyServer();
this.realm = prototype.getRealm();
this.file = prototype.getFile();
this.followRedirect = prototype.getFollowRedirect();
this.requestTimeout = prototype.getRequestTimeout();
this.rangeOffset = prototype.getRangeOffset();
this.charset = prototype.getCharset();
this.connectionPoolPartitioning = prototype.getConnectionPoolPartitioning();
this.nameResolver = prototype.getNameResolver();
}
@SuppressWarnings("unchecked")
private T asDerivedType() {
return (T) this;
}
public T setUrl(String url) {
return setUri(Uri.create(url));
}
public T setUri(Uri uri) {
this.uri = uri;
return asDerivedType();
}
public T setAddress(InetAddress address) {
this.address = address;
return asDerivedType();
}
public T setLocalAddress(InetAddress address) {
this.localAddress = address;
return asDerivedType();
}
public T setVirtualHost(String virtualHost) {
this.virtualHost = virtualHost;
return asDerivedType();
}
public T setHeader(CharSequence name, String value) {
this.headers.set(name, value);
return asDerivedType();
}
public T addHeader(CharSequence name, String value) {
if (value == null) {
LOGGER.warn("Value was null, set to \"\"");
value = "";
}
this.headers.add(name, value);
return asDerivedType();
}
public T setHeaders(HttpHeaders headers) {
this.headers = headers == null ? new DefaultHttpHeaders() : headers;
return asDerivedType();
}
public T setHeaders(Map<String, Collection<String>> headers) {
this.headers = new DefaultHttpHeaders();
if (headers != null) {
for (Map.Entry<String, Collection<String>> entry : headers.entrySet()) {
String headerName = entry.getKey();
this.headers.add(headerName, entry.getValue());
}
}
return asDerivedType();
}
public T setContentLength(int contentLength) {
this.contentLength = contentLength;
return asDerivedType();
}
private void lazyInitCookies() {
if (this.cookies == null)
this.cookies = new ArrayList<>(3);
}
public T setCookies(Collection<Cookie> cookies) {
this.cookies = new ArrayList<>(cookies);
return asDerivedType();
}
public T addCookie(Cookie cookie) {
lazyInitCookies();
this.cookies.add(cookie);
return asDerivedType();
}
public T addOrReplaceCookie(Cookie cookie) {
String cookieKey = cookie.getName();
boolean replace = false;
int index = 0;
lazyInitCookies();
for (Cookie c : this.cookies) {
if (c.getName().equals(cookieKey)) {
replace = true;
break;
}
index++;
}
if (replace)
this.cookies.set(index, cookie);
else
this.cookies.add(cookie);
return asDerivedType();
}
public void resetCookies() {
if (this.cookies != null)
this.cookies.clear();
}
public void resetQuery() {
queryParams = null;
this.uri = this.uri.withNewQuery(null);
}
public void resetFormParams() {
this.formParams = null;
}
public void resetNonMultipartData() {
this.byteData = null;
this.compositeByteData = null;
this.byteBufferData = null;
this.stringData = null;
this.streamData = null;
this.bodyGenerator = null;
this.contentLength = -1;
}
public void resetMultipartData() {
this.bodyParts = null;
}
public T setBody(File file) {
this.file = file;
return asDerivedType();
}
private void resetBody() {
resetFormParams();
resetNonMultipartData();
resetMultipartData();
}
public T setBody(byte[] data) {
resetBody();
this.byteData = data;
return asDerivedType();
}
public T setBody(List<byte[]> data) {
resetBody();
this.compositeByteData = data;
return asDerivedType();
}
public T setBody(String data) {
resetBody();
this.stringData = data;
return asDerivedType();
}
public T setBody(ByteBuffer data) {
resetBody();
this.byteBufferData = data;
return asDerivedType();
}
public T setBody(InputStream stream) {
resetBody();
this.streamData = stream;
return asDerivedType();
}
public T setBody(Publisher<ByteBuffer> publisher) {
return setBody(new ReactiveStreamsBodyGenerator(publisher));
}
public T setBody(BodyGenerator bodyGenerator) {
this.bodyGenerator = bodyGenerator;
return asDerivedType();
}
public T addQueryParam(String name, String value) {
if (queryParams == null)
queryParams = new ArrayList<>(1);
queryParams.add(new Param(name, value));
return asDerivedType();
}
public T addQueryParams(List<Param> params) {
if (queryParams == null)
queryParams = params;
else
queryParams.addAll(params);
return asDerivedType();
}
public T setQueryParams(Map<String, List<String>> map) {
return setQueryParams(Param.map2ParamList(map));
}
public T setQueryParams(List<Param> params) {
// reset existing query
if (isNonEmpty(this.uri.getQuery()))
this.uri = this.uri.withNewQuery(null);
queryParams = params;
return asDerivedType();
}
public T addFormParam(String name, String value) {
resetNonMultipartData();
resetMultipartData();
if (this.formParams == null)
this.formParams = new ArrayList<>(1);
this.formParams.add(new Param(name, value));
return asDerivedType();
}
public T setFormParams(Map<String, List<String>> map) {
return setFormParams(Param.map2ParamList(map));
}
public T setFormParams(List<Param> params) {
resetNonMultipartData();
resetMultipartData();
this.formParams = params;
return asDerivedType();
}
public T addBodyPart(Part bodyPart) {
resetFormParams();
resetNonMultipartData();
if (this.bodyParts == null)
this.bodyParts = new ArrayList<>();
this.bodyParts.add(bodyPart);
return asDerivedType();
}
public T setBodyParts(List<Part> bodyParts) {
this.bodyParts = new ArrayList<>(bodyParts);
return asDerivedType();
}
public T setProxyServer(ProxyServer proxyServer) {
this.proxyServer = proxyServer;
return asDerivedType();
}
public T setProxyServer(ProxyServer.Builder proxyServerBuilder) {
this.proxyServer = proxyServerBuilder.build();
return asDerivedType();
}
public T setRealm(Realm realm) {
this.realm = realm;
return asDerivedType();
}
public T setFollowRedirect(boolean followRedirect) {
this.followRedirect = followRedirect;
return asDerivedType();
}
public T setRequestTimeout(int requestTimeout) {
this.requestTimeout = requestTimeout;
return asDerivedType();
}
public T setRangeOffset(long rangeOffset) {
this.rangeOffset = rangeOffset;
return asDerivedType();
}
public T setMethod(String method) {
this.method = method;
return asDerivedType();
}
public T setCharset(Charset charset) {
this.charset = charset;
return asDerivedType();
}
public T setConnectionPoolPartitioning(ConnectionPoolPartitioning connectionPoolPartitioning) {
this.connectionPoolPartitioning = connectionPoolPartitioning;
return asDerivedType();
}
public T setNameResolver(NameResolver nameResolver) {
this.nameResolver = nameResolver;
return asDerivedType();
}
public T setSignatureCalculator(SignatureCalculator signatureCalculator) {
this.signatureCalculator = signatureCalculator;
return asDerivedType();
}
private RequestBuilderBase<?> executeSignatureCalculator() {
if (signatureCalculator == null)
return this;
// build a first version of the request, without signatureCalculator in play
RequestBuilder rb = new RequestBuilder(this.method);
// make copy of mutable collections so we don't risk affecting
// original RequestBuilder
// call setFormParams first as it resets other fields
if (this.formParams != null)
rb.setFormParams(this.formParams);
if (this.headers != null)
rb.headers.add(this.headers);
if (this.cookies != null)
rb.setCookies(this.cookies);
if (this.bodyParts != null)
rb.setBodyParts(this.bodyParts);
// copy all other fields
// but rb.signatureCalculator, that's the whole point here
rb.uriEncoder = this.uriEncoder;
rb.queryParams = this.queryParams;
rb.uri = this.uri;
rb.address = this.address;
rb.localAddress = this.localAddress;
rb.byteData = this.byteData;
rb.compositeByteData = this.compositeByteData;
rb.stringData = this.stringData;
rb.byteBufferData = this.byteBufferData;
rb.streamData = this.streamData;
rb.bodyGenerator = this.bodyGenerator;
rb.virtualHost = this.virtualHost;
rb.contentLength = this.contentLength;
rb.proxyServer = this.proxyServer;
rb.realm = this.realm;
rb.file = this.file;
rb.followRedirect = this.followRedirect;
rb.requestTimeout = this.requestTimeout;
rb.rangeOffset = this.rangeOffset;
rb.charset = this.charset;
rb.connectionPoolPartitioning = this.connectionPoolPartitioning;
rb.nameResolver = this.nameResolver;
Request unsignedRequest = rb.build();
signatureCalculator.calculateAndAddSignature(unsignedRequest, rb);
return rb;
}
private Charset computeCharset() {
if (this.charset == null) {
try {
final String contentType = this.headers.get(HttpHeaders.Names.CONTENT_TYPE);
if (contentType != null) {
final Charset charset = parseCharset(contentType);
if (charset != null) {
// ensure that if charset is provided with the
// Content-Type header,
// we propagate that down to the charset of the Request
// object
return charset;
}
}
} catch (Throwable e) {
// NoOp -- we can't fix the Content-Type or charset from here
}
}
return this.charset;
}
private long computeRequestContentLength() {
if (this.contentLength < 0 && this.streamData == null) {
// can't concatenate content-length
final String contentLength = this.headers.get(HttpHeaders.Names.CONTENT_LENGTH);
if (contentLength != null) {
try {
return Long.parseLong(contentLength);
} catch (NumberFormatException e) {
// NoOp -- we won't specify length so it will be chunked?
}
}
}
return this.contentLength;
}
private Uri computeUri() {
Uri tempUri = this.uri;
if (tempUri == null) {
LOGGER.debug("setUrl hasn't been invoked. Using {}", DEFAULT_REQUEST_URL);
tempUri = DEFAULT_REQUEST_URL;
} else {
validateSupportedScheme(tempUri);
}
return uriEncoder.encode(tempUri, queryParams);
}
public Request build() {
RequestBuilderBase<?> rb = executeSignatureCalculator();
Uri finalUri = rb.computeUri();
Charset finalCharset = rb.computeCharset();
long finalContentLength = rb.computeRequestContentLength();
// make copies of mutable internal collections
List<Cookie> cookiesCopy = rb.cookies == null ? Collections.emptyList() : new ArrayList<>(rb.cookies);
List<Param> formParamsCopy = rb.formParams == null ? Collections.emptyList() : new ArrayList<>(rb.formParams);
List<Part> bodyPartsCopy = rb.bodyParts == null ? Collections.emptyList() : new ArrayList<>(rb.bodyParts);
return new DefaultRequest(rb.method,//
finalUri,//
rb.address,//
rb.localAddress,//
rb.headers,//
cookiesCopy,//
rb.byteData,//
rb.compositeByteData,//
rb.stringData,//
rb.byteBufferData,//
rb.streamData,//
rb.bodyGenerator,//
formParamsCopy,//
bodyPartsCopy,//
rb.virtualHost,//
finalContentLength,//
rb.proxyServer,//
rb.realm,//
rb.file,//
rb.followRedirect,//
rb.requestTimeout,//
rb.rangeOffset,//
finalCharset,//
rb.connectionPoolPartitioning,//
rb.nameResolver);
}
}
| Fix RequestBuilderBase when building from prototype
| client/src/main/java/org/asynchttpclient/RequestBuilderBase.java | Fix RequestBuilderBase when building from prototype | <ide><path>lient/src/main/java/org/asynchttpclient/RequestBuilderBase.java
<ide> this.address = prototype.getAddress();
<ide> this.localAddress = prototype.getLocalAddress();
<ide> this.headers.add(prototype.getHeaders());
<del> this.cookies = new ArrayList<Cookie>(prototype.getCookies());
<add> if (isNonEmpty(prototype.getCookies())) {
<add> this.cookies = new ArrayList<>(prototype.getCookies());
<add> }
<ide> this.byteData = prototype.getByteData();
<ide> this.compositeByteData = prototype.getCompositeByteData();
<ide> this.stringData = prototype.getStringData();
<ide> this.byteBufferData = prototype.getByteBufferData();
<ide> this.streamData = prototype.getStreamData();
<ide> this.bodyGenerator = prototype.getBodyGenerator();
<del> this.formParams = prototype.getFormParams();
<del> this.bodyParts = prototype.getBodyParts();
<add> if (isNonEmpty(prototype.getFormParams())) {
<add> this.formParams = new ArrayList<>(prototype.getFormParams());
<add> }
<add> if (isNonEmpty(prototype.getBodyParts())) {
<add> this.bodyParts = new ArrayList<>(prototype.getBodyParts());
<add> }
<ide> this.virtualHost = prototype.getVirtualHost();
<ide> this.contentLength = prototype.getContentLength();
<ide> this.proxyServer = prototype.getProxyServer(); |
|
Java | apache-2.0 | 37ab584277f18913b2367bf5b0594cf7606609e2 | 0 | izonder/intellij-community,allotria/intellij-community,allotria/intellij-community,caot/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,ibinti/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,caot/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,kool79/intellij-community,apixandru/intellij-community,robovm/robovm-studio,diorcety/intellij-community,xfournet/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,caot/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,youdonghai/intellij-community,holmes/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,clumsy/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,amith01994/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,xfournet/intellij-community,fitermay/intellij-community,izonder/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,supersven/intellij-community,blademainer/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,caot/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,signed/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,asedunov/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,supersven/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,da1z/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,retomerz/intellij-community,fitermay/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,petteyg/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,semonte/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,petteyg/intellij-community,slisson/intellij-community,slisson/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,izonder/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,holmes/intellij-community,diorcety/intellij-community,kool79/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,ryano144/intellij-community,ryano144/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,retomerz/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,samthor/intellij-community,clumsy/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,FHannes/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,allotria/intellij-community,blademainer/intellij-community,jagguli/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,izonder/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,allotria/intellij-community,slisson/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,lucafavatella/intellij-community,signed/intellij-community,caot/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,clumsy/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,adedayo/intellij-community,allotria/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,kool79/intellij-community,youdonghai/intellij-community,semonte/intellij-community,jagguli/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,slisson/intellij-community,signed/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,ibinti/intellij-community,supersven/intellij-community,vladmm/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,da1z/intellij-community,fitermay/intellij-community,kool79/intellij-community,supersven/intellij-community,samthor/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,semonte/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,supersven/intellij-community,apixandru/intellij-community,kool79/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,caot/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,asedunov/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,semonte/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,samthor/intellij-community,kdwink/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,signed/intellij-community,signed/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,caot/intellij-community,petteyg/intellij-community,adedayo/intellij-community,dslomov/intellij-community,hurricup/intellij-community,samthor/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,samthor/intellij-community,caot/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,ibinti/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,signed/intellij-community,clumsy/intellij-community,retomerz/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,allotria/intellij-community,signed/intellij-community,salguarnieri/intellij-community,signed/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,slisson/intellij-community,fitermay/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,holmes/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,petteyg/intellij-community,apixandru/intellij-community,supersven/intellij-community,allotria/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,caot/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,allotria/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,FHannes/intellij-community,vladmm/intellij-community,kool79/intellij-community,wreckJ/intellij-community,allotria/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,fnouama/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,caot/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,semonte/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,izonder/intellij-community,FHannes/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ryano144/intellij-community,dslomov/intellij-community,holmes/intellij-community,semonte/intellij-community,izonder/intellij-community,asedunov/intellij-community,clumsy/intellij-community,kdwink/intellij-community,da1z/intellij-community,gnuhub/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,da1z/intellij-community,apixandru/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,kool79/intellij-community,holmes/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,kool79/intellij-community,holmes/intellij-community,amith01994/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ahb0327/intellij-community,caot/intellij-community,slisson/intellij-community,kool79/intellij-community,apixandru/intellij-community,robovm/robovm-studio,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,izonder/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,signed/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,izonder/intellij-community,dslomov/intellij-community,ibinti/intellij-community,holmes/intellij-community,dslomov/intellij-community,da1z/intellij-community,vladmm/intellij-community,adedayo/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,dslomov/intellij-community,kdwink/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,supersven/intellij-community,youdonghai/intellij-community,samthor/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,samthor/intellij-community,Lekanich/intellij-community,signed/intellij-community,retomerz/intellij-community,ibinti/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,xfournet/intellij-community,fitermay/intellij-community,supersven/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,allotria/intellij-community,ahb0327/intellij-community,semonte/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,dslomov/intellij-community,vladmm/intellij-community,gnuhub/intellij-community | python/testSrc/com/jetbrains/python/PyPackagingTest.java | package com.jetbrains.python;
import com.intellij.openapi.diagnostic.Logger;
import com.jetbrains.python.env.debug.PyEnvTestCase;
import com.jetbrains.python.fixtures.PyTestCase;
import com.jetbrains.python.packaging.PyExternalProcessException;
import com.jetbrains.python.packaging.PyPackage;
import com.jetbrains.python.packaging.PyPackagingUtil;
import java.util.List;
/**
* @author vlan
*/
public class PyPackagingTest extends PyTestCase {
private static final Logger LOG = Logger.getInstance(PyEnvTestCase.class.getName());
public void testInstalledPackages() {
final List<String> roots = PyEnvTestCase.getPythonRoots();
if (roots.size() == 0) {
String msg = getTestName(false) + ": environments are not defined. Skipping.";
LOG.warn(msg);
System.out.println(msg);
return;
}
for (String root : roots) {
List<PyPackage> packages = null;
try {
packages = PyPackagingUtil.getInstalledPackages(root);
}
catch (PyExternalProcessException e) {
final int retcode = e.getRetcode();
if (retcode != PyPackagingUtil.OK && retcode != PyPackagingUtil.ERROR_NO_PACKAGING_TOOLS) {
fail(String.format("Error for root '%s': %s", root, e.getMessage()));
}
}
if (packages != null) {
assertTrue(packages.size() > 0);
for (PyPackage pkg : packages) {
assertTrue(pkg.getName().length() > 0);
}
}
}
}
}
| PyPackagingTest converted to envtests
| python/testSrc/com/jetbrains/python/PyPackagingTest.java | PyPackagingTest converted to envtests | <ide><path>ython/testSrc/com/jetbrains/python/PyPackagingTest.java
<del>package com.jetbrains.python;
<del>
<del>import com.intellij.openapi.diagnostic.Logger;
<del>import com.jetbrains.python.env.debug.PyEnvTestCase;
<del>import com.jetbrains.python.fixtures.PyTestCase;
<del>import com.jetbrains.python.packaging.PyExternalProcessException;
<del>import com.jetbrains.python.packaging.PyPackage;
<del>import com.jetbrains.python.packaging.PyPackagingUtil;
<del>
<del>import java.util.List;
<del>
<del>/**
<del> * @author vlan
<del> */
<del>public class PyPackagingTest extends PyTestCase {
<del> private static final Logger LOG = Logger.getInstance(PyEnvTestCase.class.getName());
<del>
<del> public void testInstalledPackages() {
<del> final List<String> roots = PyEnvTestCase.getPythonRoots();
<del> if (roots.size() == 0) {
<del> String msg = getTestName(false) + ": environments are not defined. Skipping.";
<del> LOG.warn(msg);
<del> System.out.println(msg);
<del> return;
<del> }
<del> for (String root : roots) {
<del> List<PyPackage> packages = null;
<del> try {
<del> packages = PyPackagingUtil.getInstalledPackages(root);
<del> }
<del> catch (PyExternalProcessException e) {
<del> final int retcode = e.getRetcode();
<del> if (retcode != PyPackagingUtil.OK && retcode != PyPackagingUtil.ERROR_NO_PACKAGING_TOOLS) {
<del> fail(String.format("Error for root '%s': %s", root, e.getMessage()));
<del> }
<del> }
<del> if (packages != null) {
<del> assertTrue(packages.size() > 0);
<del> for (PyPackage pkg : packages) {
<del> assertTrue(pkg.getName().length() > 0);
<del> }
<del> }
<del> }
<del> }
<del>} |
||
Java | mit | 7be6ea2572f9761e10db5379daa9832b8c94255a | 0 | cflee/sloca-checker | package slocachecker;
import is203.JWTUtility;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.JSONAssert;
public class SlocaChecker {
public static void main(String[] args) {
try {
// check for minimum number of arguments, fail fast if missing
if (args.length < 1) {
System.out.println("Usage:");
System.out.println("java SlocaChecker <input filename>");
return;
}
// read all lines from file and concat into a string for JSONArray constructor parser
StringBuilder inputFileSB = new StringBuilder();
for (String line : Files.readAllLines(Paths.get(args[0]))) {
inputFileSB.append(line);
}
JSONArray inputFileJsonArray = new JSONArray(inputFileSB.toString());
// setup the default settings Map
Map<String, String> settings = new HashMap<>();
settings.put("baseUrl", "http://localhost:8084/json/");
settings.put("secret", "abcdefghijklmnop");
settings.put("adminUsername", "admin");
// look for the settings in the first object. if found, overwrite in our settings map
JSONObject inputFileConfigObject = inputFileJsonArray.getJSONObject(0);
for (Map.Entry<String, String> entry : settings.entrySet()) {
if (inputFileConfigObject.has(entry.getKey())) {
settings.put(entry.getKey(), inputFileConfigObject.getString(entry.getKey()));
}
}
// TOOD: add some validation of the user-specified settings here (eg baseUrl endsWith /)
// keep track of the total number of tests to be run, and tests passed
System.out.println("Total number of tests to run: " + (inputFileJsonArray.length() - 1));
System.out.println();
int numTestsPassed = 0;
// iterate through all the Test objects, skipping the Config object
for (int t = 1; t < inputFileJsonArray.length(); t++) {
// retrieve the Test object
JSONObject testData = inputFileJsonArray.getJSONObject(t);
// extract data from the Test object
String description = null;
String endpoint = null;
boolean needsAuthentication = false;
boolean isPost = false;
// check0 is used for the 'result' key option
// checks is used for the 'checks' array of Check objects option
JSONObject check0 = null;
JSONArray checks = null;
String generatedToken = null;
String returnedResponse = null;
try {
// retrieve all the test-specific parameters that we recognise
// mandatory keys
description = testData.getString("description");
endpoint = testData.getString("endpoint");
// optional keys
needsAuthentication = testData.optBoolean("authenticate", true);
isPost = testData.optBoolean("post");
if (testData.has("checks")) {
checks = testData.getJSONArray("checks");
} else {
// checks is not present, so the result key is mandatory
check0 = testData.getJSONObject("result");
}
// remove them from the JSONObject, to avoid them being placed
// into the GET or POST request later
testData.remove("description");
testData.remove("endpoint");
testData.remove("authenticate");
testData.remove("post");
testData.remove("checks");
testData.remove("result");
} catch (JSONException e) {
printException(t, description, "Can't test, missing mandatory attribute(s)", e);
continue;
}
// centralise the token generation here
if (needsAuthentication) {
generatedToken = JWTUtility.sign(settings.get("secret"), settings.get("adminUsername"));
}
// send the request for this test, obtain result
try {
if (isPost) {
// perform a POST request
// figure out the parameters to be sent as POST payload
// put in the token first, so that it can be overrided by the test file later
Form form = Form.form();
if (needsAuthentication) {
form.add("token", generatedToken);
}
// grab all remaining key/value pairs and add to the "form"
for (String key : (Set<String>) testData.keySet()) {
form.add(key, testData.getString(key));
}
// send HTTP POST request
returnedResponse = Request.Post(settings.get("baseUrl") + endpoint)
.socketTimeout(240 * 1000)
.bodyForm(form.build())
.execute().returnContent().asString();
} else {
// perform a GET request
// figure out the parameters to go into the query string
// put in the token first, so that it can be overrided by the test file later
URIBuilder uriBuilder = new URIBuilder(settings.get("baseUrl") + endpoint);
if (needsAuthentication) {
uriBuilder.setParameter("token", generatedToken);
}
// grab all remaining key/value pairs and add to the URI
for (String key : (Set<String>) testData.keySet()) {
uriBuilder.setParameter(key, "" + testData.get(key));
}
// send HTTP request
returnedResponse = Request.Get(uriBuilder.build())
.socketTimeout(240 * 1000)
.execute().returnContent().asString();
}
} catch (IOException | IllegalArgumentException e) {
// HTTP client couldn't connect or send for whatever reason
printException(t, description, "Could not connect to the web service!", e);
} catch (URISyntaxException e) {
// problem with constructing the URIBuilder
// (this is the Apache HttpComponents URIBuilder, not Java EE)
printException(t, description, "There was a problem with the baseUrl/endpoint!", e);
}
// process checks against the result
if (returnedResponse != null) {
JSONObject actualResult = new JSONObject(returnedResponse);
boolean failed = false;
// perform the single 'result' check
if (check0 != null) {
JSONObject expectedResult = check0;
if (!performExactCheck(t, 0, description, expectedResult, actualResult)) {
failed = true;
}
}
// process the Check objects, only if that JSON array does exist!
if (checks != null) {
for (int c = 0; c < checks.length(); c++) {
JSONObject check = checks.getJSONObject(c);
if (check.getString("type").equals("exact")) {
JSONObject expectedResult = check.getJSONObject("value");
// add one to the check #, because for user-friendliness, start counting from 1!
// also because 0 is reserved for the single 'result' check
if (!performExactCheck(t, c + 1, description, expectedResult, actualResult)) {
failed = true;
}
}
// TODO: other types of checks go here
}
}
// increment the counter only if all checks for this test passed
if (!failed) {
numTestsPassed++;
}
}
}
System.out.println();
System.out.println("Overall " + numTestsPassed + "/" + (inputFileJsonArray.length() - 1)
+ " tests passed.");
} catch (IOException ex) {
System.out.println("Error! Could not read from specified file.");
Logger.getLogger(SlocaChecker.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Perform an 'exact' type check between two JSONObjects, printing the result to the console. Note that this method
* both prints output to the console as well as returns a boolean value! It is a little strange for a non-void
* return type method.
*
* @param testNo Test # (should start from 1)
* @param checkNo Check # (should start from 1 if from Check object, 0 from result)
* @param testDescription test description
* @param expected expected JSONObject
* @param actual actual JSONObject
* @return true if passed check, false otherwise
*/
private static boolean performExactCheck(int testNo, int checkNo, String testDescription,
JSONObject expected, JSONObject actual) {
try {
JSONAssert.assertEquals(expected.toString(), actual, true);
System.out.println("Test #" + testNo + "-" + checkNo + " - PASS - " + testDescription);
return true;
} catch (AssertionError e) {
System.out.println("Test #" + testNo + "-" + checkNo + " - FAIL - " + testDescription);
System.out.print(" Assertion details:");
// don't print a newline for previous line as there will be one
// extra from the following replaceAll to indent message by 4 spaces
System.out.println(e.getMessage().replaceAll("^|\r\n|\n", "\r\n "));
System.out.println(" Checker details:");
System.out.println(" EXPECTED result: " + expected);
System.out.println(" ACTUAL result: " + actual);
}
return false;
}
private static void printException(int testNo, String testDescription, String message, Exception e) {
System.out.println("Test #" + testNo + " - ERROR - " + testDescription);
System.out.print(" " + message);
if (e.getMessage() != null) {
System.out.println(e.getMessage().replaceAll("^|\r\n|\n", "\r\n "));
} else {
// send a newline for after the message
System.out.println(("Exception class: " + e.toString())
.replaceAll("^|\r\n|\n", "\r\n "));
}
}
}
| src/slocachecker/SlocaChecker.java | package slocachecker;
import is203.JWTUtility;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.JSONAssert;
public class SlocaChecker {
public static void main(String[] args) {
try {
// check for minimum number of arguments, fail fast if missing
if (args.length < 1) {
System.out.println("Usage:");
System.out.println("java SlocaChecker <input filename>");
return;
}
// read all lines from file and concat into a string for JSONArray constructor parser
StringBuilder inputFileSB = new StringBuilder();
for (String line : Files.readAllLines(Paths.get(args[0]))) {
inputFileSB.append(line);
}
JSONArray inputFileJsonArray = new JSONArray(inputFileSB.toString());
// setup the default settings Map
Map<String, String> settings = new HashMap<>();
settings.put("baseUrl", "http://localhost:8084/json/");
settings.put("secret", "abcdefghijklmnop");
settings.put("adminUsername", "admin");
// look for the settings in the first object. if found, overwrite in our settings map
JSONObject inputFileConfigObject = inputFileJsonArray.getJSONObject(0);
for (Map.Entry<String, String> entry : settings.entrySet()) {
if (inputFileConfigObject.has(entry.getKey())) {
settings.put(entry.getKey(), inputFileConfigObject.getString(entry.getKey()));
}
}
// TOOD: add some validation of the user-specified settings here (eg baseUrl endsWith /)
// keep track of the total number of tests to be run, and tests passed
System.out.println("Total number of tests to run: " + (inputFileJsonArray.length() - 1));
System.out.println();
int numTestsPassed = 0;
// iterate through all the Test objects, skipping the Config object
for (int t = 1; t < inputFileJsonArray.length(); t++) {
// retrieve the Test object
JSONObject testData = inputFileJsonArray.getJSONObject(t);
// extract data from the Test object
String description = null;
String endpoint = null;
boolean needsAuthentication = false;
boolean isPost = false;
// check0 is used for the 'result' key option
// checks is used for the 'checks' array of Check objects option
JSONObject check0 = null;
JSONArray checks = null;
String generatedToken = null;
String returnedResponse = null;
try {
// retrieve all the test-specific parameters that we recognise
// mandatory keys
description = testData.getString("description");
endpoint = testData.getString("endpoint");
// optional keys
needsAuthentication = testData.optBoolean("authenticate", true);
isPost = testData.optBoolean("post");
if (testData.has("checks")) {
checks = testData.getJSONArray("checks");
} else {
// checks is not present, so the result key is mandatory
check0 = testData.getJSONObject("result");
}
// remove them from the JSONObject, to avoid them being placed
// into the GET or POST request later
testData.remove("description");
testData.remove("endpoint");
testData.remove("authenticate");
testData.remove("post");
testData.remove("checks");
testData.remove("result");
} catch (JSONException e) {
printException(t, description, "Can't test, missing mandatory attribute(s)", e);
continue;
}
// centralise the token generation here
if (needsAuthentication) {
generatedToken = JWTUtility.sign(settings.get("secret"), settings.get("adminUsername"));
}
// send the request for this test, obtain result
try {
if (isPost) {
// perform a POST request
// figure out the parameters to be sent as POST payload
// put in the token first, so that it can be overrided by the test file later
Form form = Form.form();
if (needsAuthentication) {
form.add("token", generatedToken);
}
// grab all remaining key/value pairs and add to the "form"
for (String key : (Set<String>) testData.keySet()) {
form.add(key, testData.getString(key));
}
// send HTTP POST request
returnedResponse = Request.Post(settings.get("baseUrl") + endpoint)
.socketTimeout(240 * 1000)
.bodyForm(form.build())
.execute().returnContent().asString();
} else {
// perform a GET request
// figure out the parameters to go into the query string
// put in the token first, so that it can be overrided by the test file later
URIBuilder uriBuilder = new URIBuilder(settings.get("baseUrl") + endpoint);
if (needsAuthentication) {
uriBuilder.setParameter("token", generatedToken);
}
// grab all remaining key/value pairs and add to the URI
for (String key : (Set<String>) testData.keySet()) {
uriBuilder.setParameter(key, "" + testData.get(key));
}
// send HTTP request
returnedResponse = Request.Get(uriBuilder.build())
.socketTimeout(240 * 1000)
.execute().returnContent().asString();
}
} catch (IOException | IllegalArgumentException e) {
// HTTP client couldn't connect or send for whatever reason
printException(t, description, "Could not connect to the web service!", e);
} catch (URISyntaxException e) {
// problem with constructing the URIBuilder
// (this is the Apache HttpComponents URIBuilder, not Java EE)
printException(t, description, "There was a problem with the baseUrl/endpoint!", e);
}
// process checks against the result
if (returnedResponse != null) {
JSONObject actualResult = new JSONObject(returnedResponse);
boolean failed = false;
// perform the single 'result' check
if (check0 != null) {
JSONObject expectedResult = check0;
if (!performExactCheck(t, 0, description, expectedResult, actualResult)) {
failed = true;
}
}
// process the Check objects, only if that JSON array does exist!
if (checks != null) {
for (int c = 0; c < checks.length(); c++) {
JSONObject check = checks.getJSONObject(c);
if (check.getString("type").equals("exact")) {
JSONObject expectedResult = check.getJSONObject("value");
if (!performExactCheck(t, c, description, expectedResult, actualResult)) {
failed = true;
}
}
// TODO: other types of checks go here
}
}
// increment the counter only if all checks for this test passed
if (!failed) {
numTestsPassed++;
}
}
}
System.out.println();
System.out.println("Overall " + numTestsPassed + "/" + (inputFileJsonArray.length() - 1)
+ " tests passed.");
} catch (IOException ex) {
System.out.println("Error! Could not read from specified file.");
Logger.getLogger(SlocaChecker.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Perform an 'exact' type check between two JSONObjects, printing the result to the console. Note that this method
* both prints output to the console as well as returns a boolean value! It is a little strange for a non-void
* return type method.
*
* @param testNo Test # (should start from 1)
* @param checkNo Check # (should start from 1 if from Check object, 0 from result)
* @param testDescription test description
* @param expected expected JSONObject
* @param actual actual JSONObject
* @return true if passed check, false otherwise
*/
private static boolean performExactCheck(int testNo, int checkNo, String testDescription,
JSONObject expected, JSONObject actual) {
try {
JSONAssert.assertEquals(expected.toString(), actual, true);
System.out.println("Test #" + testNo + "-" + checkNo + " - PASS - " + testDescription);
return true;
} catch (AssertionError e) {
System.out.println("Test #" + testNo + "-" + checkNo + " - FAIL - " + testDescription);
System.out.print(" Assertion details:");
// don't print a newline for previous line as there will be one
// extra from the following replaceAll to indent message by 4 spaces
System.out.println(e.getMessage().replaceAll("^|\r\n|\n", "\r\n "));
System.out.println(" Checker details:");
System.out.println(" EXPECTED result: " + expected);
System.out.println(" ACTUAL result: " + actual);
}
return false;
}
private static void printException(int testNo, String testDescription, String message, Exception e) {
System.out.println("Test #" + testNo + " - ERROR - " + testDescription);
System.out.print(" " + message);
if (e.getMessage() != null) {
System.out.println(e.getMessage().replaceAll("^|\r\n|\n", "\r\n "));
} else {
// send a newline for after the message
System.out.println(("Exception class: " + e.toString())
.replaceAll("^|\r\n|\n", "\r\n "));
}
}
}
| Fix output numbering of checks for complex 'checks' usage
| src/slocachecker/SlocaChecker.java | Fix output numbering of checks for complex 'checks' usage | <ide><path>rc/slocachecker/SlocaChecker.java
<ide> if (check.getString("type").equals("exact")) {
<ide> JSONObject expectedResult = check.getJSONObject("value");
<ide>
<del> if (!performExactCheck(t, c, description, expectedResult, actualResult)) {
<add> // add one to the check #, because for user-friendliness, start counting from 1!
<add> // also because 0 is reserved for the single 'result' check
<add> if (!performExactCheck(t, c + 1, description, expectedResult, actualResult)) {
<ide> failed = true;
<ide> }
<ide> } |
|
Java | apache-2.0 | 411511c090bd9e4c50b3224ca90f0813a3bb1b73 | 0 | ResearchWorx/Cresco-Agent-Controller-Plugin | package ActiveMQ;
import java.util.HashMap;
import java.util.Map;
public class BrokeredAgent {
public Map<String,BrokerStatusType> addressMap;
public BrokerStatusType brokerStatus;
public String activeAddress;
public String agentPath;
public BrokerMonitor bm;
public BrokeredAgent(String activeAddress, String agentPath)
{
System.out.println("Creating BrokerAgent : " + agentPath + " address: " + activeAddress);
System.out.print("Name of Agent to message: ");
this.bm = new BrokerMonitor(agentPath);
this.activeAddress = activeAddress;
this.agentPath = agentPath;
this.brokerStatus = BrokerStatusType.INIT;
this.addressMap = new HashMap<String,BrokerStatusType>();
this.addressMap.put(activeAddress, BrokerStatusType.INIT);
}
public void setStop()
{
//System.out.println("BrokeredAgent : setStop");
if(bm.MonitorActive)
{
//System.out.println("BrokeredAgent : setStop : shutdown");
bm.shutdown();
}
while(bm.MonitorActive)
{
//System.out.println("BrokeredAgent : setStop : Monitor Active");
try {
//System.out.println("STOPPING " + agentPath);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
brokerStatus = BrokerStatusType.STOPPED;
System.out.println("BrokeredAgent : setStop : Broker STOP");
}
public void setStarting()
{
brokerStatus = BrokerStatusType.STARTING;
addressMap.put(activeAddress, BrokerStatusType.STARTING);
if(bm.MonitorActive)
{
bm.shutdown();
}
bm = new BrokerMonitor(agentPath);
new Thread(bm).start();
while(!bm.MonitorActive)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void setActive()
{
brokerStatus = BrokerStatusType.ACTIVE;
addressMap.put(activeAddress, BrokerStatusType.ACTIVE);
}
} | src/main/java/ActiveMQ/BrokeredAgent.java | package ActiveMQ;
import java.util.HashMap;
import java.util.Map;
public class BrokeredAgent {
public Map<String,BrokerStatusType> addressMap;
public BrokerStatusType brokerStatus;
public String activeAddress;
public String agentPath;
public BrokerMonitor bm;
public BrokeredAgent(String activeAddress, String agentPath)
{
System.out.println("Creating BrokerAgnet : " + agentPath + " address: " + activeAddress);
this.bm = new BrokerMonitor(agentPath);
this.activeAddress = activeAddress;
this.agentPath = agentPath;
this.brokerStatus = BrokerStatusType.INIT;
this.addressMap = new HashMap<String,BrokerStatusType>();
this.addressMap.put(activeAddress, BrokerStatusType.INIT);
}
public void setStop()
{
//System.out.println("BrokeredAgent : setStop");
if(bm.MonitorActive)
{
//System.out.println("BrokeredAgent : setStop : shutdown");
bm.shutdown();
}
while(bm.MonitorActive)
{
//System.out.println("BrokeredAgent : setStop : Monitor Active");
try {
//System.out.println("STOPPING " + agentPath);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
brokerStatus = BrokerStatusType.STOPPED;
System.out.println("BrokeredAgent : setStop : Broker STOP");
}
public void setStarting()
{
brokerStatus = BrokerStatusType.STARTING;
addressMap.put(activeAddress, BrokerStatusType.STARTING);
if(bm.MonitorActive)
{
bm.shutdown();
}
bm = new BrokerMonitor(agentPath);
new Thread(bm).start();
while(!bm.MonitorActive)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void setActive()
{
brokerStatus = BrokerStatusType.ACTIVE;
addressMap.put(activeAddress, BrokerStatusType.ACTIVE);
}
} | Looking into BrokerMonitor
| src/main/java/ActiveMQ/BrokeredAgent.java | Looking into BrokerMonitor | <ide><path>rc/main/java/ActiveMQ/BrokeredAgent.java
<ide>
<ide> public BrokeredAgent(String activeAddress, String agentPath)
<ide> {
<del> System.out.println("Creating BrokerAgnet : " + agentPath + " address: " + activeAddress);
<add> System.out.println("Creating BrokerAgent : " + agentPath + " address: " + activeAddress);
<add> System.out.print("Name of Agent to message: ");
<ide> this.bm = new BrokerMonitor(agentPath);
<ide> this.activeAddress = activeAddress;
<ide> this.agentPath = agentPath; |
|
JavaScript | apache-2.0 | c5e88ea7c820c98654e277d0c54c8aff84b52b3b | 0 | GoogleForCreators/web-stories-wp,GoogleForCreators/web-stories-wp,GoogleForCreators/web-stories-wp,GoogleForCreators/web-stories-wp,GoogleForCreators/web-stories-wp | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { useEffect, useMemo, useState, useRef } from 'react';
/**
* Internal dependencies
*/
import { PAGE_RATIO } from '../constants';
import theme from '../theme';
const descendingBreakpointKeys = Object.keys(theme.breakpoint.raw).sort(
(a, b) => theme.breakpoint.raw[b] - theme.breakpoint.raw[a]
);
const getCurrentBp = (availableContainerSpace) => {
return descendingBreakpointKeys.reduce((current, bp) => {
return availableContainerSpace <= theme.breakpoint.raw[bp] ? bp : current;
}, descendingBreakpointKeys[0]);
};
// this will break the detail template view
const sizeFromWidth = (width, { respectSetWidth, availableContainerSpace }) => {
if (respectSetWidth) {
return { width, height: width / PAGE_RATIO };
}
const itemsInRow = Math.floor(availableContainerSpace / width);
const columnGapWidth = 10 * itemsInRow;
const takenSpace = width * itemsInRow + columnGapWidth;
const remainingSpace = availableContainerSpace - takenSpace;
const addToWidthValue = remainingSpace / itemsInRow;
const trueWidth = width + addToWidthValue;
return {
width: trueWidth,
height: trueWidth / PAGE_RATIO,
};
};
const WP_LEFT_NAV_WIDTH = 38;
const DASHBOARD_LEFT_NAV_WIDTH = 190;
// NO MAGIC NUMBERS - set gutter by bp
const getTrueInnerWidth = (bp) => {
const { innerWidth } = window;
if (innerWidth >= 783 && innerWidth <= 1120) {
return innerWidth - WP_LEFT_NAV_WIDTH;
} else if (innerWidth >= 1120) {
return innerWidth - WP_LEFT_NAV_WIDTH - DASHBOARD_LEFT_NAV_WIDTH - 40;
} else {
return innerWidth;
}
};
export default function usePagePreviewSize(options = {}) {
const { thumbnailMode = false, isGrid } = options;
const [availableContainerSpace, setAvailableContainerSpace] = useState(
getTrueInnerWidth()
);
const [bp, setBp] = useState(getCurrentBp(availableContainerSpace));
useEffect(() => {
if (thumbnailMode) {
return () => {};
}
const handleResize = () => setAvailableContainerSpace(getTrueInnerWidth());
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [thumbnailMode, availableContainerSpace]);
useEffect(() => {
if (thumbnailMode) {
return () => {};
}
return setBp(getCurrentBp(availableContainerSpace));
}, [setBp, thumbnailMode, availableContainerSpace]);
return useMemo(
() => ({
pageSize: sizeFromWidth(
theme.previewWidth[thumbnailMode ? 'thumbnail' : bp],
{
respectSetWidth: !isGrid || thumbnailMode,
availableContainerSpace,
bp,
}
),
}),
[bp, isGrid, thumbnailMode, availableContainerSpace]
);
}
| assets/src/dashboard/utils/usePagePreviewSize.js | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { useEffect, useMemo, useState } from 'react';
/**
* Internal dependencies
*/
import { PAGE_RATIO } from '../constants';
import theme from '../theme';
const descendingBreakpointKeys = Object.keys(theme.breakpoint.raw).sort(
(a, b) => theme.breakpoint.raw[b] - theme.breakpoint.raw[a]
);
const getCurrentBp = () =>
descendingBreakpointKeys.reduce(
(current, bp) =>
window.innerWidth <= theme.breakpoint.raw[bp] ? bp : current,
descendingBreakpointKeys[0]
);
const sizeFromWidth = (width) => ({
width,
height: width / PAGE_RATIO,
});
export default function usePagePreviewSize(options = {}) {
const { thumbnailMode = false } = options;
const [bp, setBp] = useState(getCurrentBp());
useEffect(() => {
if (thumbnailMode) {
return () => {};
}
const handleResize = () => setBp(getCurrentBp());
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [thumbnailMode]);
return useMemo(
() => ({
pageSize: sizeFromWidth(
theme.previewWidth[thumbnailMode ? 'thumbnail' : bp]
),
}),
[bp, thumbnailMode]
);
}
| wip working resize on cards to take up all available space
| assets/src/dashboard/utils/usePagePreviewSize.js | wip working resize on cards to take up all available space | <ide><path>ssets/src/dashboard/utils/usePagePreviewSize.js
<ide> /**
<ide> * External dependencies
<ide> */
<del>import { useEffect, useMemo, useState } from 'react';
<add>import { useEffect, useMemo, useState, useRef } from 'react';
<ide> /**
<ide> * Internal dependencies
<ide> */
<ide> const descendingBreakpointKeys = Object.keys(theme.breakpoint.raw).sort(
<ide> (a, b) => theme.breakpoint.raw[b] - theme.breakpoint.raw[a]
<ide> );
<del>const getCurrentBp = () =>
<del> descendingBreakpointKeys.reduce(
<del> (current, bp) =>
<del> window.innerWidth <= theme.breakpoint.raw[bp] ? bp : current,
<del> descendingBreakpointKeys[0]
<add>const getCurrentBp = (availableContainerSpace) => {
<add> return descendingBreakpointKeys.reduce((current, bp) => {
<add> return availableContainerSpace <= theme.breakpoint.raw[bp] ? bp : current;
<add> }, descendingBreakpointKeys[0]);
<add>};
<add>
<add>// this will break the detail template view
<add>const sizeFromWidth = (width, { respectSetWidth, availableContainerSpace }) => {
<add> if (respectSetWidth) {
<add> return { width, height: width / PAGE_RATIO };
<add> }
<add>
<add> const itemsInRow = Math.floor(availableContainerSpace / width);
<add> const columnGapWidth = 10 * itemsInRow;
<add> const takenSpace = width * itemsInRow + columnGapWidth;
<add> const remainingSpace = availableContainerSpace - takenSpace;
<add> const addToWidthValue = remainingSpace / itemsInRow;
<add>
<add> const trueWidth = width + addToWidthValue;
<add> return {
<add> width: trueWidth,
<add> height: trueWidth / PAGE_RATIO,
<add> };
<add>};
<add>
<add>const WP_LEFT_NAV_WIDTH = 38;
<add>const DASHBOARD_LEFT_NAV_WIDTH = 190;
<add>
<add>// NO MAGIC NUMBERS - set gutter by bp
<add>const getTrueInnerWidth = (bp) => {
<add> const { innerWidth } = window;
<add> if (innerWidth >= 783 && innerWidth <= 1120) {
<add> return innerWidth - WP_LEFT_NAV_WIDTH;
<add> } else if (innerWidth >= 1120) {
<add> return innerWidth - WP_LEFT_NAV_WIDTH - DASHBOARD_LEFT_NAV_WIDTH - 40;
<add> } else {
<add> return innerWidth;
<add> }
<add>};
<add>export default function usePagePreviewSize(options = {}) {
<add> const { thumbnailMode = false, isGrid } = options;
<add> const [availableContainerSpace, setAvailableContainerSpace] = useState(
<add> getTrueInnerWidth()
<ide> );
<ide>
<del>const sizeFromWidth = (width) => ({
<del> width,
<del> height: width / PAGE_RATIO,
<del>});
<del>
<del>export default function usePagePreviewSize(options = {}) {
<del> const { thumbnailMode = false } = options;
<del> const [bp, setBp] = useState(getCurrentBp());
<add> const [bp, setBp] = useState(getCurrentBp(availableContainerSpace));
<ide>
<ide> useEffect(() => {
<ide> if (thumbnailMode) {
<ide> return () => {};
<ide> }
<ide>
<del> const handleResize = () => setBp(getCurrentBp());
<add> const handleResize = () => setAvailableContainerSpace(getTrueInnerWidth());
<add>
<ide> window.addEventListener('resize', handleResize);
<ide> return () => {
<ide> window.removeEventListener('resize', handleResize);
<ide> };
<del> }, [thumbnailMode]);
<add> }, [thumbnailMode, availableContainerSpace]);
<add>
<add> useEffect(() => {
<add> if (thumbnailMode) {
<add> return () => {};
<add> }
<add> return setBp(getCurrentBp(availableContainerSpace));
<add> }, [setBp, thumbnailMode, availableContainerSpace]);
<ide>
<ide> return useMemo(
<ide> () => ({
<ide> pageSize: sizeFromWidth(
<del> theme.previewWidth[thumbnailMode ? 'thumbnail' : bp]
<add> theme.previewWidth[thumbnailMode ? 'thumbnail' : bp],
<add> {
<add> respectSetWidth: !isGrid || thumbnailMode,
<add> availableContainerSpace,
<add> bp,
<add> }
<ide> ),
<ide> }),
<del> [bp, thumbnailMode]
<add> [bp, isGrid, thumbnailMode, availableContainerSpace]
<ide> );
<ide> } |
|
Java | apache-2.0 | d1d1b02d19d06efad5bbbdb2116d8f09778a90ed | 0 | freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.tools.appletviewer;
import java.applet.AudioClip;
import java.net.URL;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
class ViewerAudioClip implements AudioClip {
private ClipImpl clip;
public ViewerAudioClip(URL url) {
AudioFormat af = null;
AudioInputStream ais = null;
SourceDataLine line = null;
try {
ais = AudioSystem.getAudioInputStream(url);
} catch (Exception e) {
System.out.println(url.toString());
e.printStackTrace();
ais = null;
return;
}
af = ais.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
boolean isSupported = AudioSystem.isLineSupported(info);
if (!isSupported){
AudioFormat tf = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
af.getSampleRate(),
16,
af.getChannels(),
af.getChannels() << 1,
af.getSampleRate(),
false);
ais = AudioSystem.getAudioInputStream(tf, ais);
af = ais.getFormat();
info = new DataLine.Info(SourceDataLine.class, af);
}
try{
line = (SourceDataLine) AudioSystem.getLine(info);
}catch (Exception e){
e.printStackTrace();
}
clip = new ClipImpl(af, ais, line);
}
public void loop() {
if(clip != null)
clip.loop();
}
public void play() {
if(clip != null)
clip.play();
}
public void stop() {
if(clip != null)
clip.stop();
}
private static class ClipImpl implements AudioClip, Runnable {
static final int BufferSize = 1024;
static final int UNLIMITED = -1;
AudioFormat af;
AudioInputStream ais;
SourceDataLine line;
Thread clip;
boolean started;
int streamLength;
int count;
ClipImpl(AudioFormat af, AudioInputStream ais, SourceDataLine line){
this.af = af;
this.ais = ais;
this.line = line;
if(ais.getFrameLength() == AudioSystem.NOT_SPECIFIED ||
af.getFrameSize() == AudioSystem.NOT_SPECIFIED){
streamLength = -1;
}
long length = ais.getFrameLength() * af.getFrameSize();
if(length > Integer.MAX_VALUE){
streamLength = -1;
}
streamLength = (int)length;
clip = new Thread(this);
}
public void run(){
if(streamLength < 0) return;
started = true;
int bytesRead = 0;
byte[] data = new byte[BufferSize];
try{
line.open(af);
}catch (Exception e){
e.printStackTrace();
}
// Main cycle
while(true){
line.start();
do{
ais.mark(streamLength);
bytesRead = 0;
while (bytesRead != -1){
try{
bytesRead = ais.read(data, 0, data.length);
}catch (Exception e){
e.printStackTrace();
}
if (bytesRead >= 0){
line.write(data, 0, bytesRead);
}
}
try{
ais.reset();
}catch (Exception e){
e.printStackTrace();
}
}while(count < 0 || --count > 0);
synchronized(clip){
try{
clip.wait();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
public void play(){
if(!started) clip.start();
synchronized(this){
count = 1;
synchronized(clip){
clip.notify();
}
}
}
public void loop(){
if(!started) clip.start();
synchronized(this){
count = UNLIMITED;
synchronized(clip){
clip.notify();
}
}
}
public void stop(){
synchronized(this){
line.stop();
count = 1;
}
}
protected void finalize(){
if(line != null && line.isOpen()){
line.drain();
line.close();
}
}
}
}
| modules/tools/src/main/java/org/apache/harmony/tools/appletviewer/ViewerAudioClip.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.tools.appletviewer;
import java.applet.AudioClip;
import java.net.URL;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.Transmitter;
class ViewerAudioClip implements AudioClip {
//private Clip clip;
private Sequencer sequencer;
public ViewerAudioClip(URL url) {
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
Sequence sequence = MidiSystem.getSequence(url);
sequencer.setSequence(sequence);
if (!(sequencer instanceof Synthesizer)) {
Synthesizer synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
Receiver receiver = synthesizer.getReceiver();
Transmitter transmitter = sequencer.getTransmitter();
transmitter.setReceiver(receiver);
}
} catch (Exception e) {
sequencer = null;
}
// try {
// this.clip = AudioSystem.getClip();
// clip.open(AudioSystem.getAudioInputStream(url));
// } catch (Exception e) {
// this.clip = null;
// }
}
public void loop() {
if (sequencer != null)
sequencer.start();
// if (clip != null)
// clip.loop(Clip.LOOP_CONTINUOUSLY);
}
public void play() {
if (sequencer != null)
sequencer.start();
// if (clip != null)
// clip.start();
}
public void stop() {
if (sequencer != null)
sequencer.stop();
// if (clip != null)
// clip.stop();
}
}
| Patch for HARMONY-5444 "[jdktools][appletviewer] appletviewer doesn't
play sound tracks"
svn path=/harmony/enhanced/jdktools/trunk/; revision=617103
| modules/tools/src/main/java/org/apache/harmony/tools/appletviewer/ViewerAudioClip.java | Patch for HARMONY-5444 "[jdktools][appletviewer] appletviewer doesn't play sound tracks" | <ide><path>odules/tools/src/main/java/org/apache/harmony/tools/appletviewer/ViewerAudioClip.java
<ide> import java.applet.AudioClip;
<ide> import java.net.URL;
<ide>
<del>import javax.sound.midi.MidiSystem;
<del>import javax.sound.midi.Receiver;
<del>import javax.sound.midi.Sequence;
<del>import javax.sound.midi.Sequencer;
<del>import javax.sound.midi.Synthesizer;
<del>import javax.sound.midi.Transmitter;
<add>import javax.sound.sampled.AudioFormat;
<add>import javax.sound.sampled.AudioInputStream;
<add>import javax.sound.sampled.AudioSystem;
<add>import javax.sound.sampled.DataLine;
<add>import javax.sound.sampled.SourceDataLine;
<ide>
<ide> class ViewerAudioClip implements AudioClip {
<del> //private Clip clip;
<del> private Sequencer sequencer;
<del>
<add>
<add> private ClipImpl clip;
<add>
<ide> public ViewerAudioClip(URL url) {
<add> AudioFormat af = null;
<add> AudioInputStream ais = null;
<add> SourceDataLine line = null;
<ide> try {
<del> sequencer = MidiSystem.getSequencer();
<del> sequencer.open();
<del>
<del> Sequence sequence = MidiSystem.getSequence(url);
<del> sequencer.setSequence(sequence);
<del>
<del> if (!(sequencer instanceof Synthesizer)) {
<del> Synthesizer synthesizer = MidiSystem.getSynthesizer();
<del> synthesizer.open();
<del> Receiver receiver = synthesizer.getReceiver();
<del> Transmitter transmitter = sequencer.getTransmitter();
<del> transmitter.setReceiver(receiver);
<del> }
<add> ais = AudioSystem.getAudioInputStream(url);
<ide> } catch (Exception e) {
<del> sequencer = null;
<del> }
<del>// try {
<del>// this.clip = AudioSystem.getClip();
<del>// clip.open(AudioSystem.getAudioInputStream(url));
<del>// } catch (Exception e) {
<del>// this.clip = null;
<del>// }
<add> System.out.println(url.toString());
<add> e.printStackTrace();
<add> ais = null;
<add> return;
<add> }
<add> af = ais.getFormat();
<add> DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
<add>
<add> boolean isSupported = AudioSystem.isLineSupported(info);
<add> if (!isSupported){
<add> AudioFormat tf = new AudioFormat(
<add> AudioFormat.Encoding.PCM_SIGNED,
<add> af.getSampleRate(),
<add> 16,
<add> af.getChannels(),
<add> af.getChannels() << 1,
<add> af.getSampleRate(),
<add> false);
<add> ais = AudioSystem.getAudioInputStream(tf, ais);
<add> af = ais.getFormat();
<add> info = new DataLine.Info(SourceDataLine.class, af);
<add> }
<add> try{
<add> line = (SourceDataLine) AudioSystem.getLine(info);
<add> }catch (Exception e){
<add> e.printStackTrace();
<add> }
<add>
<add> clip = new ClipImpl(af, ais, line);
<add>
<ide> }
<ide>
<ide> public void loop() {
<del> if (sequencer != null)
<del> sequencer.start();
<del>// if (clip != null)
<del>// clip.loop(Clip.LOOP_CONTINUOUSLY);
<add> if(clip != null)
<add> clip.loop();
<ide> }
<ide>
<ide> public void play() {
<del> if (sequencer != null)
<del> sequencer.start();
<del>// if (clip != null)
<del>// clip.start();
<add> if(clip != null)
<add> clip.play();
<ide> }
<ide>
<ide> public void stop() {
<del> if (sequencer != null)
<del> sequencer.stop();
<del>// if (clip != null)
<del>// clip.stop();
<add> if(clip != null)
<add> clip.stop();
<add> }
<add>
<add> private static class ClipImpl implements AudioClip, Runnable {
<add>
<add> static final int BufferSize = 1024;
<add> static final int UNLIMITED = -1;
<add>
<add> AudioFormat af;
<add> AudioInputStream ais;
<add> SourceDataLine line;
<add> Thread clip;
<add> boolean started;
<add> int streamLength;
<add> int count;
<add>
<add> ClipImpl(AudioFormat af, AudioInputStream ais, SourceDataLine line){
<add> this.af = af;
<add> this.ais = ais;
<add> this.line = line;
<add>
<add> if(ais.getFrameLength() == AudioSystem.NOT_SPECIFIED ||
<add> af.getFrameSize() == AudioSystem.NOT_SPECIFIED){
<add>
<add> streamLength = -1;
<add> }
<add>
<add> long length = ais.getFrameLength() * af.getFrameSize();
<add>
<add> if(length > Integer.MAX_VALUE){
<add> streamLength = -1;
<add> }
<add>
<add> streamLength = (int)length;
<add> clip = new Thread(this);
<add> }
<add>
<add> public void run(){
<add> if(streamLength < 0) return;
<add>
<add> started = true;
<add>
<add> int bytesRead = 0;
<add> byte[] data = new byte[BufferSize];
<add>
<add> try{
<add> line.open(af);
<add> }catch (Exception e){
<add> e.printStackTrace();
<add> }
<add>
<add> // Main cycle
<add>
<add> while(true){
<add>
<add> line.start();
<add>
<add> do{
<add>
<add> ais.mark(streamLength);
<add> bytesRead = 0;
<add> while (bytesRead != -1){
<add> try{
<add> bytesRead = ais.read(data, 0, data.length);
<add> }catch (Exception e){
<add> e.printStackTrace();
<add> }
<add>
<add> if (bytesRead >= 0){
<add> line.write(data, 0, bytesRead);
<add> }
<add> }
<add>
<add> try{
<add> ais.reset();
<add> }catch (Exception e){
<add> e.printStackTrace();
<add> }
<add> }while(count < 0 || --count > 0);
<add>
<add> synchronized(clip){
<add> try{
<add> clip.wait();
<add> }catch (Exception e){
<add> e.printStackTrace();
<add> }
<add> }
<add>
<add> }
<add> }
<add>
<add> public void play(){
<add> if(!started) clip.start();
<add> synchronized(this){
<add> count = 1;
<add> synchronized(clip){
<add> clip.notify();
<add> }
<add> }
<add> }
<add>
<add> public void loop(){
<add> if(!started) clip.start();
<add> synchronized(this){
<add> count = UNLIMITED;
<add> synchronized(clip){
<add> clip.notify();
<add> }
<add> }
<add> }
<add>
<add> public void stop(){
<add> synchronized(this){
<add> line.stop();
<add> count = 1;
<add> }
<add> }
<add>
<add> protected void finalize(){
<add> if(line != null && line.isOpen()){
<add> line.drain();
<add> line.close();
<add> }
<add> }
<add>
<ide> }
<ide> } |
|
Java | mit | 472d1752b9ca6363c893d95e382d8fea64bb48aa | 0 | aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips | package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
ImageIcon icon = new ImageIcon(getClass().getResource("test.png"));
ZoomImage zoom = new ZoomImage(icon.getImage());
JButton button1 = new JButton("Zoom In");
button1.addActionListener(e -> zoom.changeScale(-5));
JButton button2 = new JButton("Zoom Out");
button2.addActionListener(e -> zoom.changeScale(5));
JButton button3 = new JButton("Original size");
button3.addActionListener(e -> zoom.initScale());
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.add(button1);
box.add(button2);
box.add(button3);
add(zoom);
add(box, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ZoomImage extends JPanel {
private transient MouseWheelListener handler;
private final transient Image image;
private final int iw;
private final int ih;
private double scale = 1d;
protected ZoomImage(Image image) {
super();
this.image = image;
iw = image.getWidth(this);
ih = image.getHeight(this);
}
@Override public void updateUI() {
removeMouseWheelListener(handler);
super.updateUI();
// handler = new MouseWheelListener() {
// @Override public void mouseWheelMoved(MouseWheelEvent e) {
// changeScale(e.getWheelRotation());
// }
// };
handler = e -> changeScale(e.getWheelRotation());
addMouseWheelListener(handler);
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.scale(scale, scale);
g2.drawImage(image, 0, 0, iw, ih, this);
g2.dispose();
}
public void initScale() {
scale = 1d;
repaint();
}
public void changeScale(int iv) {
scale = Math.max(.05, Math.min(5d, scale - iv * .05));
repaint();
//double v = scale - iv * .1;
//if (v - 1d > -1.0e-2) {
// scale = Math.min(10d, v);
//} else {
// scale = Math.max(.01, scale - iv * .01);
//}
}
}
| Zoom/src/java/example/MainPanel.java | package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
ImageIcon icon = new ImageIcon(getClass().getResource("test.png"));
ZoomImage zoom = new ZoomImage(icon.getImage());
JButton button1 = new JButton("Zoom In");
button1.addActionListener(e -> zoom.changeScale(-5));
JButton button2 = new JButton("Zoom Out");
button2.addActionListener(e -> zoom.changeScale(5));
JButton button3 = new JButton("Original size");
button3.addActionListener(e -> zoom.initScale());
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.add(button1);
box.add(button2);
box.add(button3);
add(zoom);
add(box, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ZoomImage extends JPanel {
private transient MouseWheelListener handler;
private final transient Image image;
private final int iw;
private final int ih;
private double scale = 1d;
protected ZoomImage(Image image) {
super();
this.image = image;
iw = image.getWidth(this);
ih = image.getHeight(this);
}
@Override public void updateUI() {
removeMouseWheelListener(handler);
super.updateUI();
handler = new MouseWheelListener() {
@Override public void mouseWheelMoved(MouseWheelEvent e) {
changeScale(e.getWheelRotation());
}
};
addMouseWheelListener(handler);
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.scale(scale, scale);
g2.drawImage(image, 0, 0, iw, ih, this);
g2.dispose();
}
public void initScale() {
scale = 1d;
repaint();
}
public void changeScale(int iv) {
scale = Math.max(.05, Math.min(5d, scale - iv * .05));
repaint();
//double v = scale - iv * .1;
//if (v - 1d > -1.0e-2) {
// scale = Math.min(10d, v);
//} else {
// scale = Math.max(.01, scale - iv * .01);
//}
}
}
| refactor: use a lambda expression instead of an anonymous class(MouseWheelListener)
| Zoom/src/java/example/MainPanel.java | refactor: use a lambda expression instead of an anonymous class(MouseWheelListener) | <ide><path>oom/src/java/example/MainPanel.java
<ide> @Override public void updateUI() {
<ide> removeMouseWheelListener(handler);
<ide> super.updateUI();
<del> handler = new MouseWheelListener() {
<del> @Override public void mouseWheelMoved(MouseWheelEvent e) {
<del> changeScale(e.getWheelRotation());
<del> }
<del> };
<add>// handler = new MouseWheelListener() {
<add>// @Override public void mouseWheelMoved(MouseWheelEvent e) {
<add>// changeScale(e.getWheelRotation());
<add>// }
<add>// };
<add> handler = e -> changeScale(e.getWheelRotation());
<ide> addMouseWheelListener(handler);
<ide> }
<ide> @Override protected void paintComponent(Graphics g) { |
|
Java | bsd-3-clause | b0133963035cc47cbf05cb3eaf5a0aec21e3e28f | 0 | wnbittle/praisenter | /*
* Praisenter: A free open source church presentation software.
* Copyright (C) 2012-2013 William Bittle http://www.praisenter.org/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.praisenter.media.player;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.praisenter.media.MediaPlayer;
import org.praisenter.media.MediaPlayerConfiguration;
import org.praisenter.media.MediaPlayerListener;
import org.praisenter.media.VideoMediaPlayerListener;
import org.praisenter.media.XugglerPlayableMedia;
import com.xuggle.xuggler.IAudioSamples;
import com.xuggle.xuggler.ICodec;
import com.xuggle.xuggler.IContainer;
import com.xuggle.xuggler.IStream;
import com.xuggle.xuggler.IStreamCoder;
/**
* Class used to play {@link XugglerPlayableMedia}.
* <p>
* This class uses a number of threads to read and playback the given media.
* @author William Bittle
* @version 2.0.1
* @since 2.0.0
*/
public class XugglerMediaPlayer implements MediaPlayer<XugglerPlayableMedia> {
/** The class level logger */
private static final Logger LOGGER = Logger.getLogger(XugglerMediaPlayer.class);
/** The state of the media player */
protected State state;
/** The player configuration */
protected MediaPlayerConfiguration configuration;
/** The list of media player listeners */
protected List<MediaPlayerListener> listeners;
// the media
/** The media to play */
protected XugglerPlayableMedia media;
// threads
/** The media reader thread */
protected XugglerMediaReaderThread mediaReaderThread;
/** The media player thread */
protected XugglerMediaPlayerThread mediaPlayerThread;
/** The audio player thread */
protected XugglerAudioPlayerThread audioPlayerThread;
/**
* Default constructor.
*/
public XugglerMediaPlayer() {
this.state = State.STOPPED;
this.listeners = new ArrayList<>();
this.configuration = new MediaPlayerConfiguration();
// we override the thread classes below to provide the wiring up
// required for them to communicate
// we also override the onStopped methods so that they call the next
// thread to be ended to force them to end in sequence
// create the threads
this.mediaReaderThread = new XugglerMediaReaderThread() {
@Override
protected void queueVideoImage(XugglerVideoData image) {
mediaPlayerThread.queueVideoImage(image);
}
@Override
protected void queueAudioImage(XugglerAudioData samples) {
mediaPlayerThread.queueAudioSamples(samples);
}
@Override
protected void onMediaEnd() {
XugglerMediaPlayer.this.loop();
}
@Override
protected void onThreadStopped() {
super.onThreadStopped();
LOGGER.debug("MediaReaderThread Ended");
mediaPlayerThread.end();
}
};
this.mediaPlayerThread = new XugglerMediaPlayerThread() {
@Override
protected void playVideo(BufferedImage image) {
notifyListeners(image);
}
@Override
protected void playAudio(byte[] samples) {
audioPlayerThread.queue(samples);
}
@Override
protected void onThreadStopped() {
super.onThreadStopped();
LOGGER.debug("MediaPlayerThread Ended");
audioPlayerThread.end();
}
};
this.audioPlayerThread = new XugglerAudioPlayerThread() {
protected void onThreadStopped() {
super.onThreadStopped();
LOGGER.debug("AudioPlayerThread Ended");
onRelease();
}
};
// start the threads
this.audioPlayerThread.start();
this.mediaPlayerThread.start();
this.mediaReaderThread.start();
}
/**
* Initializes the playback of the given media.
* <p>
* Returns true if the media was opened successfully and is ready for playback.
* @param media the media
* @return boolean
*/
private boolean initializeMedia(XugglerPlayableMedia media) {
// assign the media
this.media = media;
// open the media
// create the video container object
IContainer container = IContainer.make();
// open the container format
String filePath = media.getFile().getFullPath();
if (container.open(filePath, IContainer.Type.READ, null) < 0) {
LOGGER.error("Could not open file [" + media.getFile().getRelativePath() + "]. Unsupported container format.");
this.media = null;
if (container != null) {
container.close();
}
return false;
}
LOGGER.debug("Media file opened width container format: " + container.getContainerFormat().getInputFormatLongName());
// query how many streams the call to open found
int numStreams = container.getNumStreams();
LOGGER.debug("Stream count: " + container.getContainerFormat().getInputFormatLongName());
// loop over the streams to find the first video stream
IStreamCoder videoCoder = null;
IStreamCoder audioCoder = null;
for (int i = 0; i < numStreams; i++) {
IStream stream = container.getStream(i);
// get the coder for the stream
IStreamCoder coder = stream.getStreamCoder();
// see if the coder is a video coder
if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
// if so, break from the loop
videoCoder = coder;
}
if (stream.getStreamCoder().getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
audioCoder = coder;
}
}
if (videoCoder == null && audioCoder == null) {
LOGGER.error("No audio or video stream found.");
this.media = null;
if (container != null) {
container.close();
}
return false;
}
// see if we have a video stream
if (videoCoder != null) {
// open the coder to read the video data
String codecName = "Unknown";
ICodec codec = videoCoder.getCodec();
if (codec != null) {
codecName = codec.getLongName();
}
if (videoCoder.open(null, null) < 0) {
LOGGER.error("Could not open video decoder for: " + codecName);
this.media = null;
if (container != null) {
container.close();
}
return false;
}
LOGGER.debug("Video coder opened with format: " + codecName);
} else {
LOGGER.debug("No video stream in container.");
}
// see if we have an audio stream
if (audioCoder != null) {
String codecName = "Unknown";
ICodec codec = audioCoder.getCodec();
if (codec != null) {
codecName = codec.getLongName();
}
if (audioCoder.open(null, null) < 0) {
LOGGER.error("Could not open audio decoder for: " + codecName);
this.media = null;
if (container != null) {
container.close();
}
return false;
}
LOGGER.debug("Audio coder opened with format: " + codecName);
} else {
LOGGER.debug("No audio stream in container.");
}
// initialize the playback threads
int audioConversions = this.audioPlayerThread.initialize(audioCoder);
// make sure the initialization worked (-1 if it didnt)
if (audioConversions >= 0 && audioConversions != XugglerAudioData.CONVERSION_NONE) {
List<String> conversions = new ArrayList<String>();
if ((audioConversions & XugglerAudioData.CONVERSION_TO_BIT_DEPTH_16) == XugglerAudioData.CONVERSION_TO_BIT_DEPTH_16) {
conversions.add("BitDepth[" + (int)IAudioSamples.findSampleBitDepth(audioCoder.getSampleFormat()) + " to 16]");
}
if ((audioConversions & XugglerAudioData.CONVERSION_TO_STEREO) == XugglerAudioData.CONVERSION_TO_STEREO) {
conversions.add("Channels[" + audioCoder.getChannels() + " to 2]");
}
LOGGER.info("Audio conversions [" + StringUtils.join(conversions, ",") + "] required for audio in: " + media.getFile().getFullPath());
}
this.mediaPlayerThread.initialize(videoCoder != null, audioCoder != null);
this.mediaReaderThread.initialize(container, videoCoder, audioCoder, audioConversions);
return true;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#getMedia()
*/
@Override
public XugglerPlayableMedia getMedia() {
return this.media;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#setMedia(org.praisenter.media.PlayableMedia)
*/
@Override
public boolean setMedia(XugglerPlayableMedia media) {
if (media == null) {
return false;
}
// stop any playback
this.stop();
// assign the media
return this.initializeMedia(media);
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#getConfiguration()
*/
@Override
public MediaPlayerConfiguration getConfiguration() {
return new MediaPlayerConfiguration(this.configuration);
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#setConfiguration(org.praisenter.media.MediaPlayerConfiguration)
*/
@Override
public void setConfiguration(MediaPlayerConfiguration configuration) {
this.configuration = configuration;
this.audioPlayerThread.setVolume(configuration.getVolume());
this.audioPlayerThread.setMuted(configuration.isAudioMuted());
this.mediaReaderThread.setOutputDimensions(configuration.getWidth(), configuration.getHeight());
this.mediaReaderThread.setVideoConversionEnabled(configuration.isReadTimeVideoConversionEnabled());
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#play()
*/
@Override
public void play() {
if (this.media != null) {
this.state = State.PLAYING;
this.setPaused(false);
LOGGER.debug("Playing");
}
}
/**
* Pauses or unpauses the media threads.
* @param flag true if the threads should be paused
*/
private void setPaused(boolean flag) {
this.audioPlayerThread.setPaused(flag);
this.mediaPlayerThread.setPaused(flag);
this.mediaReaderThread.setPaused(flag);
}
/**
* Stops the current playback and seeks to the beginning and
* beings playback.
*/
private void loop() {
// stop, but drain whats left
boolean reset = stop(true);
// check if we should loop
if (this.configuration.isLoopEnabled()) {
// make sure we were able to reset
// the media to its start position
if (reset) {
LOGGER.debug("Looping");
play();
return;
}
LOGGER.warn("Loop failed, stopping media playback.");
}
// if we don't loop (or it failed) then we need to pause all the threads
this.audioPlayerThread.setPaused(true);
this.mediaPlayerThread.setPaused(true);
this.mediaReaderThread.setPaused(true);
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#pause()
*/
@Override
public void pause() {
if (this.state == State.PLAYING) {
this.state = State.PAUSED;
this.setPaused(true);
LOGGER.debug("Paused");
}
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#resume()
*/
@Override
public void resume() {
if (this.state == State.PAUSED) {
this.state = State.PLAYING;
this.setPaused(false);
LOGGER.debug("Resumed");
}
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#stop()
*/
@Override
public void stop() {
this.stop(false);
}
/**
* Stops the playback of the media optionally draining or
* flushing any remaining audio/video frames.
* <p>
* Returns true if the media was successfully reset to the
* beginning of the media.
* @param drain true if the queued media should be drained
* @return boolean
*/
private boolean stop(boolean drain) {
// if we are paused or playing we can stop the media and reset it
if (this.state == State.PLAYING || this.state == State.PAUSED) {
this.state = State.STOPPED;
// only pause the reading thread
this.mediaReaderThread.setPaused(true);
LOGGER.debug("Seeking");
boolean looped = this.mediaReaderThread.loop();
if (drain) {
LOGGER.debug("Draining");
this.mediaPlayerThread.drain();
this.audioPlayerThread.drain();
} else {
LOGGER.debug("Flushing");
this.mediaPlayerThread.flush();
this.audioPlayerThread.flush();
}
LOGGER.debug("Stopped");
return looped;
}
return true;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#seek(long)
*/
@Override
public void seek(long position) {
// FIXME implement seeking
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#getPosition()
*/
@Override
public long getPosition() {
// FIXME implement seeking
return 0;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#release()
*/
@Override
public void release() {
this.stop();
this.state = State.ENDED;
this.listeners = null;
// we overrode the end method of the reader class in
// our anonymous inner class to call the end() methods
// in sequence
if (this.mediaReaderThread != null) {
this.mediaReaderThread.end();
}
}
/**
* Called when the last thread of this player has been released.
*/
protected void onRelease() {
this.mediaReaderThread = null;
this.mediaPlayerThread = null;
this.audioPlayerThread = null;
this.configuration = null;
this.listeners = null;
this.media = null;
LOGGER.debug("Released");
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#isPaused()
*/
@Override
public boolean isPaused() {
return this.state == State.PAUSED;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#isPlaying()
*/
@Override
public boolean isPlaying() {
return this.state == State.PLAYING;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#isStopped()
*/
@Override
public boolean isStopped() {
return this.state == State.STOPPED;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#addMediaPlayerListener(org.praisenter.media.MediaPlayerListener)
*/
@Override
public void addMediaPlayerListener(MediaPlayerListener listener) {
this.listeners.add(listener);
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#removeMediaPlayerListener(org.praisenter.media.MediaPlayerListener)
*/
@Override
public boolean removeMediaPlayerListener(MediaPlayerListener listener) {
return this.listeners.remove(listener);
}
/**
* Notifies any listeners of the video image event.
* @param image the video image
*/
private void notifyListeners(BufferedImage image) {
if (this.listeners != null) {
for (MediaPlayerListener listener : this.listeners) {
if (listener instanceof VideoMediaPlayerListener) {
((VideoMediaPlayerListener)listener).onVideoImage(image);
}
}
}
}
}
| gpl/org/praisenter/media/player/XugglerMediaPlayer.java | /*
* Praisenter: A free open source church presentation software.
* Copyright (C) 2012-2013 William Bittle http://www.praisenter.org/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.praisenter.media.player;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.praisenter.media.MediaPlayer;
import org.praisenter.media.MediaPlayerConfiguration;
import org.praisenter.media.MediaPlayerListener;
import org.praisenter.media.VideoMediaPlayerListener;
import org.praisenter.media.XugglerPlayableMedia;
import com.xuggle.xuggler.IAudioSamples;
import com.xuggle.xuggler.ICodec;
import com.xuggle.xuggler.IContainer;
import com.xuggle.xuggler.IStream;
import com.xuggle.xuggler.IStreamCoder;
/**
* Class used to play {@link XugglerPlayableMedia}.
* <p>
* This class uses a number of threads to read and playback the given media.
* @author William Bittle
* @version 2.0.1
* @since 2.0.0
*/
public class XugglerMediaPlayer implements MediaPlayer<XugglerPlayableMedia> {
/** The class level logger */
private static final Logger LOGGER = Logger.getLogger(XugglerMediaPlayer.class);
/** The state of the media player */
protected State state;
/** The player configuration */
protected MediaPlayerConfiguration configuration;
/** The list of media player listeners */
protected List<MediaPlayerListener> listeners;
// the media
/** The media to play */
protected XugglerPlayableMedia media;
// threads
/** The media reader thread */
protected XugglerMediaReaderThread mediaReaderThread;
/** The media player thread */
protected XugglerMediaPlayerThread mediaPlayerThread;
/** The audio player thread */
protected XugglerAudioPlayerThread audioPlayerThread;
/**
* Default constructor.
*/
public XugglerMediaPlayer() {
this.state = State.STOPPED;
this.listeners = new ArrayList<>();
this.configuration = new MediaPlayerConfiguration();
// we override the thread classes below to provide the wiring up
// required for them to communicate
// we also override the onStopped methods so that they call the next
// thread to be ended to force them to end in sequence
// create the threads
this.mediaReaderThread = new XugglerMediaReaderThread() {
@Override
protected void queueVideoImage(XugglerVideoData image) {
mediaPlayerThread.queueVideoImage(image);
}
@Override
protected void queueAudioImage(XugglerAudioData samples) {
mediaPlayerThread.queueAudioSamples(samples);
}
@Override
protected void onMediaEnd() {
XugglerMediaPlayer.this.loop();
}
@Override
protected void onThreadStopped() {
super.onThreadStopped();
LOGGER.debug("MediaReaderThread Ended");
mediaPlayerThread.end();
}
};
this.mediaPlayerThread = new XugglerMediaPlayerThread() {
@Override
protected void playVideo(BufferedImage image) {
notifyListeners(image);
}
@Override
protected void playAudio(byte[] samples) {
audioPlayerThread.queue(samples);
}
@Override
protected void onThreadStopped() {
super.onThreadStopped();
LOGGER.debug("MediaPlayerThread Ended");
audioPlayerThread.end();
}
};
this.audioPlayerThread = new XugglerAudioPlayerThread() {
protected void onThreadStopped() {
super.onThreadStopped();
LOGGER.debug("AudioPlayerThread Ended");
onRelease();
}
};
// start the threads
this.audioPlayerThread.start();
this.mediaPlayerThread.start();
this.mediaReaderThread.start();
}
/**
* Initializes the playback of the given media.
* <p>
* Returns true if the media was opened successfully and is ready for playback.
* @param media the media
* @return boolean
*/
private boolean initializeMedia(XugglerPlayableMedia media) {
// assign the media
this.media = media;
// open the media
// create the video container object
IContainer container = IContainer.make();
// open the container format
String filePath = media.getFile().getFullPath();
if (container.open(filePath, IContainer.Type.READ, null) < 0) {
LOGGER.error("Could not open file [" + media.getFile().getRelativePath() + "]. Unsupported container format.");
this.media = null;
if (container != null) {
container.close();
}
return false;
}
LOGGER.debug("Media file opened width container format: " + container.getContainerFormat().getInputFormatLongName());
// query how many streams the call to open found
int numStreams = container.getNumStreams();
LOGGER.debug("Stream count: " + container.getContainerFormat().getInputFormatLongName());
// loop over the streams to find the first video stream
IStreamCoder videoCoder = null;
IStreamCoder audioCoder = null;
for (int i = 0; i < numStreams; i++) {
IStream stream = container.getStream(i);
// get the coder for the stream
IStreamCoder coder = stream.getStreamCoder();
// see if the coder is a video coder
if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
// if so, break from the loop
videoCoder = coder;
}
if (stream.getStreamCoder().getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
audioCoder = coder;
}
}
if (videoCoder == null && audioCoder == null) {
LOGGER.error("No audio or video stream found.");
this.media = null;
if (container != null) {
container.close();
}
return false;
}
// see if we have a video stream
if (videoCoder != null) {
// open the coder to read the video data
String codecName = "Unknown";
ICodec codec = videoCoder.getCodec();
if (codec != null) {
codecName = codec.getLongName();
}
if (videoCoder.open(null, null) < 0) {
LOGGER.error("Could not open video decoder for: " + codecName);
this.media = null;
if (container != null) {
container.close();
}
return false;
}
LOGGER.debug("Video coder opened with format: " + codecName);
} else {
LOGGER.debug("No video stream in container.");
}
// see if we have an audio stream
if (audioCoder != null) {
String codecName = "Unknown";
ICodec codec = audioCoder.getCodec();
if (codec != null) {
codecName = codec.getLongName();
}
if (audioCoder.open(null, null) < 0) {
LOGGER.error("Could not open audio decoder for: " + codecName);
this.media = null;
if (container != null) {
container.close();
}
return false;
}
LOGGER.debug("Audio coder opened with format: " + codecName);
} else {
LOGGER.debug("No audio stream in container.");
}
// initialize the playback threads
int audioConversions = this.audioPlayerThread.initialize(audioCoder);
if (audioConversions != XugglerAudioData.CONVERSION_NONE) {
List<String> conversions = new ArrayList<String>();
if ((audioConversions & XugglerAudioData.CONVERSION_TO_BIT_DEPTH_16) == XugglerAudioData.CONVERSION_TO_BIT_DEPTH_16) {
conversions.add("BitDepth[" + (int)IAudioSamples.findSampleBitDepth(audioCoder.getSampleFormat()) + " to 16]");
}
if ((audioConversions & XugglerAudioData.CONVERSION_TO_STEREO) == XugglerAudioData.CONVERSION_TO_STEREO) {
conversions.add("Channels[" + audioCoder.getChannels() + " to 2]");
}
LOGGER.info("Audio conversions [" + StringUtils.join(conversions, ",") + "] required for audio in: " + media.getFile().getFullPath());
}
this.mediaPlayerThread.initialize(videoCoder != null, audioCoder != null);
this.mediaReaderThread.initialize(container, videoCoder, audioCoder, audioConversions);
return true;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#getMedia()
*/
@Override
public XugglerPlayableMedia getMedia() {
return this.media;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#setMedia(org.praisenter.media.PlayableMedia)
*/
@Override
public boolean setMedia(XugglerPlayableMedia media) {
if (media == null) {
return false;
}
// stop any playback
this.stop();
// assign the media
return this.initializeMedia(media);
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#getConfiguration()
*/
@Override
public MediaPlayerConfiguration getConfiguration() {
return new MediaPlayerConfiguration(this.configuration);
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#setConfiguration(org.praisenter.media.MediaPlayerConfiguration)
*/
@Override
public void setConfiguration(MediaPlayerConfiguration configuration) {
this.configuration = configuration;
this.audioPlayerThread.setVolume(configuration.getVolume());
this.audioPlayerThread.setMuted(configuration.isAudioMuted());
this.mediaReaderThread.setOutputDimensions(configuration.getWidth(), configuration.getHeight());
this.mediaReaderThread.setVideoConversionEnabled(configuration.isReadTimeVideoConversionEnabled());
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#play()
*/
@Override
public void play() {
if (this.media != null) {
this.state = State.PLAYING;
this.setPaused(false);
LOGGER.debug("Playing");
}
}
/**
* Pauses or unpauses the media threads.
* @param flag true if the threads should be paused
*/
private void setPaused(boolean flag) {
this.audioPlayerThread.setPaused(flag);
this.mediaPlayerThread.setPaused(flag);
this.mediaReaderThread.setPaused(flag);
}
/**
* Stops the current playback and seeks to the beginning and
* beings playback.
*/
private void loop() {
// stop, but drain whats left
boolean reset = stop(true);
// check if we should loop
if (this.configuration.isLoopEnabled()) {
// make sure we were able to reset
// the media to its start position
if (reset) {
LOGGER.debug("Looping");
play();
return;
}
LOGGER.warn("Loop failed, stopping media playback.");
}
// if we don't loop (or it failed) then we need to pause all the threads
this.audioPlayerThread.setPaused(true);
this.mediaPlayerThread.setPaused(true);
this.mediaReaderThread.setPaused(true);
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#pause()
*/
@Override
public void pause() {
if (this.state == State.PLAYING) {
this.state = State.PAUSED;
this.setPaused(true);
LOGGER.debug("Paused");
}
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#resume()
*/
@Override
public void resume() {
if (this.state == State.PAUSED) {
this.state = State.PLAYING;
this.setPaused(false);
LOGGER.debug("Resumed");
}
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#stop()
*/
@Override
public void stop() {
this.stop(false);
}
/**
* Stops the playback of the media optionally draining or
* flushing any remaining audio/video frames.
* <p>
* Returns true if the media was successfully reset to the
* beginning of the media.
* @param drain true if the queued media should be drained
* @return boolean
*/
private boolean stop(boolean drain) {
// if we are paused or playing we can stop the media and reset it
if (this.state == State.PLAYING || this.state == State.PAUSED) {
this.state = State.STOPPED;
// only pause the reading thread
this.mediaReaderThread.setPaused(true);
LOGGER.debug("Seeking");
boolean looped = this.mediaReaderThread.loop();
if (drain) {
LOGGER.debug("Draining");
this.mediaPlayerThread.drain();
this.audioPlayerThread.drain();
} else {
LOGGER.debug("Flushing");
this.mediaPlayerThread.flush();
this.audioPlayerThread.flush();
}
LOGGER.debug("Stopped");
return looped;
}
return true;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#seek(long)
*/
@Override
public void seek(long position) {
// FIXME implement seeking
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#getPosition()
*/
@Override
public long getPosition() {
// FIXME implement seeking
return 0;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#release()
*/
@Override
public void release() {
this.stop();
this.state = State.ENDED;
this.listeners = null;
// we overrode the end method of the reader class in
// our anonymous inner class to call the end() methods
// in sequence
if (this.mediaReaderThread != null) {
this.mediaReaderThread.end();
}
}
/**
* Called when the last thread of this player has been released.
*/
protected void onRelease() {
this.mediaReaderThread = null;
this.mediaPlayerThread = null;
this.audioPlayerThread = null;
this.configuration = null;
this.listeners = null;
this.media = null;
LOGGER.debug("Released");
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#isPaused()
*/
@Override
public boolean isPaused() {
return this.state == State.PAUSED;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#isPlaying()
*/
@Override
public boolean isPlaying() {
return this.state == State.PLAYING;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#isStopped()
*/
@Override
public boolean isStopped() {
return this.state == State.STOPPED;
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#addMediaPlayerListener(org.praisenter.media.MediaPlayerListener)
*/
@Override
public void addMediaPlayerListener(MediaPlayerListener listener) {
this.listeners.add(listener);
}
/* (non-Javadoc)
* @see org.praisenter.media.MediaPlayer#removeMediaPlayerListener(org.praisenter.media.MediaPlayerListener)
*/
@Override
public boolean removeMediaPlayerListener(MediaPlayerListener listener) {
return this.listeners.remove(listener);
}
/**
* Notifies any listeners of the video image event.
* @param image the video image
*/
private void notifyListeners(BufferedImage image) {
if (this.listeners != null) {
for (MediaPlayerListener listener : this.listeners) {
if (listener instanceof VideoMediaPlayerListener) {
((VideoMediaPlayerListener)listener).onVideoImage(image);
}
}
}
}
}
| Fixed a NPE bug when a video had no audio | gpl/org/praisenter/media/player/XugglerMediaPlayer.java | Fixed a NPE bug when a video had no audio | <ide><path>pl/org/praisenter/media/player/XugglerMediaPlayer.java
<ide>
<ide> // initialize the playback threads
<ide> int audioConversions = this.audioPlayerThread.initialize(audioCoder);
<del> if (audioConversions != XugglerAudioData.CONVERSION_NONE) {
<add> // make sure the initialization worked (-1 if it didnt)
<add> if (audioConversions >= 0 && audioConversions != XugglerAudioData.CONVERSION_NONE) {
<ide> List<String> conversions = new ArrayList<String>();
<ide> if ((audioConversions & XugglerAudioData.CONVERSION_TO_BIT_DEPTH_16) == XugglerAudioData.CONVERSION_TO_BIT_DEPTH_16) {
<ide> conversions.add("BitDepth[" + (int)IAudioSamples.findSampleBitDepth(audioCoder.getSampleFormat()) + " to 16]"); |
|
JavaScript | agpl-3.0 | aac0467d03163a0abd91c447146c0012cc821bca | 0 | ONLYOFFICE/web-apps,ONLYOFFICE/web-apps,ONLYOFFICE/web-apps,ONLYOFFICE/web-apps | /*
*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
/**
* FormulaDialog.js
*
* Formula Dialog Controller
*
* Created by Alexey.Musinov on 14/04/2014
* Copyright (c) 2018 Ascensio System SIA. All rights reserved.
*
*/
define([
'core',
'spreadsheeteditor/main/app/collection/FormulaGroups',
'spreadsheeteditor/main/app/view/FormulaDialog',
'spreadsheeteditor/main/app/view/FormulaTab'
], function () {
'use strict';
SSE.Controllers = SSE.Controllers || {};
SSE.Controllers.FormulaDialog = Backbone.Controller.extend(_.extend({
models: [],
views: [
'FormulaDialog',
'FormulaTab'
],
collections: [
'FormulaGroups'
],
initialize: function () {
var me = this;
me.langJson = {};
me.langDescJson = {};
this.addListeners({
'FileMenu': {
'settings:apply': function() {
if (!me.mode || !me.mode.isEdit) return;
me.needUpdateFormula = true;
var lang = Common.localStorage.getItem("sse-settings-func-locale");
Common.Utils.InternalSettings.set("sse-settings-func-locale", lang);
me.formulasGroups.reset();
me.reloadTranslations(lang);
}
},
'FormulaTab': {
'function:apply': this.applyFunction
},
'Toolbar': {
'function:apply': this.applyFunction,
'tab:active': this.onTabActive
}
});
},
applyFunction: function(func, autocomplete, group) {
if (func) {
if (func.origin === 'more') {
this.showDialog(group);
} else {
this.api.asc_insertFormula(func.name, Asc.c_oAscPopUpSelectorType.Func, !!autocomplete);
!autocomplete && this.updateLast10Formulas(func.origin);
}
}
},
setConfig: function(config) {
this.toolbar = config.toolbar;
this.formulaTab = this.createView('FormulaTab', {
toolbar: this.toolbar.toolbar,
formulasGroups: this.formulasGroups
});
return this;
},
setApi: function (api) {
this.api = api;
if (this.formulasGroups && this.api) {
Common.Utils.InternalSettings.set("sse-settings-func-last", Common.localStorage.getItem("sse-settings-func-last"));
this.reloadTranslations(Common.localStorage.getItem("sse-settings-func-locale") || this.appOptions.lang, true);
var me = this;
this.formulas = new SSE.Views.FormulaDialog({
api : this.api,
toolclose : 'hide',
formulasGroups : this.formulasGroups,
handler : _.bind(this.applyFunction, this)
});
this.formulas.on({
'hide': function () {
me.api.asc_enableKeyEvents(true);
}
});
}
this.formulaTab && this.formulaTab.setApi(this.api);
return this;
},
setMode: function(mode) {
this.mode = mode;
return this;
},
onLaunch: function () {
this.formulasGroups = this.getApplication().getCollection('FormulaGroups');
var descriptions = ['Financial', 'Logical', 'TextAndData', 'DateAndTime', 'LookupAndReference', 'Mathematic', 'Cube', 'Database', 'Engineering', 'Information',
'Statistical', 'Last10'];
Common.Gateway.on('init', this.loadConfig.bind(this));
},
loadConfig: function(data) {
this.appOptions = {};
this.appOptions.lang = data.config.lang;
},
reloadTranslations: function (lang, suppressEvent) {
var me = this;
lang = (lang || 'en').split(/[\-_]/)[0].toLowerCase();
Common.Utils.InternalSettings.set("sse-settings-func-locale", lang);
if (me.langJson[lang]) {
me.api.asc_setLocalization(me.langJson[lang]);
Common.NotificationCenter.trigger('formula:settings', this);
} else if (lang == 'en') {
me.api.asc_setLocalization(undefined);
Common.NotificationCenter.trigger('formula:settings', this);
} else {
Common.Utils.loadConfig('resources/formula-lang/' + lang + '.json',
function (config) {
if ( config != 'error' ) {
me.langJson[lang] = config;
me.api.asc_setLocalization(config);
Common.NotificationCenter.trigger('formula:settings', this);
}
});
}
if (me.langDescJson[lang])
me.loadingFormulas(me.langDescJson[lang], suppressEvent);
else {
Common.Utils.loadConfig('resources/formula-lang/' + lang + '_desc.json',
function (config) {
if ( config != 'error' ) {
me.langDescJson[lang] = config;
me.loadingFormulas(config, suppressEvent);
} else {
Common.Utils.loadConfig('resources/formula-lang/en_desc.json',
function (config) {
me.langDescJson[lang] = (config != 'error') ? config : null;
me.loadingFormulas(me.langDescJson[lang], suppressEvent);
});
}
});
}
},
getDescription: function(lang) {
if (!lang) return '';
lang = lang.toLowerCase() ;
if (this.langDescJson[lang])
return this.langDescJson[lang];
return null;
},
showDialog: function (group) {
if (this.formulas) {
if ( this.needUpdateFormula ) {
this.needUpdateFormula = false;
if (this.formulas.$window) {
this.formulas.fillFormulasGroups();
}
}
this.formulas.show(group);
}
},
hideDialog: function () {
if (this.formulas && this.formulas.isVisible()) {
this.formulas.hide();
}
},
updateLast10Formulas: function(formula) {
var arr = Common.Utils.InternalSettings.get("sse-settings-func-last") || 'SUM;AVERAGE;IF;HYPERLINK;COUNT;MAX;SIN;SUMIF;PMT;STDEV';
arr = arr.split(';');
var idx = _.indexOf(arr, formula);
arr.splice((idx<0) ? arr.length-1 : idx, 1);
arr.unshift(formula);
var val = arr.join(';');
Common.localStorage.setItem("sse-settings-func-last", val);
Common.Utils.InternalSettings.set("sse-settings-func-last", val);
if (this.formulasGroups) {
var group = this.formulasGroups.findWhere({name : 'Last10'});
group && group.set('functions', this.loadingLast10Formulas(this.getDescription(Common.Utils.InternalSettings.get("sse-settings-func-locale"))));
this.formulaTab && this.formulaTab.updateRecent();
}
},
loadingLast10Formulas: function(descrarr) {
var arr = (Common.Utils.InternalSettings.get("sse-settings-func-last") || 'SUM;AVERAGE;IF;HYPERLINK;COUNT;MAX;SIN;SUMIF;PMT;STDEV').split(';'),
separator = this.api.asc_getFunctionArgumentSeparator(),
functions = [];
for (var j = 0; j < arr.length; j++) {
var funcname = arr[j];
functions.push(new SSE.Models.FormulaModel({
index : j,
group : 'Last10',
name : this.api.asc_getFormulaLocaleName(funcname),
origin: funcname,
args : ((descrarr && descrarr[funcname]) ? descrarr[funcname].a : '').replace(/[,;]/g, separator),
desc : (descrarr && descrarr[funcname]) ? descrarr[funcname].d : ''
}));
}
return functions;
},
loadingFormulas: function (descrarr, suppressEvent) {
var i = 0, j = 0,
ascGroupName,
ascFunctions,
functions,
store = this.formulasGroups,
formulaGroup = null,
index = 0,
funcInd = 0,
info = null,
allFunctions = [],
allFunctionsGroup = null,
last10FunctionsGroup = null,
separator = this.api.asc_getFunctionArgumentSeparator();
if (store) {
ascGroupName = 'Last10';
last10FunctionsGroup = new SSE.Models.FormulaGroup ({
name : ascGroupName,
index : index,
store : store,
caption : this['sCategory' + ascGroupName] || ascGroupName
});
if (last10FunctionsGroup) {
last10FunctionsGroup.set('functions', this.loadingLast10Formulas(descrarr));
store.push(last10FunctionsGroup);
index += 1;
}
ascGroupName = 'All';
allFunctionsGroup = new SSE.Models.FormulaGroup ({
name : ascGroupName,
index : index,
store : store,
caption : this['sCategory' + ascGroupName] || ascGroupName
});
if (allFunctionsGroup) {
store.push(allFunctionsGroup);
index += 1;
}
if (allFunctionsGroup) {
info = this.api.asc_getFormulasInfo();
for (i = 0; i < info.length; i += 1) {
ascGroupName = info[i].asc_getGroupName();
ascFunctions = info[i].asc_getFormulasArray();
formulaGroup = new SSE.Models.FormulaGroup({
name : ascGroupName,
index : index,
store : store,
caption : this['sCategory' + ascGroupName] || ascGroupName
});
index += 1;
functions = [];
for (j = 0; j < ascFunctions.length; j += 1) {
var funcname = ascFunctions[j].asc_getName();
var func = new SSE.Models.FormulaModel({
index : funcInd,
group : ascGroupName,
name : ascFunctions[j].asc_getLocaleName(),
origin: funcname,
args : ((descrarr && descrarr[funcname]) ? descrarr[funcname].a : '').replace(/[,;]/g, separator),
desc : (descrarr && descrarr[funcname]) ? descrarr[funcname].d : ''
});
funcInd += 1;
functions.push(func);
allFunctions.push(func);
}
formulaGroup.set('functions', _.sortBy(functions, function (model) {return model.get('name'); }));
store.push(formulaGroup);
}
allFunctionsGroup.set('functions',
_.sortBy(allFunctions, function (model) {return model.get('name'); }));
}
}
(!suppressEvent || this._formulasInited) && this.formulaTab && this.formulaTab.fillFunctions();
},
onTabActive: function (tab) {
if ( tab == 'formula' && !this._formulasInited && this.formulaTab) {
this.formulaTab.fillFunctions();
this._formulasInited = true;
}
},
sCategoryAll: 'All',
sCategoryLast10: '10 last used',
sCategoryLogical: 'Logical',
sCategoryCube: 'Cube',
sCategoryDatabase: 'Database',
sCategoryDateAndTime: 'Date and time',
sCategoryEngineering: 'Engineering',
sCategoryFinancial: 'Financial',
sCategoryInformation: 'Information',
sCategoryLookupAndReference: 'Lookup and reference',
sCategoryMathematic: 'Math and trigonometry',
sCategoryStatistical: 'Statistical',
sCategoryTextAndData: 'Text and data'
}, SSE.Controllers.FormulaDialog || {}));
});
| apps/spreadsheeteditor/main/app/controller/FormulaDialog.js | /*
*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
/**
* FormulaDialog.js
*
* Formula Dialog Controller
*
* Created by Alexey.Musinov on 14/04/2014
* Copyright (c) 2018 Ascensio System SIA. All rights reserved.
*
*/
define([
'core',
'spreadsheeteditor/main/app/collection/FormulaGroups',
'spreadsheeteditor/main/app/view/FormulaDialog',
'spreadsheeteditor/main/app/view/FormulaTab'
], function () {
'use strict';
SSE.Controllers = SSE.Controllers || {};
SSE.Controllers.FormulaDialog = Backbone.Controller.extend(_.extend({
models: [],
views: [
'FormulaDialog',
'FormulaTab'
],
collections: [
'FormulaGroups'
],
initialize: function () {
var me = this;
me.langJson = {};
me.langDescJson = {};
this.addListeners({
'FileMenu': {
'settings:apply': function() {
if (!me.mode || !me.mode.isEdit) return;
me.needUpdateFormula = true;
var lang = Common.localStorage.getItem("sse-settings-func-locale");
Common.Utils.InternalSettings.set("sse-settings-func-locale", lang);
me.formulasGroups.reset();
me.reloadTranslations(lang);
}
},
'FormulaTab': {
'function:apply': this.applyFunction
},
'Toolbar': {
'function:apply': this.applyFunction,
'tab:active': this.onTabActive
}
});
},
applyFunction: function(func, autocomplete, group) {
if (func) {
if (func.origin === 'more') {
this.showDialog(group);
} else {
this.api.asc_insertFormula(func.name, Asc.c_oAscPopUpSelectorType.Func, !!autocomplete);
!autocomplete && this.updateLast10Formulas(func.origin);
}
}
},
setConfig: function(config) {
this.toolbar = config.toolbar;
this.formulaTab = this.createView('FormulaTab', {
toolbar: this.toolbar.toolbar,
formulasGroups: this.formulasGroups
});
return this;
},
setApi: function (api) {
this.api = api;
if (this.formulasGroups && this.api) {
Common.Utils.InternalSettings.set("sse-settings-func-last", Common.localStorage.getItem("sse-settings-func-last"));
this.reloadTranslations(Common.localStorage.getItem("sse-settings-func-locale") || this.appOptions.lang, true);
var me = this;
this.formulas = new SSE.Views.FormulaDialog({
api : this.api,
toolclose : 'hide',
formulasGroups : this.formulasGroups,
handler : _.bind(this.applyFunction, this)
});
this.formulas.on({
'hide': function () {
me.api.asc_enableKeyEvents(true);
}
});
}
this.formulaTab && this.formulaTab.setApi(this.api);
return this;
},
setMode: function(mode) {
this.mode = mode;
return this;
},
onLaunch: function () {
this.formulasGroups = this.getApplication().getCollection('FormulaGroups');
var descriptions = ['Financial', 'Logical', 'TextAndData', 'DateAndTime', 'LookupAndReference', 'Mathematic', 'Cube', 'Database', 'Engineering', 'Information',
'Statistical', 'Last10'];
Common.Gateway.on('init', this.loadConfig.bind(this));
},
loadConfig: function(data) {
this.appOptions = {};
this.appOptions.lang = data.config.lang;
},
reloadTranslations: function (lang, suppressEvent) {
var me = this;
lang = (lang || 'en').split(/[\-_]/)[0].toLowerCase();
Common.Utils.InternalSettings.set("sse-settings-func-locale", lang);
if (me.langJson[lang]) {
me.api.asc_setLocalization(me.langJson[lang]);
Common.NotificationCenter.trigger('formula:settings', this);
} else if (lang == 'en') {
me.api.asc_setLocalization(undefined);
Common.NotificationCenter.trigger('formula:settings', this);
} else {
Common.Utils.loadConfig('resources/formula-lang/' + lang + '.json',
function (config) {
if ( config != 'error' ) {
me.langJson[lang] = config;
me.api.asc_setLocalization(config);
Common.NotificationCenter.trigger('formula:settings', this);
}
});
}
if (me.langDescJson[lang])
me.loadingFormulas(me.langDescJson[lang], suppressEvent);
else {
Common.Utils.loadConfig('resources/formula-lang/' + lang + '_desc.json',
function (config) {
if ( config != 'error' ) {
me.langDescJson[lang] = config;
me.loadingFormulas(config, suppressEvent);
} else {
Common.Utils.loadConfig('resources/formula-lang/en_desc.json',
function (config) {
me.langDescJson[lang] = (config != 'error') ? config : null;
me.loadingFormulas(me.langDescJson[lang], suppressEvent);
});
}
});
}
},
getDescription: function(lang) {
if (!lang) return '';
lang = lang.toLowerCase() ;
if (this.langDescJson[lang])
return this.langDescJson[lang];
return null;
},
showDialog: function (group) {
if (this.formulas) {
if ( this.needUpdateFormula ) {
this.needUpdateFormula = false;
if (this.formulas.$window) {
this.formulas.fillFormulasGroups();
}
}
this.formulas.show(group);
}
},
hideDialog: function () {
if (this.formulas && this.formulas.isVisible()) {
this.formulas.hide();
}
},
updateLast10Formulas: function(formula) {
var arr = Common.Utils.InternalSettings.get("sse-settings-func-last") || 'SUM;AVERAGE;IF;HYPERLINK;COUNT;MAX;SIN;SUMIF;PMT;STDEV';
arr = arr.split(';');
var idx = _.indexOf(arr, formula);
arr.splice((idx<0) ? arr.length-1 : idx, 1);
arr.unshift(formula);
var val = arr.join(';');
Common.localStorage.setItem("sse-settings-func-last", val);
Common.Utils.InternalSettings.set("sse-settings-func-last", val);
if (this.formulasGroups) {
var group = this.formulasGroups.findWhere({name : 'Last10'});
group && group.set('functions', this.loadingLast10Formulas(this.getDescription(Common.Utils.InternalSettings.get("sse-settings-func-locale"))));
this.formulaTab && this.formulaTab.updateRecent();
}
},
loadingLast10Formulas: function(descrarr) {
var arr = (Common.Utils.InternalSettings.get("sse-settings-func-last") || 'SUM;AVERAGE;IF;HYPERLINK;COUNT;MAX;SIN;SUMIF;PMT;STDEV').split(';'),
separator = this.api.asc_getFunctionArgumentSeparator(),
functions = [];
for (var j = 0; j < arr.length; j++) {
var funcname = arr[j];
functions.push(new SSE.Models.FormulaModel({
index : j,
group : 'Last10',
name : this.api.asc_getFormulaLocaleName(funcname),
origin: funcname,
args : ((descrarr && descrarr[funcname]) ? descrarr[funcname].a : '').replace(/[,;]/g, separator),
desc : (descrarr && descrarr[funcname]) ? descrarr[funcname].d : ''
}));
}
return functions;
},
loadingFormulas: function (descrarr, suppressEvent) {
var i = 0, j = 0,
ascGroupName,
ascFunctions,
functions,
store = this.formulasGroups,
formulaGroup = null,
index = 0,
funcInd = 0,
info = null,
allFunctions = [],
allFunctionsGroup = null,
last10FunctionsGroup = null,
separator = this.api.asc_getFunctionArgumentSeparator();
if (store) {
ascGroupName = 'Last10';
last10FunctionsGroup = new SSE.Models.FormulaGroup ({
name : ascGroupName,
index : index,
store : store,
caption : this['sCategory' + ascGroupName] || ascGroupName
});
if (last10FunctionsGroup) {
last10FunctionsGroup.set('functions', this.loadingLast10Formulas(descrarr));
store.push(last10FunctionsGroup);
index += 1;
}
ascGroupName = 'All';
allFunctionsGroup = new SSE.Models.FormulaGroup ({
name : ascGroupName,
index : index,
store : store,
caption : this['sCategory' + ascGroupName] || ascGroupName
});
if (allFunctionsGroup) {
store.push(allFunctionsGroup);
index += 1;
}
if (allFunctionsGroup) {
info = this.api.asc_getFormulasInfo();
for (i = 0; i < info.length; i += 1) {
ascGroupName = info[i].asc_getGroupName();
ascFunctions = info[i].asc_getFormulasArray();
formulaGroup = new SSE.Models.FormulaGroup({
name : ascGroupName,
index : index,
store : store,
caption : this['sCategory' + ascGroupName] || ascGroupName
});
index += 1;
functions = [];
for (j = 0; j < ascFunctions.length; j += 1) {
var funcname = ascFunctions[j].asc_getName();
var func = new SSE.Models.FormulaModel({
index : funcInd,
group : ascGroupName,
name : ascFunctions[j].asc_getLocaleName(),
origin: funcname,
args : ((descrarr && descrarr[funcname]) ? descrarr[funcname].a : '').replace(/[,;]/g, separator),
desc : (descrarr && descrarr[funcname]) ? descrarr[funcname].d : ''
});
funcInd += 1;
functions.push(func);
allFunctions.push(func);
}
formulaGroup.set('functions', functions);
store.push(formulaGroup);
}
allFunctionsGroup.set('functions',
_.sortBy(allFunctions, function (model) {return model.get('name'); }));
}
}
(!suppressEvent || this._formulasInited) && this.formulaTab && this.formulaTab.fillFunctions();
},
onTabActive: function (tab) {
if ( tab == 'formula' && !this._formulasInited && this.formulaTab) {
this.formulaTab.fillFunctions();
this._formulasInited = true;
}
},
sCategoryAll: 'All',
sCategoryLast10: '10 last used',
sCategoryLogical: 'Logical',
sCategoryCube: 'Cube',
sCategoryDatabase: 'Database',
sCategoryDateAndTime: 'Date and time',
sCategoryEngineering: 'Engineering',
sCategoryFinancial: 'Financial',
sCategoryInformation: 'Information',
sCategoryLookupAndReference: 'Lookup and reference',
sCategoryMathematic: 'Math and trigonometry',
sCategoryStatistical: 'Statistical',
sCategoryTextAndData: 'Text and data'
}, SSE.Controllers.FormulaDialog || {}));
});
| [SSE] Fix Bug 42510
| apps/spreadsheeteditor/main/app/controller/FormulaDialog.js | [SSE] Fix Bug 42510 | <ide><path>pps/spreadsheeteditor/main/app/controller/FormulaDialog.js
<ide> allFunctions.push(func);
<ide> }
<ide>
<del> formulaGroup.set('functions', functions);
<add> formulaGroup.set('functions', _.sortBy(functions, function (model) {return model.get('name'); }));
<ide> store.push(formulaGroup);
<ide> }
<ide> |
|
Java | apache-2.0 | 1028df468267452c2046d22512140f25c6381427 | 0 | liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.editors.sql;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration;
import org.jkiss.dbeaver.registry.DataSourceUtils;
import org.jkiss.utils.CommonUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Script-to-datasource binding type
*/
public enum SQLScriptBindingType {
EXTERNAL("N/A", "External binding (IDE resources)") {
@Override
public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
// do nothing
}
},
ID("ID", "Connection unique ID") {
@Override
public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
spec.append(DataSourceUtils.PARAM_ID).append("=").append(dataSource.getId());
}
},
NAME("NAME", "Connection name") {
@Override
public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
spec.append(DataSourceUtils.PARAM_NAME).append("=").append(dataSource.getName());
}
},
URL("URL", "Connection URL (jdbc:dbms://host:port/...)") {
@Override
public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
spec.append(DataSourceUtils.PARAM_URL).append("=").append(dataSource.getConnectionConfiguration().getUrl());
}
},
PARAMS("PARAMS", "Connection parameters (name1=value1;name2=value2;...)") {
@Override
public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
DBPConnectionConfiguration cfg = dataSource.getConnectionConfiguration();
Map<String,String> params = new HashMap<>();
if (!CommonUtils.isEmpty(cfg.getServerName())) {
params.put(DataSourceUtils.PARAM_SERVER, cfg.getServerName());
}
if (!CommonUtils.isEmpty(cfg.getHostName())) {
params.put(DataSourceUtils.PARAM_HOST, cfg.getHostName());
}
if (!CommonUtils.isEmpty(cfg.getHostPort())) {
params.put(DataSourceUtils.PARAM_PORT, cfg.getHostPort());
}
if (!CommonUtils.isEmpty(cfg.getDatabaseName())) {
params.put(DataSourceUtils.PARAM_DATABASE, cfg.getDatabaseName());
}
if (!CommonUtils.isEmpty(cfg.getUserName())) {
params.put(DataSourceUtils.PARAM_USER, cfg.getUserName());
}
boolean first = true;
for (Map.Entry<String, String> param : params.entrySet()) {
if (!first) spec.append("|");
spec.append(param.getKey()).append("=").append(param.getValue());
first = false;
}
}
};
private final String name;
private final String description;
SQLScriptBindingType(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public abstract void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec);
}
| plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/editors/sql/SQLScriptBindingType.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.editors.sql;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration;
import org.jkiss.dbeaver.registry.DataSourceUtils;
import org.jkiss.utils.CommonUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Script-to-datasource binding type
*/
public enum SQLScriptBindingType {
EXTERNAL("N/A", "External binding (IDE resources)") {
@Override
public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
// do nothing
}
},
ID("ID", "Connection unique ID") {
@Override
public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
spec.append(DataSourceUtils.PARAM_ID).append("=").append(dataSource.getId());
}
},
NAME("NAME", "Connection name") {
@Override
public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
spec.append(DataSourceUtils.PARAM_NAME).append("=").append(dataSource.getName());
}
},
URL("URL", "DataSource URL (jdbc:dbms://host:port/...)") {
@Override
public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
spec.append(DataSourceUtils.PARAM_URL).append("=").append(dataSource.getConnectionConfiguration().getUrl());
}
},
PARAMS("PARAMS", "DataSource parameters (name1=value1;name2=value2;...)") {
@Override
public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
DBPConnectionConfiguration cfg = dataSource.getConnectionConfiguration();
Map<String,String> params = new HashMap<>();
if (!CommonUtils.isEmpty(cfg.getServerName())) {
params.put(DataSourceUtils.PARAM_SERVER, cfg.getServerName());
}
if (!CommonUtils.isEmpty(cfg.getHostName())) {
params.put(DataSourceUtils.PARAM_HOST, cfg.getHostName());
}
if (!CommonUtils.isEmpty(cfg.getHostPort())) {
params.put(DataSourceUtils.PARAM_PORT, cfg.getHostPort());
}
if (!CommonUtils.isEmpty(cfg.getDatabaseName())) {
params.put(DataSourceUtils.PARAM_DATABASE, cfg.getDatabaseName());
}
if (!CommonUtils.isEmpty(cfg.getUserName())) {
params.put(DataSourceUtils.PARAM_USER, cfg.getUserName());
}
boolean first = true;
for (Map.Entry<String, String> param : params.entrySet()) {
if (!first) spec.append("|");
spec.append(param.getKey()).append("=").append(param.getValue());
first = false;
}
}
};
private final String name;
private final String description;
SQLScriptBindingType(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public abstract void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec);
}
| #3846 Script->connection mapping read/write
| plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/editors/sql/SQLScriptBindingType.java | #3846 Script->connection mapping read/write | <ide><path>lugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/editors/sql/SQLScriptBindingType.java
<ide> spec.append(DataSourceUtils.PARAM_NAME).append("=").append(dataSource.getName());
<ide> }
<ide> },
<del> URL("URL", "DataSource URL (jdbc:dbms://host:port/...)") {
<add> URL("URL", "Connection URL (jdbc:dbms://host:port/...)") {
<ide> @Override
<ide> public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
<ide> spec.append(DataSourceUtils.PARAM_URL).append("=").append(dataSource.getConnectionConfiguration().getUrl());
<ide> }
<ide> },
<del> PARAMS("PARAMS", "DataSource parameters (name1=value1;name2=value2;...)") {
<add> PARAMS("PARAMS", "Connection parameters (name1=value1;name2=value2;...)") {
<ide> @Override
<ide> public void appendSpec(DBPDataSourceContainer dataSource, StringBuilder spec) {
<ide> DBPConnectionConfiguration cfg = dataSource.getConnectionConfiguration(); |
|
Java | apache-2.0 | 53790247cb8013f347748ca60e10791a4ffc895c | 0 | tr3vr/jena,kidaa/jena,kamir/jena,samaitra/jena,samaitra/jena,CesarPantoja/jena,apache/jena,samaitra/jena,apache/jena,kidaa/jena,samaitra/jena,CesarPantoja/jena,apache/jena,tr3vr/jena,kamir/jena,apache/jena,tr3vr/jena,kamir/jena,kamir/jena,kidaa/jena,kamir/jena,CesarPantoja/jena,apache/jena,tr3vr/jena,samaitra/jena,apache/jena,tr3vr/jena,kidaa/jena,kamir/jena,CesarPantoja/jena,apache/jena,CesarPantoja/jena,tr3vr/jena,samaitra/jena,CesarPantoja/jena,tr3vr/jena,kidaa/jena,kidaa/jena,samaitra/jena,apache/jena,kamir/jena,CesarPantoja/jena,kidaa/jena | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.sparql.engine.join;
import java.util.Collection ;
import java.util.Iterator ;
import java.util.List ;
import org.apache.jena.atlas.lib.DS ;
import org.apache.jena.sparql.core.Var ;
/** JoinKey for hash joins */
public final class JoinKey implements Iterable<Var>
{
// Common way to make a JoinKey
/** Make a JoinKey from the intersection of two sets **/
public static JoinKey create(Collection<Var> vars1, Collection<Var> vars2) {
// JoinKeys are generally small so short loops are best.
// vars2 may be smallest e.g. from triple and running accumulator (vars1)
List<Var> intersection = DS.list() ;
for ( Var v : vars1 ) {
if ( vars2.contains(v) )
// First and single key.
return create(v) ;
// Compound keys needs validation : what if they are partial
// i.e. some rows only have part of the join key?
//intersection.add(v) ;
}
return new JoinKey(intersection) ;
}
public static JoinKey create(Var var) {
return new JoinKey(var) ;
}
/** The builder can emit a key every time build() is caller
* and it can be continued to be used.
*/
public static final class Builder {
private List<Var> keys = DS.list() ;
public Builder() { }
public boolean contains(Var var) {
return keys.contains(var) ;
}
public Builder add(Var var) {
// We expect the keys list to be short - a Set is overkill(??)
if ( ! contains(var) )
keys.add(var) ;
return this ;
}
public Builder remove(Var var) {
keys.remove(var) ;
return this ;
}
public Builder clear() { keys.clear() ; return this ; }
public JoinKey build() {
JoinKey joinKey = new JoinKey(DS.list(keys)) ;
return joinKey ;
}
}
// Consider using an array.
private final List<Var> keys ;
private JoinKey(List<Var> _keys) { keys = _keys ; }
private JoinKey(Var var) { keys = DS.listOfOne(var) ; }
public boolean isEmpty() { return keys.isEmpty() ; }
/** Get a single variable for this key.
* For any one key, it always returns the same var */
public Var getVarKey() {
if ( keys.isEmpty() )
return null ;
return keys.get(0) ;
}
@Override
public Iterator<Var> iterator() { return keys.iterator() ; }
@Override
public String toString() {
return keys.toString() ;
}
}
| jena-arq/src/main/java/org/apache/jena/sparql/engine/join/JoinKey.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.sparql.engine.join;
import java.util.Collection ;
import java.util.Iterator ;
import java.util.List ;
import org.apache.jena.atlas.lib.DS ;
import org.apache.jena.sparql.core.Var ;
/** JoinKey for hash joins */
public final class JoinKey implements Iterable<Var>
{
// Common way to make a JoinKey
/** Make a JoinKey from the intersection of two sets **/
public static JoinKey create(Collection<Var> vars1, Collection<Var> vars2) {
// JoinKeys are generally small so short loops are best.
// vars2 may be smallest e.g. from triple and running accumulator (vars1)
List<Var> intersection = DS.list() ;
for ( Var v : vars1 ) {
if ( vars2.contains(v) )
intersection.add(v) ;
}
return new JoinKey(intersection) ;
}
public static JoinKey create(Var var) {
return new JoinKey(var) ;
}
/** The builder can emit a key every time build() is caller
* and it can be continued to be used.
*/
public static final class Builder {
private List<Var> keys = DS.list() ;
public Builder() { }
public boolean contains(Var var) {
return keys.contains(var) ;
}
public Builder add(Var var) {
// We expect the keys list to be short - a Set is overkill(??)
if ( ! contains(var) )
keys.add(var) ;
return this ;
}
public Builder remove(Var var) {
keys.remove(var) ;
return this ;
}
public Builder clear() { keys.clear() ; return this ; }
public JoinKey build() {
JoinKey joinKey = new JoinKey(DS.list(keys)) ;
return joinKey ;
}
}
// Consider using an array.
private final List<Var> keys ;
private JoinKey(List<Var> _keys) { keys = _keys ; }
private JoinKey(Var var) { keys = DS.listOfOne(var) ; }
public boolean isEmpty() { return keys.isEmpty() ; }
/** Get a single variable for this key.
* For any one key, it always returns the same var */
public Var getVarKey() {
if ( keys.isEmpty() )
return null ;
return keys.get(0) ;
}
@Override
public Iterator<Var> iterator() { return keys.iterator() ; }
@Override
public String toString() {
return keys.toString() ;
}
}
| Create single variable join keys. | jena-arq/src/main/java/org/apache/jena/sparql/engine/join/JoinKey.java | Create single variable join keys. | <ide><path>ena-arq/src/main/java/org/apache/jena/sparql/engine/join/JoinKey.java
<ide> List<Var> intersection = DS.list() ;
<ide> for ( Var v : vars1 ) {
<ide> if ( vars2.contains(v) )
<del> intersection.add(v) ;
<add> // First and single key.
<add> return create(v) ;
<add> // Compound keys needs validation : what if they are partial
<add> // i.e. some rows only have part of the join key?
<add> //intersection.add(v) ;
<ide> }
<ide> return new JoinKey(intersection) ;
<ide> } |
|
Java | lgpl-2.1 | 0a5714b6619026766692d36da9ba28bbeae957e8 | 0 | threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya | //
// $Id: DObject.java,v 1.61 2003/03/30 19:38:56 mdb Exp $
package com.threerings.presents.dobj;
import java.lang.reflect.Field;
import java.util.ArrayList;
import com.samskivert.util.ListUtil;
import com.samskivert.util.StringUtil;
import com.threerings.io.Streamable;
import com.threerings.presents.Log;
/**
* The distributed object forms the foundation of the Presents system. All
* information shared among users of the system is done via distributed
* objects. A distributed object has a set of subscribers. These
* subscribers have access to the object or a proxy of the object and
* therefore have access to the data stored in the object's members at all
* times.
*
* <p> When there is any change to that data, initiated by one of the
* subscribers, an event is generated which is dispatched to all
* subscribers of the object, notifying them of that change and affecting
* that change to the copy of the object maintained at each client. In
* this way, both a respository of shared information and a mechanism for
* asynchronous notification are made available as a fundamental
* application building blocks.
*
* <p> To define what information is shared, an application creates a
* distributed object declaration which is much like a class declaration
* except that it is transformed into a proper derived class of
* <code>DObject</code> by a script. A declaration looks something like
* this:
*
* <pre>
* public dclass RoomObject
* {
* public String description;
* public int[] occupants;
* }
* </pre>
*
* which is converted into an actual Java class that looks like this:
*
* <pre>
* public class RoomObject extends DObject
* {
* public String getDescription ()
* {
* // ...
* }
*
* public void setDescription (String description)
* {
* // ...
* }
*
* public int[] getOccupants ()
* {
* // ...
* }
*
* public void setOccupants (int[] occupants)
* {
* // ...
* }
*
* public void setOccupantsAt (int index, int value)
* {
* // ...
* }
* }
* </pre>
*
* These method calls on the actual distributed object will result in the
* proper attribute change events being generated and dispatched.
*
* <p> Note that distributed object fields can only be of a limited set of
* supported types. These types are:
*
* <code><pre>
* byte, short, int, long, float, double
* Byte, Short, Integer, Long, Float, Double, String
* byte[], short[], int[], long[], float[], double[], String[]
* </pre></code>
*/
public class DObject implements Streamable
{
/**
* Returns the object id of this object. All objects in the system
* have a unique object id.
*/
public int getOid ()
{
return _oid;
}
/**
* Don't call this function! Go through the distributed object manager
* instead to ensure that everything is done on the proper thread.
* This function can only safely be called directly when you know you
* are operating on the omgr thread (you are in the middle of a call
* to <code>objectAvailable</code> or to a listener callback).
*
* @see DObjectManager#subscribeToObject
*/
public void addSubscriber (Subscriber sub)
{
// only add the subscriber if they're not already there
Object[] subs = ListUtil.testAndAdd(_subs, sub);
if (subs != null) {
// Log.info("Adding subscriber " + which() + ": " + sub + ".");
_subs = subs;
_scount++;
} else {
Log.warning("Refusing subscriber that's already in the list " +
"[dobj=" + which() + ", subscriber=" + sub + "]");
Thread.dumpStack();
}
}
/**
* Don't call this function! Go through the distributed object manager
* instead to ensure that everything is done on the proper thread.
* This function can only safely be called directly when you know you
* are operating on the omgr thread (you are in the middle of a call
* to <code>objectAvailable</code> or to a listener callback).
*
* @see DObjectManager#unsubscribeFromObject
*/
public void removeSubscriber (Subscriber sub)
{
if (ListUtil.clear(_subs, sub) != null) {
// if we removed something, check to see if we just removed
// the last subscriber from our list; we also want to be sure
// that we're still active otherwise there's no need to notify
// our objmgr because we don't have one
if (--_scount == 0 && _omgr != null) {
_omgr.removedLastSubscriber(this);
}
}
}
/**
* Adds an event listener to this object. The listener will be
* notified when any events are dispatched on this object that match
* their particular listener interface.
*
* <p> Note that the entity adding itself as a listener should have
* obtained the object reference by subscribing to it or should be
* acting on behalf of some other entity that subscribed to the
* object, <em>and</em> that it must be sure to remove itself from the
* listener list (via {@link #removeListener}) when it is done because
* unsubscribing from the object (done by whatever entity subscribed
* in the first place) is not guaranteed to result in the listeners
* added through that subscription being automatically removed (in
* most cases, they definitely will not be removed).
*
* @param listener the listener to be added.
*
* @see EventListener
* @see AttributeChangeListener
* @see SetListener
* @see OidListListener
*/
public void addListener (ChangeListener listener)
{
// only add the listener if they're not already there
Object[] els = ListUtil.testAndAdd(_listeners, listener);
if (els != null) {
_listeners = els;
} else {
// complain if an object requests to add itself more than once
Log.warning("Refusing listener that's already in the list " +
"[dobj=" + which() + ", listener=" + listener + "]");
Thread.dumpStack();
}
}
/**
* Removes an event listener from this object. The listener will no
* longer be notified when events are dispatched on this object.
*
* @param listener the listener to be removed.
*/
public void removeListener (ChangeListener listener)
{
ListUtil.clear(_listeners, listener);
}
/**
* Provides this object with an entity that can be used to validate
* subscription requests and events before they are processed. The
* access controller is handy for ensuring that clients are behaving
* as expected and for preventing impermissible modifications or event
* dispatches on a distributed object.
*/
public void setAccessController (AccessController controller)
{
_controller = controller;
}
/**
* Returns a reference to the access controller in use by this object
* or null if none has been configured.
*/
public AccessController getAccessController ()
{
return _controller;
}
/**
* At times, an entity on the server may need to ensure that events it
* has queued up have made it through the event queue and are applied
* to their respective objects before a service may safely be
* undertaken again. To make this possible, it can acquire a lock on a
* distributed object, generate the events in question and then
* release the lock (via a call to <code>releaseLock</code>) which
* will queue up a final event, the processing of which will release
* the lock. Thus the lock will not be released until all of the
* previously generated events have been processed. If the service is
* invoked again before that lock is released, the associated call to
* <code>acquireLock</code> will fail and the code can respond
* accordingly. An object may have any number of outstanding locks as
* long as they each have a unique name.
*
* @param name the name of the lock to acquire.
*
* @return true if the lock was acquired, false if the lock was not
* acquired because it has not yet been released from a previous
* acquisition.
*
* @see #releaseLock
*/
public boolean acquireLock (String name)
{
// check for the existence of the lock in the list and add it if
// it's not already there
Object[] list = ListUtil.testAndAddEqual(_locks, name);
if (list == null) {
// a null list means the object was already in the list
return false;
} else {
// a non-null list means the object was added
_locks = list;
return true;
}
}
/**
* Queues up an event that when processed will release the lock of the
* specified name.
*
* @see #acquireLock
*/
public void releaseLock (String name)
{
// queue up a release lock event
postEvent(new ReleaseLockEvent(_oid, name));
}
/**
* Don't call this function! It is called by a remove lock event when
* that event is processed and shouldn't be called at any other time.
* If you mean to release a lock that was acquired with
* <code>acquireLock</code> you should be using
* <code>releaseLock</code>.
*
* @see #acquireLock
* @see #releaseLock
*/
protected void clearLock (String name)
{
// clear the lock from the list
if (ListUtil.clearEqual(_locks, name) == null) {
// complain if we didn't find the lock
Log.info("Unable to clear non-existent lock [lock=" + name +
", dobj=" + this + "].");
}
}
/**
* Requests that this distributed object be destroyed. It does so by
* queueing up an object destroyed event which the server will
* validate and process.
*/
public void destroy ()
{
postEvent(new ObjectDestroyedEvent(_oid));
}
/**
* Checks to ensure that the specified subscriber has access to this
* object. This will be called before satisfying a subscription
* request. If an {@link AccessController} has been specified for this
* object, it will be used to determine whether or not to allow the
* subscription request. If no controller is set, the subscription
* will be allowed.
*
* @param sub the subscriber that will subscribe to this object.
*
* @return true if the subscriber has access to the object, false if
* they do not.
*/
public boolean checkPermissions (Subscriber sub)
{
if (_controller != null) {
return _controller.allowSubscribe(this, sub);
} else {
return true;
}
}
/**
* Checks to ensure that this event which is about to be processed,
* has the appropriate permissions. If an {@link AccessController} has
* been specified for this object, it will be used to determine
* whether or not to allow the even dispatch. If no controller is set,
* all events are allowed.
*
* @param event the event that will be dispatched, object permitting.
*
* @return true if the event is valid and should be dispatched, false
* if the event fails the permissions check and should be aborted.
*/
public boolean checkPermissions (DEvent event)
{
if (_controller != null) {
return _controller.allowDispatch(this, event);
} else {
return true;
}
}
/**
* Called by the distributed object manager after it has applied an
* event to this object. This dispatches an event notification to all
* of the subscribers of this object.
*
* @param event the event that was just applied.
*/
public void notifyListeners (DEvent event)
{
// if we have no listeners, we're home free
if (_listeners == null) {
return;
}
// iterate over the listener list, performing the necessary
// notifications
int llength = _listeners.length;
for (int i = 0; i < llength; i++) {
Object listener = _listeners[i];
// skip empty slots
if (listener == null) {
continue;
}
try {
// do any event specific notifications
event.notifyListener(listener);
// and notify them if they are listening for all events
if (listener instanceof EventListener) {
((EventListener)listener).eventReceived(event);
}
} catch (Exception e) {
Log.warning("Listener choked during notification " +
"[listener=" + listener +
", event=" + event + "].");
Log.logStackTrace(e);
}
}
}
/**
* Sets the named attribute to the specified value. This is only used
* by the internals of the event dispatch mechanism and should not be
* called directly by users. Use the generated attribute setter
* methods instead.
*/
public void setAttribute (String name, Object value)
throws ObjectAccessException
{
try {
// for values that contain other values (arrays and DSets), we
// need to clone them before putting them in the object
// because otherwise a subsequent event might come along and
// modify these values before the networking thread has had a
// chance to propagate this event to the clients
// i wish i could just call value.clone() but Object declares
// clone() to be inaccessible, so we must cast the values to
// their actual types to gain access to the widened clone()
// methods
if (value instanceof DSet) {
value = ((DSet)value).clone();
} else if (value instanceof int[]) {
value = ((int[])value).clone();
} else if (value instanceof String[]) {
value = ((String[])value).clone();
} else if (value instanceof byte[]) {
value = ((byte[])value).clone();
} else if (value instanceof long[]) {
value = ((long[])value).clone();
} else if (value instanceof float[]) {
value = ((float[])value).clone();
} else if (value instanceof short[]) {
value = ((short[])value).clone();
} else if (value instanceof double[]) {
value = ((double[])value).clone();
}
// now actually set the value
getClass().getField(name).set(this, value);
} catch (Exception e) {
String errmsg = "Attribute setting failure [name=" + name +
", value=" + value +
", vclass=" + value.getClass().getName() + "].";
throw new ObjectAccessException(errmsg, e);
}
}
/**
* Looks up the named attribute and returns a reference to it. This
* should only be used by the internals of the event dispatch
* mechanism and should not be called directly by users. Use the
* generated attribute getter methods instead.
*/
public Object getAttribute (String name)
throws ObjectAccessException
{
try {
return getClass().getField(name).get(this);
} catch (Exception e) {
String errmsg = "Attribute getting failure [name=" + name + "].";
throw new ObjectAccessException(errmsg, e);
}
}
/**
* Posts a message event on this distrubuted object.
*/
public void postMessage (String name, Object[] args)
{
postEvent(new MessageEvent(_oid, name, args));
}
/**
* Posts the specified event either to our dobject manager or to the
* compound event for which we are currently transacting.
*/
public void postEvent (DEvent event)
{
if (_tevent != null) {
_tevent.postEvent(event);
} else if (_omgr != null) {
_omgr.postEvent(event);
} else {
Log.warning("Unable to post event, object has no omgr " +
"[oid=" + getOid() + ", class=" + getClass().getName() +
", event=" + event + "].");
Thread.dumpStack();
}
}
/**
* Returns true if this object is active and registered with the
* distributed object system. If an object is created via
* <code>DObjectManager.createObject</code> it will be active until
* such time as it is destroyed.
*/
public boolean isActive ()
{
return _omgr != null;
}
/**
* Don't call this function! It initializes this distributed object
* with the supplied distributed object manager. This is called by the
* distributed object manager when an object is created and registered
* with the system.
*
* @see DObjectManager#createObject
*/
public void setManager (DObjectManager omgr)
{
_omgr = omgr;
}
/**
* Don't call this function. It is called by the distributed object
* manager when an object is created and registered with the system.
*
* @see DObjectManager#createObject
*/
public void setOid (int oid)
{
_oid = oid;
}
/**
* Generates a concise string representation of this object.
*/
public String which ()
{
StringBuffer buf = new StringBuffer();
which(buf);
return buf.toString();
}
/**
* Used to briefly describe this distributed object.
*/
protected void which (StringBuffer buf)
{
buf.append(StringUtil.shortClassName(this));
buf.append(":").append(_oid);
}
/**
* Generates a string representation of this object.
*/
public String toString ()
{
StringBuffer buf = new StringBuffer();
toString(buf);
return buf.append("]").toString();
}
/**
* Generates a string representation of this object.
*/
protected void toString (StringBuffer buf)
{
StringUtil.fieldsToString(buf, this, "\n");
if (buf.length() > 0) {
buf.insert(0, "\n");
}
buf.insert(0, _oid);
buf.insert(0, "[oid=");
}
/**
* Begins a transaction on this distributed object. In some
* situations, it is desirable to cause multiple changes to
* distributed object fields in one unified operation. Starting a
* transaction causes all subsequent field modifications to be stored
* in a single compound event which can then be committed, dispatching
* and applying all included events in a single group. Additionally,
* the events are dispatched over the network in a single unit which
* can significantly enhance network efficiency.
*
* <p> When the transaction is complete, the caller must call {@link
* #commitTransaction} or {@link CompoundEvent#commit} to commit the
* transaction and release all involved objects back to their normal
* non-transacting state. If the caller decides not to commit their
* transaction, they must call {@link #cancelTransaction} or {@link
* CompoundEvent#cancel} to cancel the transaction and release all
* involved objects. Failure to do so will cause the pooch to be
* totally screwed.
*
* <p> Note: like all other distributed object operations,
* transactions are not thread safe. It is expected that a single
* thread will handle all distributed object operations and that
* thread will begin and complete a transaction before giving up
* control to unknown code which might try to operate on the
* transacting distributed object (or objects).
*
* <p> Note also: if the object is already engaged in a transaction, a
* transaction participant count will be incremented to note that an
* additional call to {@link #commitTransaction} is required before
* the transaction should actually be committed. Thus <em>every</em>
* call to {@link #startTransaction} must be accompanied by a call to
* either {@link #commitTransaction} or {@link
* #cancelTransaction}. Additionally, if any transaction participant
* cancels the transaction, the entire transaction is cancelled for
* all participants, regardless of whether the other participants
* attempted to commit the transaction.
*
* <p> Note also: nested transactions are not allowed when an object
* is joined to another object's transaction via {@link
* #joinTransaction}.
*
* @return the compound event that encapsulates the transaction. This
* can be ignored if the transaction will be limited to this object,
* but if it is desired that other objects be involved in the
* transaction, the caller will need to pass the {@link CompoundEvent}
* returned by this method to a call to {@link #joinTransaction} on
* the other objects that are involved.
*/
public CompoundEvent startTransaction ()
{
// sanity check
if (!isActive()) {
String errmsg = "Can't start transaction on non-active object " +
"[oid=" + getOid() + ", type=" + getClass().getName() + "]";
throw new IllegalStateException(errmsg);
}
if (_tevent != null) {
// a transaction count of -1 indicates that we're joined to
// another objects transaction that should not allow
// transaction nesting
if (_tcount == -1) {
String errmsg = "Object involved in shared transaction, " +
"nesting not allowed [dobj=" + this + "]";
throw new IllegalStateException(errmsg);
} else {
_tcount++;
}
} else {
_tevent = new CompoundEvent(_omgr);
_tevent.addObject(this);
}
return _tevent;
}
/**
* Causes this object to join the supplied transaction. See {@link
* #startTransaction} for more information on transactions. The
* transaction can be committed by a call to {@link
* #commitTransaction} on any participanting object.
*/
public void joinTransaction (CompoundEvent event)
{
if (_tevent != null) {
String errmsg = "Cannot join transaction while already " +
"transacting [dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
_tevent = event;
_tevent.addObject(this);
_tcount = -1; // make a note that nesting is not allowed
}
/**
* Commits the transaction in which this distributed object is
* involved.
*
* @see CompoundEvent#commit
*/
public void commitTransaction ()
{
if (_tevent == null) {
String errmsg = "Cannot commit: not involved in a transaction " +
"[dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
// if we are nested, we decrement our nesting count rather than
// committing the transaction
if (_tcount > 0) {
_tcount--;
} else {
// we may actually be doing our final commit after someone
// already cancelled this transaction, so we need to perform
// the appropriate action at this point
if (_tcancelled) {
_tevent.cancel();
} else {
_tevent.commit();
}
}
}
/**
* Returns true if this object is in the middle of a transaction or
* false if it is not.
*/
public boolean inTransaction ()
{
return (_tevent != null);
}
/**
* Cancels the transaction in which this distributed object is
* involved.
*
* @see CompoundEvent#cancel
*/
public void cancelTransaction ()
{
if (_tevent == null) {
String errmsg = "Cannot cancel: not involved in a transaction " +
"[dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
// if we're in a nested transaction, make a note that it is to be
// cancelled when all parties commit and decrement the nest count
if (_tcount > 0) {
_tcancelled = true;
_tcount--;
} else {
_tevent.cancel();
}
}
/**
* Removes this object from participation in any transaction in which
* it might be taking part.
*/
protected void clearTransaction ()
{
// sanity check
if (_tcount != 0) {
Log.warning("Transaction cleared with non-zero nesting count " +
"[dobj=" + this + "].");
_tcount = 0;
}
// clear our transaction state
_tevent = null;
_tcancelled = false;
}
/**
* Called by derived instances when an attribute setter method was
* called.
*/
protected void requestAttributeChange (String name, Object value)
{
// dispatch an attribute changed event
postEvent(new AttributeChangedEvent(_oid, name, value));
}
/**
* Called by derived instances when an element updater method was
* called.
*/
protected void requestElementUpdate (String name, Object value, int index)
{
// dispatch an attribute changed event
postEvent(new ElementUpdatedEvent(_oid, name, value, index));
}
/**
* Calls by derived instances when an oid adder method was called.
*/
protected void requestOidAdd (String name, int oid)
{
// dispatch an object added event
postEvent(new ObjectAddedEvent(_oid, name, oid));
}
/**
* Calls by derived instances when an oid remover method was called.
*/
protected void requestOidRemove (String name, int oid)
{
// dispatch an object removed event
postEvent(new ObjectRemovedEvent(_oid, name, oid));
}
/**
* Calls by derived instances when a set adder method was called.
*/
protected void requestEntryAdd (String name, DSet.Entry entry)
{
try {
DSet set = (DSet)getAttribute(name);
// if we're on the authoritative server, we update the set
// immediately
boolean alreadyApplied = false;
if (_omgr != null && _omgr.isManager(this)) {
// Log.info("Immediately adding [name=" + name +
// ", entry=" + entry + "].");
set.add(entry);
alreadyApplied = true;
}
// dispatch an entry added event
postEvent(new EntryAddedEvent(_oid, name, entry, alreadyApplied));
} catch (ObjectAccessException oae) {
Log.warning("Unable to request entryAdd [name=" + name +
", entry=" + entry + ", error=" + oae + "].");
}
}
/**
* Calls by derived instances when a set remover method was called.
*/
protected void requestEntryRemove (String name, Comparable key)
{
try {
DSet set = (DSet)getAttribute(name);
// if we're on the authoritative server, we update the set
// immediately
DSet.Entry oldEntry = null;
if (_omgr != null && _omgr.isManager(this)) {
// Log.info("Immediately removing [name=" + name +
// ", key=" + key + "].");
oldEntry = set.get(key);
set.removeKey(key);
}
// dispatch an entry removed event
postEvent(new EntryRemovedEvent(_oid, name, key, oldEntry));
} catch (ObjectAccessException oae) {
Log.warning("Unable to request entryRemove [name=" + name +
", key=" + key + ", error=" + oae + "].");
}
}
/**
* Calls by derived instances when a set updater method was called.
*/
protected void requestEntryUpdate (String name, DSet.Entry entry)
{
try {
DSet set = (DSet)getAttribute(name);
// if we're on the authoritative server, we update the set
// immediately
DSet.Entry oldEntry = null;
if (_omgr != null && _omgr.isManager(this)) {
// Log.info("Immediately updating [name=" + name +
// ", entry=" + entry + "].");
oldEntry = set.get(entry.getKey());
set.update(entry);
}
// dispatch an entry updated event
postEvent(new EntryUpdatedEvent(_oid, name, entry, oldEntry));
} catch (ObjectAccessException oae) {
Log.warning("Unable to request entryUpdate [name=" + name +
", entry=" + entry + ", error=" + oae + "].");
}
}
/** Our object id. */
protected int _oid;
/** A reference to our object manager. */
protected transient DObjectManager _omgr;
/** The entity that tells us if an event or subscription request
* should be allowed. */
protected transient AccessController _controller;
/** A list of outstanding locks. */
protected transient Object[] _locks;
/** Our subscribers list. */
protected transient Object[] _subs;
/** Our event listeners list. */
protected transient Object[] _listeners;
/** Our subscriber count. */
protected transient int _scount;
/** The compound event associated with our transaction, if we're
* currently in a transaction. */
protected transient CompoundEvent _tevent;
/** The nesting depth of our current transaction. */
protected transient int _tcount;
/** Whether or not our nested transaction has been cancelled. */
protected transient boolean _tcancelled;
}
| src/java/com/threerings/presents/dobj/DObject.java | //
// $Id: DObject.java,v 1.60 2003/03/10 18:29:54 mdb Exp $
package com.threerings.presents.dobj;
import java.lang.reflect.Field;
import java.util.ArrayList;
import com.samskivert.util.ListUtil;
import com.samskivert.util.StringUtil;
import com.threerings.io.Streamable;
import com.threerings.presents.Log;
/**
* The distributed object forms the foundation of the Presents system. All
* information shared among users of the system is done via distributed
* objects. A distributed object has a set of subscribers. These
* subscribers have access to the object or a proxy of the object and
* therefore have access to the data stored in the object's members at all
* times.
*
* <p> When there is any change to that data, initiated by one of the
* subscribers, an event is generated which is dispatched to all
* subscribers of the object, notifying them of that change and affecting
* that change to the copy of the object maintained at each client. In
* this way, both a respository of shared information and a mechanism for
* asynchronous notification are made available as a fundamental
* application building blocks.
*
* <p> To define what information is shared, an application creates a
* distributed object declaration which is much like a class declaration
* except that it is transformed into a proper derived class of
* <code>DObject</code> by a script. A declaration looks something like
* this:
*
* <pre>
* public dclass RoomObject
* {
* public String description;
* public int[] occupants;
* }
* </pre>
*
* which is converted into an actual Java class that looks like this:
*
* <pre>
* public class RoomObject extends DObject
* {
* public String getDescription ()
* {
* // ...
* }
*
* public void setDescription (String description)
* {
* // ...
* }
*
* public int[] getOccupants ()
* {
* // ...
* }
*
* public void setOccupants (int[] occupants)
* {
* // ...
* }
*
* public void setOccupantsAt (int index, int value)
* {
* // ...
* }
* }
* </pre>
*
* These method calls on the actual distributed object will result in the
* proper attribute change events being generated and dispatched.
*
* <p> Note that distributed object fields can only be of a limited set of
* supported types. These types are:
*
* <code><pre>
* byte, short, int, long, float, double
* Byte, Short, Integer, Long, Float, Double, String
* byte[], short[], int[], long[], float[], double[], String[]
* </pre></code>
*/
public class DObject implements Streamable
{
/**
* Returns the object id of this object. All objects in the system
* have a unique object id.
*/
public int getOid ()
{
return _oid;
}
/**
* Don't call this function! Go through the distributed object manager
* instead to ensure that everything is done on the proper thread.
* This function can only safely be called directly when you know you
* are operating on the omgr thread (you are in the middle of a call
* to <code>objectAvailable</code> or to a listener callback).
*
* @see DObjectManager#subscribeToObject
*/
public void addSubscriber (Subscriber sub)
{
// only add the subscriber if they're not already there
Object[] subs = ListUtil.testAndAdd(_subs, sub);
if (subs != null) {
// Log.info("Adding subscriber " + which() + ": " + sub + ".");
_subs = subs;
_scount++;
} else {
Log.warning("Refusing subscriber that's already in the list " +
"[dobj=" + which() + ", subscriber=" + sub + "]");
Thread.dumpStack();
}
}
/**
* Don't call this function! Go through the distributed object manager
* instead to ensure that everything is done on the proper thread.
* This function can only safely be called directly when you know you
* are operating on the omgr thread (you are in the middle of a call
* to <code>objectAvailable</code> or to a listener callback).
*
* @see DObjectManager#unsubscribeFromObject
*/
public void removeSubscriber (Subscriber sub)
{
if (ListUtil.clear(_subs, sub) != null) {
// if we removed something, check to see if we just removed
// the last subscriber from our list; we also want to be sure
// that we're still active otherwise there's no need to notify
// our objmgr because we don't have one
if (--_scount == 0 && _omgr != null) {
_omgr.removedLastSubscriber(this);
}
}
}
/**
* Adds an event listener to this object. The listener will be
* notified when any events are dispatched on this object that match
* their particular listener interface.
*
* <p> Note that the entity adding itself as a listener should have
* obtained the object reference by subscribing to it or should be
* acting on behalf of some other entity that subscribed to the
* object, <em>and</em> that it must be sure to remove itself from the
* listener list (via {@link #removeListener}) when it is done because
* unsubscribing from the object (done by whatever entity subscribed
* in the first place) is not guaranteed to result in the listeners
* added through that subscription being automatically removed (in
* most cases, they definitely will not be removed).
*
* @param listener the listener to be added.
*
* @see EventListener
* @see AttributeChangeListener
* @see SetListener
* @see OidListListener
*/
public void addListener (ChangeListener listener)
{
// only add the listener if they're not already there
Object[] els = ListUtil.testAndAdd(_listeners, listener);
if (els != null) {
_listeners = els;
} else {
// complain if an object requests to add itself more than once
Log.warning("Refusing listener that's already in the list " +
"[dobj=" + which() + ", listener=" + listener + "]");
Thread.dumpStack();
}
}
/**
* Removes an event listener from this object. The listener will no
* longer be notified when events are dispatched on this object.
*
* @param listener the listener to be removed.
*/
public void removeListener (ChangeListener listener)
{
ListUtil.clear(_listeners, listener);
}
/**
* Provides this object with an entity that can be used to validate
* subscription requests and events before they are processed. The
* access controller is handy for ensuring that clients are behaving
* as expected and for preventing impermissible modifications or event
* dispatches on a distributed object.
*/
public void setAccessController (AccessController controller)
{
_controller = controller;
}
/**
* Returns a reference to the access controller in use by this object
* or null if none has been configured.
*/
public AccessController getAccessController ()
{
return _controller;
}
/**
* At times, an entity on the server may need to ensure that events it
* has queued up have made it through the event queue and are applied
* to their respective objects before a service may safely be
* undertaken again. To make this possible, it can acquire a lock on a
* distributed object, generate the events in question and then
* release the lock (via a call to <code>releaseLock</code>) which
* will queue up a final event, the processing of which will release
* the lock. Thus the lock will not be released until all of the
* previously generated events have been processed. If the service is
* invoked again before that lock is released, the associated call to
* <code>acquireLock</code> will fail and the code can respond
* accordingly. An object may have any number of outstanding locks as
* long as they each have a unique name.
*
* @param name the name of the lock to acquire.
*
* @return true if the lock was acquired, false if the lock was not
* acquired because it has not yet been released from a previous
* acquisition.
*
* @see #releaseLock
*/
public boolean acquireLock (String name)
{
// check for the existence of the lock in the list and add it if
// it's not already there
Object[] list = ListUtil.testAndAddEqual(_locks, name);
if (list == null) {
// a null list means the object was already in the list
return false;
} else {
// a non-null list means the object was added
_locks = list;
return true;
}
}
/**
* Queues up an event that when processed will release the lock of the
* specified name.
*
* @see #acquireLock
*/
public void releaseLock (String name)
{
// queue up a release lock event
postEvent(new ReleaseLockEvent(_oid, name));
}
/**
* Don't call this function! It is called by a remove lock event when
* that event is processed and shouldn't be called at any other time.
* If you mean to release a lock that was acquired with
* <code>acquireLock</code> you should be using
* <code>releaseLock</code>.
*
* @see #acquireLock
* @see #releaseLock
*/
protected void clearLock (String name)
{
// clear the lock from the list
if (ListUtil.clearEqual(_locks, name) == null) {
// complain if we didn't find the lock
Log.info("Unable to clear non-existent lock [lock=" + name +
", dobj=" + this + "].");
}
}
/**
* Requests that this distributed object be destroyed. It does so by
* queueing up an object destroyed event which the server will
* validate and process.
*/
public void destroy ()
{
postEvent(new ObjectDestroyedEvent(_oid));
}
/**
* Checks to ensure that the specified subscriber has access to this
* object. This will be called before satisfying a subscription
* request. If an {@link AccessController} has been specified for this
* object, it will be used to determine whether or not to allow the
* subscription request. If no controller is set, the subscription
* will be allowed.
*
* @param sub the subscriber that will subscribe to this object.
*
* @return true if the subscriber has access to the object, false if
* they do not.
*/
public boolean checkPermissions (Subscriber sub)
{
if (_controller != null) {
return _controller.allowSubscribe(this, sub);
} else {
return true;
}
}
/**
* Checks to ensure that this event which is about to be processed,
* has the appropriate permissions. If an {@link AccessController} has
* been specified for this object, it will be used to determine
* whether or not to allow the even dispatch. If no controller is set,
* all events are allowed.
*
* @param event the event that will be dispatched, object permitting.
*
* @return true if the event is valid and should be dispatched, false
* if the event fails the permissions check and should be aborted.
*/
public boolean checkPermissions (DEvent event)
{
if (_controller != null) {
return _controller.allowDispatch(this, event);
} else {
return true;
}
}
/**
* Called by the distributed object manager after it has applied an
* event to this object. This dispatches an event notification to all
* of the subscribers of this object.
*
* @param event the event that was just applied.
*/
public void notifyListeners (DEvent event)
{
// if we have no listeners, we're home free
if (_listeners == null) {
return;
}
// iterate over the listener list, performing the necessary
// notifications
int llength = _listeners.length;
for (int i = 0; i < llength; i++) {
Object listener = _listeners[i];
// skip empty slots
if (listener == null) {
continue;
}
try {
// do any event specific notifications
event.notifyListener(listener);
// and notify them if they are listening for all events
if (listener instanceof EventListener) {
((EventListener)listener).eventReceived(event);
}
} catch (Exception e) {
Log.warning("Listener choked during notification " +
"[listener=" + listener +
", event=" + event + "].");
Log.logStackTrace(e);
}
}
}
/**
* Sets the named attribute to the specified value. This is only used
* by the internals of the event dispatch mechanism and should not be
* called directly by users. Use the generated attribute setter
* methods instead.
*/
public void setAttribute (String name, Object value)
throws ObjectAccessException
{
try {
// for values that contain other values (arrays and DSets), we
// need to clone them before putting them in the object
// because otherwise a subsequent event might come along and
// modify these values before the networking thread has had a
// chance to propagate this event to the clients
// i wish i could just call value.clone() but Object declares
// clone() to be inaccessible, so we must cast the values to
// their actual types to gain access to the widened clone()
// methods
if (value instanceof DSet) {
value = ((DSet)value).clone();
} else if (value instanceof int[]) {
value = ((int[])value).clone();
} else if (value instanceof String[]) {
value = ((String[])value).clone();
} else if (value instanceof byte[]) {
value = ((byte[])value).clone();
} else if (value instanceof long[]) {
value = ((long[])value).clone();
} else if (value instanceof float[]) {
value = ((float[])value).clone();
} else if (value instanceof short[]) {
value = ((short[])value).clone();
} else if (value instanceof double[]) {
value = ((double[])value).clone();
}
// now actually set the value
getClass().getField(name).set(this, value);
} catch (Exception e) {
String errmsg = "Attribute setting failure [name=" + name +
", value=" + value +
", vclass=" + value.getClass().getName() + "].";
throw new ObjectAccessException(errmsg, e);
}
}
/**
* Looks up the named attribute and returns a reference to it. This
* should only be used by the internals of the event dispatch
* mechanism and should not be called directly by users. Use the
* generated attribute getter methods instead.
*/
public Object getAttribute (String name)
throws ObjectAccessException
{
try {
return getClass().getField(name).get(this);
} catch (Exception e) {
String errmsg = "Attribute getting failure [name=" + name + "].";
throw new ObjectAccessException(errmsg, e);
}
}
/**
* Posts a message event on this distrubuted object.
*/
public void postMessage (String name, Object[] args)
{
postEvent(new MessageEvent(_oid, name, args));
}
/**
* Posts the specified event either to our dobject manager or to the
* compound event for which we are currently transacting.
*/
public void postEvent (DEvent event)
{
if (_tevent != null) {
_tevent.postEvent(event);
} else if (_omgr != null) {
_omgr.postEvent(event);
} else {
Log.warning("Unable to post event, object has no omgr " +
"[oid=" + getOid() + ", class=" + getClass().getName() +
", event=" + event + "].");
Thread.dumpStack();
}
}
/**
* Returns true if this object is active and registered with the
* distributed object system. If an object is created via
* <code>DObjectManager.createObject</code> it will be active until
* such time as it is destroyed.
*/
public boolean isActive ()
{
return _omgr != null;
}
/**
* Don't call this function! It initializes this distributed object
* with the supplied distributed object manager. This is called by the
* distributed object manager when an object is created and registered
* with the system.
*
* @see DObjectManager#createObject
*/
public void setManager (DObjectManager omgr)
{
_omgr = omgr;
}
/**
* Don't call this function. It is called by the distributed object
* manager when an object is created and registered with the system.
*
* @see DObjectManager#createObject
*/
public void setOid (int oid)
{
_oid = oid;
}
/**
* Generates a concise string representation of this object.
*/
public String which ()
{
StringBuffer buf = new StringBuffer();
which(buf);
return buf.toString();
}
/**
* Used to briefly describe this distributed object.
*/
protected void which (StringBuffer buf)
{
buf.append(StringUtil.shortClassName(this));
buf.append(":").append(_oid);
}
/**
* Generates a string representation of this object.
*/
public String toString ()
{
StringBuffer buf = new StringBuffer();
toString(buf);
return buf.append("]").toString();
}
/**
* Generates a string representation of this object.
*/
protected void toString (StringBuffer buf)
{
StringUtil.fieldsToString(buf, this, "\n");
if (buf.length() > 0) {
buf.insert(0, "\n");
}
buf.insert(0, _oid);
buf.insert(0, "[oid=");
}
/**
* Begins a transaction on this distributed object. In some
* situations, it is desirable to cause multiple changes to
* distributed object fields in one unified operation. Starting a
* transaction causes all subsequent field modifications to be stored
* in a single compound event which can then be committed, dispatching
* and applying all included events in a single group. Additionally,
* the events are dispatched over the network in a single unit which
* can significantly enhance network efficiency.
*
* <p> When the transaction is complete, the caller must call {@link
* #commitTransaction} or {@link CompoundEvent#commit} to commit the
* transaction and release all involved objects back to their normal
* non-transacting state. If the caller decides not to commit their
* transaction, they must call {@link #cancelTransaction} or {@link
* CompoundEvent#cancel} to cancel the transaction and release all
* involved objects. Failure to do so will cause the pooch to be
* totally screwed.
*
* <p> Note: like all other distributed object operations,
* transactions are not thread safe. It is expected that a single
* thread will handle all distributed object operations and that
* thread will begin and complete a transaction before giving up
* control to unknown code which might try to operate on the
* transacting distributed object (or objects).
*
* <p> Note also: if the object is already engaged in a transaction, a
* transaction participant count will be incremented to note that an
* additional call to {@link #commitTransaction} is required before
* the transaction should actually be committed. Thus <em>every</em>
* call to {@link #startTransaction} must be accompanied by a call to
* either {@link #commitTransaction} or {@link
* #cancelTransaction}. Additionally, if any transaction participant
* cancels the transaction, the entire transaction is cancelled for
* all participants, regardless of whether the other participants
* attempted to commit the transaction.
*
* <p> Note also: nested transactions are not allowed when an object
* is joined to another object's transaction via {@link
* #joinTransaction}.
*
* @return the compound event that encapsulates the transaction. This
* can be ignored if the transaction will be limited to this object,
* but if it is desired that other objects be involved in the
* transaction, the caller will need to pass the {@link CompoundEvent}
* returned by this method to a call to {@link #joinTransaction} on
* the other objects that are involved.
*/
public CompoundEvent startTransaction ()
{
// sanity check
if (!isActive()) {
String errmsg = "Can't start transaction on non-active object " +
"[oid=" + getOid() + ", type=" + getClass().getName() + "]";
throw new IllegalStateException(errmsg);
}
if (_tevent != null) {
// a transaction count of -1 indicates that we're joined to
// another objects transaction that should not allow
// transaction nesting
if (_tcount == -1) {
String errmsg = "Object involved in shared transaction, " +
"nesting not allowed [dobj=" + this + "]";
throw new IllegalStateException(errmsg);
} else {
_tcount++;
}
} else {
_tevent = new CompoundEvent(_omgr);
_tevent.addObject(this);
}
return _tevent;
}
/**
* Causes this object to join the supplied transaction. See {@link
* #startTransaction} for more information on transactions. The
* transaction can be committed by a call to {@link
* #commitTransaction} on any participanting object.
*/
public void joinTransaction (CompoundEvent event)
{
if (_tevent != null) {
String errmsg = "Cannot join transaction while already " +
"transacting [dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
_tevent = event;
_tevent.addObject(this);
_tcount = -1; // make a note that nesting is not allowed
}
/**
* Commits the transaction in which this distributed object is
* involved.
*
* @see CompoundEvent#commit
*/
public void commitTransaction ()
{
if (_tevent == null) {
String errmsg = "Cannot commit: not involved in a transaction " +
"[dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
// if we are nested, we decrement our nesting count rather than
// committing the transaction
if (_tcount > 0) {
_tcount--;
} else {
// we may actually be doing our final commit after someone
// already cancelled this transaction, so we need to perform
// the appropriate action at this point
if (_tcancelled) {
_tevent.cancel();
} else {
_tevent.commit();
}
}
}
/**
* Returns true if this object is in the middle of a transaction or
* false if it is not.
*/
public boolean inTransaction ()
{
return (_tevent != null);
}
/**
* Cancels the transaction in which this distributed object is
* involved.
*
* @see CompoundEvent#cancel
*/
public void cancelTransaction ()
{
if (_tevent == null) {
String errmsg = "Cannot cancel: not involved in a transaction " +
"[dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
// if we're in a nested transaction, make a note that it is to be
// cancelled when all parties commit and decrement the nest count
if (_tcount > 0) {
_tcancelled = true;
_tcount--;
} else {
_tevent.cancel();
}
}
/**
* Removes this object from participation in any transaction in which
* it might be taking part.
*/
protected void clearTransaction ()
{
// sanity check
if (_tcount != 0) {
Log.warning("Transaction cleared with non-zero nesting count " +
"[dobj=" + this + "].");
_tcount = 0;
}
// clear our transaction state
_tevent = null;
_tcancelled = false;
}
/**
* Called by derived instances when an attribute setter method was
* called.
*/
protected void requestAttributeChange (String name, Object value)
{
// dispatch an attribute changed event
postEvent(new AttributeChangedEvent(_oid, name, value));
}
/**
* Called by derived instances when an element updater method was
* called.
*/
protected void requestElementUpdate (String name, Object value, int index)
{
// dispatch an attribute changed event
postEvent(new ElementUpdatedEvent(_oid, name, value, index));
}
/**
* Calls by derived instances when an oid adder method was called.
*/
protected void requestOidAdd (String name, int oid)
{
// dispatch an object added event
postEvent(new ObjectAddedEvent(_oid, name, oid));
}
/**
* Calls by derived instances when an oid remover method was called.
*/
protected void requestOidRemove (String name, int oid)
{
// dispatch an object removed event
postEvent(new ObjectRemovedEvent(_oid, name, oid));
}
/**
* Calls by derived instances when a set adder method was called.
*/
protected void requestEntryAdd (String name, DSet.Entry entry)
{
try {
DSet set = (DSet)getAttribute(name);
// if we're on the authoritative server, we update the set
// immediately
boolean alreadyApplied = false;
if (_omgr.isManager(this)) {
// Log.info("Immediately adding [name=" + name +
// ", entry=" + entry + "].");
set.add(entry);
alreadyApplied = true;
}
// dispatch an entry added event
postEvent(new EntryAddedEvent(_oid, name, entry, alreadyApplied));
} catch (ObjectAccessException oae) {
Log.warning("Unable to request entryAdd [name=" + name +
", entry=" + entry + ", error=" + oae + "].");
}
}
/**
* Calls by derived instances when a set remover method was called.
*/
protected void requestEntryRemove (String name, Comparable key)
{
try {
DSet set = (DSet)getAttribute(name);
// if we're on the authoritative server, we update the set
// immediately
DSet.Entry oldEntry = null;
if (_omgr.isManager(this)) {
// Log.info("Immediately removing [name=" + name +
// ", key=" + key + "].");
oldEntry = set.get(key);
set.removeKey(key);
}
// dispatch an entry removed event
postEvent(new EntryRemovedEvent(_oid, name, key, oldEntry));
} catch (ObjectAccessException oae) {
Log.warning("Unable to request entryRemove [name=" + name +
", key=" + key + ", error=" + oae + "].");
}
}
/**
* Calls by derived instances when a set updater method was called.
*/
protected void requestEntryUpdate (String name, DSet.Entry entry)
{
try {
DSet set = (DSet)getAttribute(name);
// if we're on the authoritative server, we update the set
// immediately
DSet.Entry oldEntry = null;
if (_omgr.isManager(this)) {
// Log.info("Immediately updating [name=" + name +
// ", entry=" + entry + "].");
oldEntry = set.get(entry.getKey());
set.update(entry);
}
// dispatch an entry updated event
postEvent(new EntryUpdatedEvent(_oid, name, entry, oldEntry));
} catch (ObjectAccessException oae) {
Log.warning("Unable to request entryUpdate [name=" + name +
", entry=" + entry + ", error=" + oae + "].");
}
}
/** Our object id. */
protected int _oid;
/** A reference to our object manager. */
protected transient DObjectManager _omgr;
/** The entity that tells us if an event or subscription request
* should be allowed. */
protected transient AccessController _controller;
/** A list of outstanding locks. */
protected transient Object[] _locks;
/** Our subscribers list. */
protected transient Object[] _subs;
/** Our event listeners list. */
protected transient Object[] _listeners;
/** Our subscriber count. */
protected transient int _scount;
/** The compound event associated with our transaction, if we're
* currently in a transaction. */
protected transient CompoundEvent _tevent;
/** The nesting depth of our current transaction. */
protected transient int _tcount;
/** Whether or not our nested transaction has been cancelled. */
protected transient boolean _tcancelled;
}
| Safety first!
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@2354 542714f4-19e9-0310-aa3c-eee0fc999fb1
| src/java/com/threerings/presents/dobj/DObject.java | Safety first! | <ide><path>rc/java/com/threerings/presents/dobj/DObject.java
<ide> //
<del>// $Id: DObject.java,v 1.60 2003/03/10 18:29:54 mdb Exp $
<add>// $Id: DObject.java,v 1.61 2003/03/30 19:38:56 mdb Exp $
<ide>
<ide> package com.threerings.presents.dobj;
<ide>
<ide> // if we're on the authoritative server, we update the set
<ide> // immediately
<ide> boolean alreadyApplied = false;
<del> if (_omgr.isManager(this)) {
<add> if (_omgr != null && _omgr.isManager(this)) {
<ide> // Log.info("Immediately adding [name=" + name +
<ide> // ", entry=" + entry + "].");
<ide> set.add(entry);
<ide> // if we're on the authoritative server, we update the set
<ide> // immediately
<ide> DSet.Entry oldEntry = null;
<del> if (_omgr.isManager(this)) {
<add> if (_omgr != null && _omgr.isManager(this)) {
<ide> // Log.info("Immediately removing [name=" + name +
<ide> // ", key=" + key + "].");
<ide> oldEntry = set.get(key);
<ide> // if we're on the authoritative server, we update the set
<ide> // immediately
<ide> DSet.Entry oldEntry = null;
<del> if (_omgr.isManager(this)) {
<add> if (_omgr != null && _omgr.isManager(this)) {
<ide> // Log.info("Immediately updating [name=" + name +
<ide> // ", entry=" + entry + "].");
<ide> oldEntry = set.get(entry.getKey()); |
|
Java | apache-2.0 | e0f87c6098fd50b2da20ff09e63658c7ec3acc5d | 0 | FasterXML/jackson-databind,FasterXML/jackson-databind | package com.fasterxml.jackson.databind.node;
import java.math.BigDecimal;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* Additional tests for {@link ObjectNode} container class.
*/
public class TestObjectNode
extends BaseMapTest
{
@JsonDeserialize(as = DataImpl.class)
public interface Data {
}
public static class DataImpl implements Data
{
protected JsonNode root;
@JsonCreator
public DataImpl(JsonNode n) {
root = n;
}
@JsonValue
public JsonNode value() { return root; }
/*
public Wrapper(ObjectNode n) { root = n; }
@JsonValue
public ObjectNode value() { return root; }
*/
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final ObjectMapper MAPPER = objectMapper();
// for [Issue#346]
public void testEmptyNodeAsValue() throws Exception
{
Data w = MAPPER.readValue("{}", Data.class);
assertNotNull(w);
}
public void testBasics()
{
ObjectNode n = new ObjectNode(JsonNodeFactory.instance);
assertStandardEquals(n);
assertFalse(n.elements().hasNext());
assertFalse(n.fields().hasNext());
assertFalse(n.fieldNames().hasNext());
assertNull(n.get("a"));
assertTrue(n.path("a").isMissingNode());
TextNode text = TextNode.valueOf("x");
assertSame(n, n.set("a", text));
assertEquals(1, n.size());
assertTrue(n.elements().hasNext());
assertTrue(n.fields().hasNext());
assertTrue(n.fieldNames().hasNext());
assertSame(text, n.get("a"));
assertSame(text, n.path("a"));
assertNull(n.get("b"));
assertNull(n.get(0)); // not used with objects
assertFalse(n.has(0));
assertFalse(n.hasNonNull(0));
assertTrue(n.has("a"));
assertTrue(n.hasNonNull("a"));
assertFalse(n.has("b"));
assertFalse(n.hasNonNull("b"));
ObjectNode n2 = new ObjectNode(JsonNodeFactory.instance);
n2.put("b", 13);
assertFalse(n.equals(n2));
n.setAll(n2);
assertEquals(2, n.size());
n.set("null", (JsonNode)null);
assertEquals(3, n.size());
// may be non-intuitive, but explicit nulls do exist in tree:
assertTrue(n.has("null"));
assertFalse(n.hasNonNull("null"));
// should replace, not add
n.put("null", "notReallNull");
assertEquals(3, n.size());
assertNotNull(n.remove("null"));
assertEquals(2, n.size());
Map<String,JsonNode> nodes = new HashMap<String,JsonNode>();
nodes.put("d", text);
n.setAll(nodes);
assertEquals(3, n.size());
n.removeAll();
assertEquals(0, n.size());
}
/**
* Verify null handling
*/
public void testNullChecking()
{
ObjectNode o1 = JsonNodeFactory.instance.objectNode();
ObjectNode o2 = JsonNodeFactory.instance.objectNode();
// used to throw NPE before fix:
o1.setAll(o2);
assertEquals(0, o1.size());
assertEquals(0, o2.size());
// also: nulls should be converted to NullNodes...
o1.set("x", null);
JsonNode n = o1.get("x");
assertNotNull(n);
assertSame(n, NullNode.instance);
o1.put("str", (String) null);
n = o1.get("str");
assertNotNull(n);
assertSame(n, NullNode.instance);
o1.put("d", (BigDecimal) null);
n = o1.get("d");
assertNotNull(n);
assertSame(n, NullNode.instance);
}
/**
* Another test to verify [JACKSON-227]...
*/
public void testNullChecking2()
{
ObjectNode src = MAPPER.createObjectNode();
ObjectNode dest = MAPPER.createObjectNode();
src.put("a", "b");
dest.setAll(src);
}
public void testRemove()
{
ObjectNode ob = MAPPER.createObjectNode();
ob.put("a", "a");
ob.put("b", "b");
ob.put("c", "c");
assertEquals(3, ob.size());
assertSame(ob, ob.without(Arrays.asList("a", "c")));
assertEquals(1, ob.size());
assertEquals("b", ob.get("b").textValue());
}
public void testRetain()
{
ObjectNode ob = MAPPER.createObjectNode();
ob.put("a", "a");
ob.put("b", "b");
ob.put("c", "c");
assertEquals(3, ob.size());
assertSame(ob, ob.retain("a", "c"));
assertEquals(2, ob.size());
assertEquals("a", ob.get("a").textValue());
assertNull(ob.get("b"));
assertEquals("c", ob.get("c").textValue());
}
public void testValidWith() throws Exception
{
ObjectNode root = MAPPER.createObjectNode();
assertEquals("{}", MAPPER.writeValueAsString(root));
JsonNode child = root.with("prop");
assertTrue(child instanceof ObjectNode);
assertEquals("{\"prop\":{}}", MAPPER.writeValueAsString(root));
}
public void testValidWithArray() throws Exception
{
ObjectNode root = MAPPER.createObjectNode();
assertEquals("{}", MAPPER.writeValueAsString(root));
JsonNode child = root.withArray("arr");
assertTrue(child instanceof ArrayNode);
assertEquals("{\"arr\":[]}", MAPPER.writeValueAsString(root));
}
public void testInvalidWith() throws Exception
{
JsonNode root = MAPPER.createArrayNode();
try { // should not work for non-ObjectNode nodes:
root.with("prop");
fail("Expected exception");
} catch (UnsupportedOperationException e) {
verifyException(e, "not of type ObjectNode");
}
// also: should fail of we already have non-object property
ObjectNode root2 = MAPPER.createObjectNode();
root2.put("prop", 13);
try { // should not work for non-ObjectNode nodes:
root2.with("prop");
fail("Expected exception");
} catch (UnsupportedOperationException e) {
verifyException(e, "has value that is not");
}
}
public void testInvalidWithArray() throws Exception
{
JsonNode root = MAPPER.createArrayNode();
try { // should not work for non-ObjectNode nodes:
root.withArray("prop");
fail("Expected exception");
} catch (UnsupportedOperationException e) {
verifyException(e, "not of type ObjectNode");
}
// also: should fail of we already have non-Array property
ObjectNode root2 = MAPPER.createObjectNode();
root2.put("prop", 13);
try { // should not work for non-ObjectNode nodes:
root2.withArray("prop");
fail("Expected exception");
} catch (UnsupportedOperationException e) {
verifyException(e, "has value that is not");
}
}
// [Issue#93]
public void testSetAll() throws Exception
{
ObjectNode root = MAPPER.createObjectNode();
assertEquals(0, root.size());
HashMap<String,JsonNode> map = new HashMap<String,JsonNode>();
map.put("a", root.numberNode(1));
root.setAll(map);
assertEquals(1, root.size());
assertTrue(root.has("a"));
assertFalse(root.has("b"));
map.put("b", root.numberNode(2));
root.setAll(map);
assertEquals(2, root.size());
assertTrue(root.has("a"));
assertTrue(root.has("b"));
assertEquals(2, root.path("b").intValue());
// Then with ObjectNodes...
ObjectNode root2 = MAPPER.createObjectNode();
root2.setAll(root);
assertEquals(2, root.size());
assertEquals(2, root2.size());
root2.setAll(root);
assertEquals(2, root.size());
assertEquals(2, root2.size());
ObjectNode root3 = MAPPER.createObjectNode();
root3.put("a", 2);
root3.put("c", 3);
assertEquals(2, root3.path("a").intValue());
root3.setAll(root2);
assertEquals(3, root3.size());
assertEquals(1, root3.path("a").intValue());
}
// [Issue#237] (databind): support DeserializationFeature#FAIL_ON_READING_DUP_TREE_KEY
public void testFailOnDupKeys() throws Exception
{
final String DUP_JSON = "{ \"a\":1, \"a\":2 }";
// first: verify defaults:
ObjectMapper mapper = new ObjectMapper();
assertFalse(mapper.isEnabled(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY));
ObjectNode root = (ObjectNode) mapper.readTree(DUP_JSON);
assertEquals(2, root.path("a").asInt());
// and then enable checks:
try {
mapper.reader(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY).readTree(DUP_JSON);
fail("Should have thrown exception!");
} catch (JsonMappingException e) {
verifyException(e, "duplicate field 'a'");
}
}
public void testEqualityWrtOrder() throws Exception
{
ObjectNode ob1 = MAPPER.createObjectNode();
ObjectNode ob2 = MAPPER.createObjectNode();
// same contents, different insertion order; should not matter
ob1.put("a", 1);
ob1.put("b", 2);
ob1.put("c", 3);
ob2.put("b", 2);
ob2.put("c", 3);
ob2.put("a", 1);
assertTrue(ob1.equals(ob2));
assertTrue(ob2.equals(ob1));
}
}
| src/test/java/com/fasterxml/jackson/databind/node/TestObjectNode.java | package com.fasterxml.jackson.databind.node;
import java.math.BigDecimal;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* Additional tests for {@link ObjectNode} container class.
*/
public class TestObjectNode
extends BaseMapTest
{
@JsonDeserialize(as = DataImpl.class)
public interface Data {
}
public static class DataImpl implements Data
{
protected JsonNode root;
@JsonCreator
public DataImpl(JsonNode n) {
root = n;
}
@JsonValue
public JsonNode value() { return root; }
/*
public Wrapper(ObjectNode n) { root = n; }
@JsonValue
public ObjectNode value() { return root; }
*/
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final ObjectMapper MAPPER = objectMapper();
// for [Issue#346]
public void testEmptyNodeAsValue() throws Exception
{
Data w = MAPPER.readValue("{}", Data.class);
assertNotNull(w);
}
public void testBasics()
{
ObjectNode n = new ObjectNode(JsonNodeFactory.instance);
assertStandardEquals(n);
assertFalse(n.elements().hasNext());
assertFalse(n.fields().hasNext());
assertFalse(n.fieldNames().hasNext());
assertNull(n.get("a"));
assertTrue(n.path("a").isMissingNode());
TextNode text = TextNode.valueOf("x");
assertSame(n, n.set("a", text));
assertEquals(1, n.size());
assertTrue(n.elements().hasNext());
assertTrue(n.fields().hasNext());
assertTrue(n.fieldNames().hasNext());
assertSame(text, n.get("a"));
assertSame(text, n.path("a"));
assertNull(n.get("b"));
assertNull(n.get(0)); // not used with objects
assertFalse(n.has(0));
assertFalse(n.hasNonNull(0));
assertTrue(n.has("a"));
assertTrue(n.hasNonNull("a"));
assertFalse(n.has("b"));
assertFalse(n.hasNonNull("b"));
ObjectNode n2 = new ObjectNode(JsonNodeFactory.instance);
n2.put("b", 13);
assertFalse(n.equals(n2));
n.setAll(n2);
assertEquals(2, n.size());
n.set("null", (JsonNode)null);
assertEquals(3, n.size());
// may be non-intuitive, but explicit nulls do exist in tree:
assertTrue(n.has("null"));
assertFalse(n.hasNonNull("null"));
// should replace, not add
n.put("null", "notReallNull");
assertEquals(3, n.size());
assertNotNull(n.remove("null"));
assertEquals(2, n.size());
Map<String,JsonNode> nodes = new HashMap<String,JsonNode>();
nodes.put("d", text);
n.setAll(nodes);
assertEquals(3, n.size());
n.removeAll();
assertEquals(0, n.size());
}
/**
* Verify null handling
*/
public void testNullChecking()
{
ObjectNode o1 = JsonNodeFactory.instance.objectNode();
ObjectNode o2 = JsonNodeFactory.instance.objectNode();
// used to throw NPE before fix:
o1.setAll(o2);
assertEquals(0, o1.size());
assertEquals(0, o2.size());
// also: nulls should be converted to NullNodes...
o1.set("x", null);
JsonNode n = o1.get("x");
assertNotNull(n);
assertSame(n, NullNode.instance);
o1.put("str", (String) null);
n = o1.get("str");
assertNotNull(n);
assertSame(n, NullNode.instance);
o1.put("d", (BigDecimal) null);
n = o1.get("d");
assertNotNull(n);
assertSame(n, NullNode.instance);
}
/**
* Another test to verify [JACKSON-227]...
*/
public void testNullChecking2()
{
ObjectNode src = MAPPER.createObjectNode();
ObjectNode dest = MAPPER.createObjectNode();
src.put("a", "b");
dest.setAll(src);
}
public void testRemove()
{
ObjectNode ob = MAPPER.createObjectNode();
ob.put("a", "a");
ob.put("b", "b");
ob.put("c", "c");
assertEquals(3, ob.size());
assertSame(ob, ob.without(Arrays.asList("a", "c")));
assertEquals(1, ob.size());
assertEquals("b", ob.get("b").textValue());
}
public void testRetain()
{
ObjectNode ob = MAPPER.createObjectNode();
ob.put("a", "a");
ob.put("b", "b");
ob.put("c", "c");
assertEquals(3, ob.size());
assertSame(ob, ob.retain("a", "c"));
assertEquals(2, ob.size());
assertEquals("a", ob.get("a").textValue());
assertNull(ob.get("b"));
assertEquals("c", ob.get("c").textValue());
}
public void testValidWith() throws Exception
{
ObjectNode root = MAPPER.createObjectNode();
assertEquals("{}", MAPPER.writeValueAsString(root));
JsonNode child = root.with("prop");
assertTrue(child instanceof ObjectNode);
assertEquals("{\"prop\":{}}", MAPPER.writeValueAsString(root));
}
public void testValidWithArray() throws Exception
{
ObjectNode root = MAPPER.createObjectNode();
assertEquals("{}", MAPPER.writeValueAsString(root));
JsonNode child = root.withArray("arr");
assertTrue(child instanceof ArrayNode);
assertEquals("{\"arr\":[]}", MAPPER.writeValueAsString(root));
}
public void testInvalidWith() throws Exception
{
JsonNode root = MAPPER.createArrayNode();
try { // should not work for non-ObjectNode nodes:
root.with("prop");
fail("Expected exception");
} catch (UnsupportedOperationException e) {
verifyException(e, "not of type ObjectNode");
}
// also: should fail of we already have non-object property
ObjectNode root2 = MAPPER.createObjectNode();
root2.put("prop", 13);
try { // should not work for non-ObjectNode nodes:
root2.with("prop");
fail("Expected exception");
} catch (UnsupportedOperationException e) {
verifyException(e, "has value that is not");
}
}
public void testInvalidWithArray() throws Exception
{
JsonNode root = MAPPER.createArrayNode();
try { // should not work for non-ObjectNode nodes:
root.withArray("prop");
fail("Expected exception");
} catch (UnsupportedOperationException e) {
verifyException(e, "not of type ObjectNode");
}
// also: should fail of we already have non-Array property
ObjectNode root2 = MAPPER.createObjectNode();
root2.put("prop", 13);
try { // should not work for non-ObjectNode nodes:
root2.withArray("prop");
fail("Expected exception");
} catch (UnsupportedOperationException e) {
verifyException(e, "has value that is not");
}
}
// [Issue#93]
public void testSetAll() throws Exception
{
ObjectNode root = MAPPER.createObjectNode();
assertEquals(0, root.size());
HashMap<String,JsonNode> map = new HashMap<String,JsonNode>();
map.put("a", root.numberNode(1));
root.setAll(map);
assertEquals(1, root.size());
assertTrue(root.has("a"));
assertFalse(root.has("b"));
map.put("b", root.numberNode(2));
root.setAll(map);
assertEquals(2, root.size());
assertTrue(root.has("a"));
assertTrue(root.has("b"));
assertEquals(2, root.path("b").intValue());
// Then with ObjectNodes...
ObjectNode root2 = MAPPER.createObjectNode();
root2.setAll(root);
assertEquals(2, root.size());
assertEquals(2, root2.size());
root2.setAll(root);
assertEquals(2, root.size());
assertEquals(2, root2.size());
ObjectNode root3 = MAPPER.createObjectNode();
root3.put("a", 2);
root3.put("c", 3);
assertEquals(2, root3.path("a").intValue());
root3.setAll(root2);
assertEquals(3, root3.size());
assertEquals(1, root3.path("a").intValue());
}
// [Issue#237] (databind): support DeserializationFeature#FAIL_ON_READING_DUP_TREE_KEY
public void testFailOnDupKeys() throws Exception
{
final String DUP_JSON = "{ \"a\":1, \"a\":2 }";
// first: verify defaults:
ObjectMapper mapper = new ObjectMapper();
assertFalse(mapper.isEnabled(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY));
ObjectNode root = (ObjectNode) mapper.readTree(DUP_JSON);
assertEquals(2, root.path("a").asInt());
// and then enable checks:
try {
mapper.reader(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY).readTree(DUP_JSON);
fail("Should have thrown exception!");
} catch (JsonMappingException e) {
verifyException(e, "duplicate field 'a'");
}
}
}
| trying to reproduce #366
| src/test/java/com/fasterxml/jackson/databind/node/TestObjectNode.java | trying to reproduce #366 | <ide><path>rc/test/java/com/fasterxml/jackson/databind/node/TestObjectNode.java
<ide> verifyException(e, "duplicate field 'a'");
<ide> }
<ide> }
<add>
<add> public void testEqualityWrtOrder() throws Exception
<add> {
<add> ObjectNode ob1 = MAPPER.createObjectNode();
<add> ObjectNode ob2 = MAPPER.createObjectNode();
<add>
<add> // same contents, different insertion order; should not matter
<add>
<add> ob1.put("a", 1);
<add> ob1.put("b", 2);
<add> ob1.put("c", 3);
<add>
<add> ob2.put("b", 2);
<add> ob2.put("c", 3);
<add> ob2.put("a", 1);
<add>
<add> assertTrue(ob1.equals(ob2));
<add> assertTrue(ob2.equals(ob1));
<add> }
<ide> } |
|
Java | apache-2.0 | daee8bd13375a79994d48350535cc90dff7f23b1 | 0 | gingerwizard/elasticsearch,robin13/elasticsearch,gingerwizard/elasticsearch,HonzaKral/elasticsearch,uschindler/elasticsearch,GlenRSmith/elasticsearch,gfyoung/elasticsearch,robin13/elasticsearch,HonzaKral/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,coding0011/elasticsearch,nknize/elasticsearch,scorpionvicky/elasticsearch,uschindler/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,uschindler/elasticsearch,uschindler/elasticsearch,gfyoung/elasticsearch,robin13/elasticsearch,gingerwizard/elasticsearch,scorpionvicky/elasticsearch,scorpionvicky/elasticsearch,coding0011/elasticsearch,scorpionvicky/elasticsearch,gfyoung/elasticsearch,coding0011/elasticsearch,HonzaKral/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,gingerwizard/elasticsearch,nknize/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,gfyoung/elasticsearch,gingerwizard/elasticsearch,coding0011/elasticsearch,gfyoung/elasticsearch,scorpionvicky/elasticsearch,uschindler/elasticsearch,coding0011/elasticsearch,HonzaKral/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.apache.http.HttpEntity;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest;
import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest;
import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.explain.ExplainRequest;
import org.elasticsearch.action.explain.ExplainResponse;
import org.elasticsearch.action.fieldcaps.FieldCapabilitiesRequest;
import org.elasticsearch.action.fieldcaps.FieldCapabilitiesResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.main.MainRequest;
import org.elasticsearch.action.main.MainResponse;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.ClearScrollResponse;
import org.elasticsearch.action.search.MultiSearchRequest;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.common.CheckedConsumer;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ContextParser;
import org.elasticsearch.common.xcontent.DeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.rankeval.RankEvalRequest;
import org.elasticsearch.index.rankeval.RankEvalResponse;
import org.elasticsearch.plugins.spi.NamedXContentProvider;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.script.mustache.MultiSearchTemplateRequest;
import org.elasticsearch.script.mustache.MultiSearchTemplateResponse;
import org.elasticsearch.script.mustache.SearchTemplateRequest;
import org.elasticsearch.script.mustache.SearchTemplateResponse;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.bucket.adjacency.AdjacencyMatrixAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.adjacency.ParsedAdjacencyMatrix;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.ParsedComposite;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.FiltersAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilters;
import org.elasticsearch.search.aggregations.bucket.geogrid.GeoGridAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.geogrid.ParsedGeoHashGrid;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.ParsedGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.AutoDateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.ParsedAutoDateHistogram;
import org.elasticsearch.search.aggregations.bucket.histogram.ParsedDateHistogram;
import org.elasticsearch.search.aggregations.bucket.histogram.ParsedHistogram;
import org.elasticsearch.search.aggregations.bucket.missing.MissingAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.missing.ParsedMissing;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedReverseNested;
import org.elasticsearch.search.aggregations.bucket.nested.ReverseNestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.range.DateRangeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.range.GeoDistanceAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.range.IpRangeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.range.ParsedBinaryRange;
import org.elasticsearch.search.aggregations.bucket.range.ParsedDateRange;
import org.elasticsearch.search.aggregations.bucket.range.ParsedGeoDistance;
import org.elasticsearch.search.aggregations.bucket.range.ParsedRange;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.sampler.InternalSampler;
import org.elasticsearch.search.aggregations.bucket.sampler.ParsedSampler;
import org.elasticsearch.search.aggregations.bucket.significant.ParsedSignificantLongTerms;
import org.elasticsearch.search.aggregations.bucket.significant.ParsedSignificantStringTerms;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantLongTerms;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.DoubleTerms;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedDoubleTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.avg.ParsedAvg;
import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.ParsedCardinality;
import org.elasticsearch.search.aggregations.metrics.geobounds.GeoBoundsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.geobounds.ParsedGeoBounds;
import org.elasticsearch.search.aggregations.metrics.geocentroid.GeoCentroidAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.geocentroid.ParsedGeoCentroid;
import org.elasticsearch.search.aggregations.metrics.max.MaxAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.max.ParsedMax;
import org.elasticsearch.search.aggregations.metrics.min.MinAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.min.ParsedMin;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.InternalHDRPercentileRanks;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.InternalHDRPercentiles;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.ParsedHDRPercentileRanks;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.ParsedHDRPercentiles;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.InternalTDigestPercentileRanks;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.InternalTDigestPercentiles;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.ParsedTDigestPercentileRanks;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.ParsedTDigestPercentiles;
import org.elasticsearch.search.aggregations.metrics.scripted.ParsedScriptedMetric;
import org.elasticsearch.search.aggregations.metrics.scripted.ScriptedMetricAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.ParsedStats;
import org.elasticsearch.search.aggregations.metrics.stats.StatsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStatsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ParsedExtendedStats;
import org.elasticsearch.search.aggregations.metrics.sum.ParsedSum;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.tophits.ParsedTopHits;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHitsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.valuecount.ParsedValueCount;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.InternalSimpleValue;
import org.elasticsearch.search.aggregations.pipeline.ParsedSimpleValue;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.InternalBucketMetricValue;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.ParsedBucketMetricValue;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.percentile.ParsedPercentilesBucket;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.percentile.PercentilesBucketPipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.ParsedStatsBucket;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.StatsBucketPipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ExtendedStatsBucketPipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ParsedExtendedStatsBucket;
import org.elasticsearch.search.aggregations.pipeline.derivative.DerivativePipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.derivative.ParsedDerivative;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.elasticsearch.search.suggest.phrase.PhraseSuggestion;
import org.elasticsearch.search.suggest.phrase.PhraseSuggestionBuilder;
import org.elasticsearch.search.suggest.term.TermSuggestion;
import org.elasticsearch.search.suggest.term.TermSuggestionBuilder;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toList;
/**
* High level REST client that wraps an instance of the low level {@link RestClient} and allows to build requests and read responses.
* The {@link RestClient} instance is internally built based on the provided {@link RestClientBuilder} and it gets closed automatically
* when closing the {@link RestHighLevelClient} instance that wraps it.
* In case an already existing instance of a low-level REST client needs to be provided, this class can be subclassed and the
* {@link #RestHighLevelClient(RestClient, CheckedConsumer, List)} constructor can be used.
* This class can also be sub-classed to expose additional client methods that make use of endpoints added to Elasticsearch through
* plugins, or to add support for custom response sections, again added to Elasticsearch through plugins.
*/
public class RestHighLevelClient implements Closeable {
private final RestClient client;
private final NamedXContentRegistry registry;
private final CheckedConsumer<RestClient, IOException> doClose;
private final IndicesClient indicesClient = new IndicesClient(this);
private final ClusterClient clusterClient = new ClusterClient(this);
private final IngestClient ingestClient = new IngestClient(this);
private final SnapshotClient snapshotClient = new SnapshotClient(this);
private final TasksClient tasksClient = new TasksClient(this);
private final XPackClient xPackClient = new XPackClient(this);
private final WatcherClient watcherClient = new WatcherClient(this);
private final GraphClient graphClient = new GraphClient(this);
private final LicenseClient licenseClient = new LicenseClient(this);
private final MigrationClient migrationClient = new MigrationClient(this);
private final MachineLearningClient machineLearningClient = new MachineLearningClient(this);
/**
* Creates a {@link RestHighLevelClient} given the low level {@link RestClientBuilder} that allows to build the
* {@link RestClient} to be used to perform requests.
*/
public RestHighLevelClient(RestClientBuilder restClientBuilder) {
this(restClientBuilder, Collections.emptyList());
}
/**
* Creates a {@link RestHighLevelClient} given the low level {@link RestClientBuilder} that allows to build the
* {@link RestClient} to be used to perform requests and parsers for custom response sections added to Elasticsearch through plugins.
*/
protected RestHighLevelClient(RestClientBuilder restClientBuilder, List<NamedXContentRegistry.Entry> namedXContentEntries) {
this(restClientBuilder.build(), RestClient::close, namedXContentEntries);
}
/**
* Creates a {@link RestHighLevelClient} given the low level {@link RestClient} that it should use to perform requests and
* a list of entries that allow to parse custom response sections added to Elasticsearch through plugins.
* This constructor can be called by subclasses in case an externally created low-level REST client needs to be provided.
* The consumer argument allows to control what needs to be done when the {@link #close()} method is called.
* Also subclasses can provide parsers for custom response sections added to Elasticsearch through plugins.
*/
protected RestHighLevelClient(RestClient restClient, CheckedConsumer<RestClient, IOException> doClose,
List<NamedXContentRegistry.Entry> namedXContentEntries) {
this.client = Objects.requireNonNull(restClient, "restClient must not be null");
this.doClose = Objects.requireNonNull(doClose, "doClose consumer must not be null");
this.registry = new NamedXContentRegistry(
Stream.of(getDefaultNamedXContents().stream(), getProvidedNamedXContents().stream(), namedXContentEntries.stream())
.flatMap(Function.identity()).collect(toList()));
}
/**
* Returns the low-level client that the current high-level client instance is using to perform requests
*/
public final RestClient getLowLevelClient() {
return client;
}
@Override
public final void close() throws IOException {
doClose.accept(client);
}
/**
* Provides an {@link IndicesClient} which can be used to access the Indices API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices.html">Indices API on elastic.co</a>
*/
public final IndicesClient indices() {
return indicesClient;
}
/**
* Provides a {@link ClusterClient} which can be used to access the Cluster API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster.html">Cluster API on elastic.co</a>
*/
public final ClusterClient cluster() {
return clusterClient;
}
/**
* Provides a {@link IngestClient} which can be used to access the Ingest API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/ingest.html">Ingest API on elastic.co</a>
*/
public final IngestClient ingest() {
return ingestClient;
}
/**
* Provides a {@link SnapshotClient} which can be used to access the Snapshot API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html">Snapshot API on elastic.co</a>
*/
public final SnapshotClient snapshot() {
return snapshotClient;
}
/**
* Provides a {@link TasksClient} which can be used to access the Tasks API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html">Task Management API on elastic.co</a>
*/
public final TasksClient tasks() {
return tasksClient;
}
/**
* Provides methods for accessing the Elastic Licensed X-Pack Info
* and Usage APIs that are shipped with the default distribution of
* Elasticsearch. All of these APIs will 404 if run against the OSS
* distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/info-api.html">
* Info APIs on elastic.co</a> for more information.
*/
public final XPackClient xpack() {
return xPackClient;
}
/**
* Provides methods for accessing the Elastic Licensed Watcher APIs that
* are shipped with the default distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api.html">
* Watcher APIs on elastic.co</a> for more information.
*/
public WatcherClient watcher() { return watcherClient; }
/**
* Provides methods for accessing the Elastic Licensed Graph explore API that
* is shipped with the default distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/graph-explore-api.html">
* Graph API on elastic.co</a> for more information.
*/
public GraphClient graph() { return graphClient; }
/**
* Provides methods for accessing the Elastic Licensed Licensing APIs that
* are shipped with the default distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/licensing-apis.html">
* Licensing APIs on elastic.co</a> for more information.
*/
public LicenseClient license() { return licenseClient; }
/**
* Provides methods for accessing the Elastic Licensed Licensing APIs that
* are shipped with the default distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/migration-api.html">
* Migration APIs on elastic.co</a> for more information.
*/
public MigrationClient migration() {
return migrationClient;
}
/**
* Provides methods for accessing the Elastic Licensed Machine Learning APIs that
* are shipped with the Elastic Stack distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/ml-apis.html">
* Machine Learning APIs on elastic.co</a> for more information.
*
* @return the client wrapper for making Machine Learning API calls
*/
public MachineLearningClient machineLearning() {
return machineLearningClient;
}
/**
* Executes a bulk request using the Bulk API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html">Bulk API on elastic.co</a>
* @param bulkRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final BulkResponse bulk(BulkRequest bulkRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(bulkRequest, RequestConverters::bulk, options, BulkResponse::fromXContent, emptySet());
}
/**
* Asynchronously executes a bulk request using the Bulk API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html">Bulk API on elastic.co</a>
* @param bulkRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void bulkAsync(BulkRequest bulkRequest, RequestOptions options, ActionListener<BulkResponse> listener) {
performRequestAsyncAndParseEntity(bulkRequest, RequestConverters::bulk, options, BulkResponse::fromXContent, listener, emptySet());
}
/**
* Pings the remote Elasticsearch cluster and returns true if the ping succeeded, false otherwise
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return <code>true</code> if the ping succeeded, false otherwise
* @throws IOException in case there is a problem sending the request
*/
public final boolean ping(RequestOptions options) throws IOException {
return performRequest(new MainRequest(), (request) -> RequestConverters.ping(), options, RestHighLevelClient::convertExistsResponse,
emptySet());
}
/**
* Get the cluster info otherwise provided when sending an HTTP request to '/'
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final MainResponse info(RequestOptions options) throws IOException {
return performRequestAndParseEntity(new MainRequest(), (request) -> RequestConverters.info(), options,
MainResponse::fromXContent, emptySet());
}
/**
* Retrieves a document by id using the Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html">Get API on elastic.co</a>
* @param getRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final GetResponse get(GetRequest getRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(getRequest, RequestConverters::get, options, GetResponse::fromXContent, singleton(404));
}
/**
* Asynchronously retrieves a document by id using the Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html">Get API on elastic.co</a>
* @param getRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void getAsync(GetRequest getRequest, RequestOptions options, ActionListener<GetResponse> listener) {
performRequestAsyncAndParseEntity(getRequest, RequestConverters::get, options, GetResponse::fromXContent, listener,
singleton(404));
}
/**
* Retrieves multiple documents by id using the Multi Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html">Multi Get API on elastic.co</a>
* @param multiGetRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
* @deprecated use {@link #mget(MultiGetRequest, RequestOptions)} instead
*/
@Deprecated
public final MultiGetResponse multiGet(MultiGetRequest multiGetRequest, RequestOptions options) throws IOException {
return mget(multiGetRequest, options);
}
/**
* Retrieves multiple documents by id using the Multi Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html">Multi Get API on elastic.co</a>
* @param multiGetRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final MultiGetResponse mget(MultiGetRequest multiGetRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(multiGetRequest, RequestConverters::multiGet, options, MultiGetResponse::fromXContent,
singleton(404));
}
/**
* Asynchronously retrieves multiple documents by id using the Multi Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html">Multi Get API on elastic.co</a>
* @param multiGetRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @deprecated use {@link #mgetAsync(MultiGetRequest, RequestOptions, ActionListener)} instead
*/
@Deprecated
public final void multiGetAsync(MultiGetRequest multiGetRequest, RequestOptions options, ActionListener<MultiGetResponse> listener) {
mgetAsync(multiGetRequest, options, listener);
}
/**
* Asynchronously retrieves multiple documents by id using the Multi Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html">Multi Get API on elastic.co</a>
* @param multiGetRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void mgetAsync(MultiGetRequest multiGetRequest, RequestOptions options, ActionListener<MultiGetResponse> listener) {
performRequestAsyncAndParseEntity(multiGetRequest, RequestConverters::multiGet, options, MultiGetResponse::fromXContent, listener,
singleton(404));
}
/**
* Checks for the existence of a document. Returns true if it exists, false otherwise.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html">Get API on elastic.co</a>
* @param getRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return <code>true</code> if the document exists, <code>false</code> otherwise
* @throws IOException in case there is a problem sending the request
*/
public final boolean exists(GetRequest getRequest, RequestOptions options) throws IOException {
return performRequest(getRequest, RequestConverters::exists, options, RestHighLevelClient::convertExistsResponse, emptySet());
}
/**
* Asynchronously checks for the existence of a document. Returns true if it exists, false otherwise.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html">Get API on elastic.co</a>
* @param getRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void existsAsync(GetRequest getRequest, RequestOptions options, ActionListener<Boolean> listener) {
performRequestAsync(getRequest, RequestConverters::exists, options, RestHighLevelClient::convertExistsResponse, listener,
emptySet());
}
/**
* Index a document using the Index API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html">Index API on elastic.co</a>
* @param indexRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final IndexResponse index(IndexRequest indexRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(indexRequest, RequestConverters::index, options, IndexResponse::fromXContent, emptySet());
}
/**
* Asynchronously index a document using the Index API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html">Index API on elastic.co</a>
* @param indexRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void indexAsync(IndexRequest indexRequest, RequestOptions options, ActionListener<IndexResponse> listener) {
performRequestAsyncAndParseEntity(indexRequest, RequestConverters::index, options, IndexResponse::fromXContent, listener,
emptySet());
}
/**
* Updates a document using the Update API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html">Update API on elastic.co</a>
* @param updateRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final UpdateResponse update(UpdateRequest updateRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(updateRequest, RequestConverters::update, options, UpdateResponse::fromXContent, emptySet());
}
/**
* Asynchronously updates a document using the Update API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html">Update API on elastic.co</a>
* @param updateRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void updateAsync(UpdateRequest updateRequest, RequestOptions options, ActionListener<UpdateResponse> listener) {
performRequestAsyncAndParseEntity(updateRequest, RequestConverters::update, options, UpdateResponse::fromXContent, listener,
emptySet());
}
/**
* Deletes a document by id using the Delete API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html">Delete API on elastic.co</a>
* @param deleteRequest the reuqest
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final DeleteResponse delete(DeleteRequest deleteRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(deleteRequest, RequestConverters::delete, options, DeleteResponse::fromXContent,
singleton(404));
}
/**
* Asynchronously deletes a document by id using the Delete API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html">Delete API on elastic.co</a>
* @param deleteRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void deleteAsync(DeleteRequest deleteRequest, RequestOptions options, ActionListener<DeleteResponse> listener) {
performRequestAsyncAndParseEntity(deleteRequest, RequestConverters::delete, options, DeleteResponse::fromXContent, listener,
Collections.singleton(404));
}
/**
* Executes a search request using the Search API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html">Search API on elastic.co</a>
* @param searchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final SearchResponse search(SearchRequest searchRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(searchRequest, RequestConverters::search, options, SearchResponse::fromXContent, emptySet());
}
/**
* Asynchronously executes a search using the Search API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html">Search API on elastic.co</a>
* @param searchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void searchAsync(SearchRequest searchRequest, RequestOptions options, ActionListener<SearchResponse> listener) {
performRequestAsyncAndParseEntity(searchRequest, RequestConverters::search, options, SearchResponse::fromXContent, listener,
emptySet());
}
/**
* Executes a multi search using the msearch API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html">Multi search API on
* elastic.co</a>
* @param multiSearchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
* @deprecated use {@link #msearch(MultiSearchRequest, RequestOptions)} instead
*/
@Deprecated
public final MultiSearchResponse multiSearch(MultiSearchRequest multiSearchRequest, RequestOptions options) throws IOException {
return msearch(multiSearchRequest, options);
}
/**
* Executes a multi search using the msearch API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html">Multi search API on
* elastic.co</a>
* @param multiSearchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final MultiSearchResponse msearch(MultiSearchRequest multiSearchRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(multiSearchRequest, RequestConverters::multiSearch, options, MultiSearchResponse::fromXContext,
emptySet());
}
/**
* Asynchronously executes a multi search using the msearch API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html">Multi search API on
* elastic.co</a>
* @param searchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @deprecated use {@link #msearchAsync(MultiSearchRequest, RequestOptions, ActionListener)} instead
*/
@Deprecated
public final void multiSearchAsync(MultiSearchRequest searchRequest, RequestOptions options,
ActionListener<MultiSearchResponse> listener) {
msearchAsync(searchRequest, options, listener);
}
/**
* Asynchronously executes a multi search using the msearch API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html">Multi search API on
* elastic.co</a>
* @param searchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void msearchAsync(MultiSearchRequest searchRequest, RequestOptions options,
ActionListener<MultiSearchResponse> listener) {
performRequestAsyncAndParseEntity(searchRequest, RequestConverters::multiSearch, options, MultiSearchResponse::fromXContext,
listener, emptySet());
}
/**
* Executes a search using the Search Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html">Search Scroll
* API on elastic.co</a>
* @param searchScrollRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
* @deprecated use {@link #scroll(SearchScrollRequest, RequestOptions)} instead
*/
@Deprecated
public final SearchResponse searchScroll(SearchScrollRequest searchScrollRequest, RequestOptions options) throws IOException {
return scroll(searchScrollRequest, options);
}
/**
* Executes a search using the Search Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html">Search Scroll
* API on elastic.co</a>
* @param searchScrollRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final SearchResponse scroll(SearchScrollRequest searchScrollRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(searchScrollRequest, RequestConverters::searchScroll, options, SearchResponse::fromXContent,
emptySet());
}
/**
* Asynchronously executes a search using the Search Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html">Search Scroll
* API on elastic.co</a>
* @param searchScrollRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @deprecated use {@link #scrollAsync(SearchScrollRequest, RequestOptions, ActionListener)} instead
*/
@Deprecated
public final void searchScrollAsync(SearchScrollRequest searchScrollRequest, RequestOptions options,
ActionListener<SearchResponse> listener) {
scrollAsync(searchScrollRequest, options, listener);
}
/**
* Asynchronously executes a search using the Search Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html">Search Scroll
* API on elastic.co</a>
* @param searchScrollRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void scrollAsync(SearchScrollRequest searchScrollRequest, RequestOptions options,
ActionListener<SearchResponse> listener) {
performRequestAsyncAndParseEntity(searchScrollRequest, RequestConverters::searchScroll, options, SearchResponse::fromXContent,
listener, emptySet());
}
/**
* Clears one or more scroll ids using the Clear Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html#_clear_scroll_api">
* Clear Scroll API on elastic.co</a>
* @param clearScrollRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final ClearScrollResponse clearScroll(ClearScrollRequest clearScrollRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(clearScrollRequest, RequestConverters::clearScroll, options, ClearScrollResponse::fromXContent,
emptySet());
}
/**
* Asynchronously clears one or more scroll ids using the Clear Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html#_clear_scroll_api">
* Clear Scroll API on elastic.co</a>
* @param clearScrollRequest the reuqest
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void clearScrollAsync(ClearScrollRequest clearScrollRequest, RequestOptions options,
ActionListener<ClearScrollResponse> listener) {
performRequestAsyncAndParseEntity(clearScrollRequest, RequestConverters::clearScroll, options, ClearScrollResponse::fromXContent,
listener, emptySet());
}
/**
* Executes a request using the Search Template API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html">Search Template API
* on elastic.co</a>.
* @param searchTemplateRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final SearchTemplateResponse searchTemplate(SearchTemplateRequest searchTemplateRequest,
RequestOptions options) throws IOException {
return performRequestAndParseEntity(searchTemplateRequest, RequestConverters::searchTemplate, options,
SearchTemplateResponse::fromXContent, emptySet());
}
/**
* Asynchronously executes a request using the Search Template API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html">Search Template API
* on elastic.co</a>.
*/
public final void searchTemplateAsync(SearchTemplateRequest searchTemplateRequest, RequestOptions options,
ActionListener<SearchTemplateResponse> listener) {
performRequestAsyncAndParseEntity(searchTemplateRequest, RequestConverters::searchTemplate, options,
SearchTemplateResponse::fromXContent, listener, emptySet());
}
/**
* Executes a request using the Explain API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html">Explain API on elastic.co</a>
* @param explainRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final ExplainResponse explain(ExplainRequest explainRequest, RequestOptions options) throws IOException {
return performRequest(explainRequest, RequestConverters::explain, options,
response -> {
CheckedFunction<XContentParser, ExplainResponse, IOException> entityParser =
parser -> ExplainResponse.fromXContent(parser, convertExistsResponse(response));
return parseEntity(response.getEntity(), entityParser);
},
singleton(404));
}
/**
* Asynchronously executes a request using the Explain API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html">Explain API on elastic.co</a>
* @param explainRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void explainAsync(ExplainRequest explainRequest, RequestOptions options, ActionListener<ExplainResponse> listener) {
performRequestAsync(explainRequest, RequestConverters::explain, options,
response -> {
CheckedFunction<XContentParser, ExplainResponse, IOException> entityParser =
parser -> ExplainResponse.fromXContent(parser, convertExistsResponse(response));
return parseEntity(response.getEntity(), entityParser);
},
listener, singleton(404));
}
/**
* Executes a request using the Ranking Evaluation API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-rank-eval.html">Ranking Evaluation API
* on elastic.co</a>
* @param rankEvalRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final RankEvalResponse rankEval(RankEvalRequest rankEvalRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(rankEvalRequest, RequestConverters::rankEval, options, RankEvalResponse::fromXContent,
emptySet());
}
/**
* Executes a request using the Multi Search Template API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-search-template.html">Multi Search Template API
* on elastic.co</a>.
*/
public final MultiSearchTemplateResponse msearchTemplate(MultiSearchTemplateRequest multiSearchTemplateRequest,
RequestOptions options) throws IOException {
return performRequestAndParseEntity(multiSearchTemplateRequest, RequestConverters::multiSearchTemplate,
options, MultiSearchTemplateResponse::fromXContext, emptySet());
}
/**
* Asynchronously executes a request using the Multi Search Template API
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-search-template.html">Multi Search Template API
* on elastic.co</a>.
*/
public final void msearchTemplateAsync(MultiSearchTemplateRequest multiSearchTemplateRequest,
RequestOptions options,
ActionListener<MultiSearchTemplateResponse> listener) {
performRequestAsyncAndParseEntity(multiSearchTemplateRequest, RequestConverters::multiSearchTemplate,
options, MultiSearchTemplateResponse::fromXContext, listener, emptySet());
}
/**
* Asynchronously executes a request using the Ranking Evaluation API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-rank-eval.html">Ranking Evaluation API
* on elastic.co</a>
* @param rankEvalRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void rankEvalAsync(RankEvalRequest rankEvalRequest, RequestOptions options, ActionListener<RankEvalResponse> listener) {
performRequestAsyncAndParseEntity(rankEvalRequest, RequestConverters::rankEval, options, RankEvalResponse::fromXContent, listener,
emptySet());
}
/**
* Executes a request using the Field Capabilities API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html">Field Capabilities API
* on elastic.co</a>.
* @param fieldCapabilitiesRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final FieldCapabilitiesResponse fieldCaps(FieldCapabilitiesRequest fieldCapabilitiesRequest,
RequestOptions options) throws IOException {
return performRequestAndParseEntity(fieldCapabilitiesRequest, RequestConverters::fieldCaps, options,
FieldCapabilitiesResponse::fromXContent, emptySet());
}
/**
* Get stored script by id.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html">
* How to use scripts on elastic.co</a>
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public GetStoredScriptResponse getScript(GetStoredScriptRequest request, RequestOptions options) throws IOException {
return performRequestAndParseEntity(request, RequestConverters::getScript, options,
GetStoredScriptResponse::fromXContent, emptySet());
}
/**
* Asynchronously get stored script by id.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html">
* How to use scripts on elastic.co</a>
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public void getScriptAsync(GetStoredScriptRequest request, RequestOptions options,
ActionListener<GetStoredScriptResponse> listener) {
performRequestAsyncAndParseEntity(request, RequestConverters::getScript, options,
GetStoredScriptResponse::fromXContent, listener, emptySet());
}
/**
* Delete stored script by id.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html">
* How to use scripts on elastic.co</a>
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public AcknowledgedResponse deleteScript(DeleteStoredScriptRequest request, RequestOptions options) throws IOException {
return performRequestAndParseEntity(request, RequestConverters::deleteScript, options,
AcknowledgedResponse::fromXContent, emptySet());
}
/**
* Asynchronously delete stored script by id.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html">
* How to use scripts on elastic.co</a>
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public void deleteScriptAsync(DeleteStoredScriptRequest request, RequestOptions options,
ActionListener<AcknowledgedResponse> listener) {
performRequestAsyncAndParseEntity(request, RequestConverters::deleteScript, options,
AcknowledgedResponse::fromXContent, listener, emptySet());
}
/**
* Asynchronously executes a request using the Field Capabilities API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html">Field Capabilities API
* on elastic.co</a>.
* @param fieldCapabilitiesRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void fieldCapsAsync(FieldCapabilitiesRequest fieldCapabilitiesRequest, RequestOptions options,
ActionListener<FieldCapabilitiesResponse> listener) {
performRequestAsyncAndParseEntity(fieldCapabilitiesRequest, RequestConverters::fieldCaps, options,
FieldCapabilitiesResponse::fromXContent, listener, emptySet());
}
/**
* @deprecated If creating a new HLRC ReST API call, consider creating new actions instead of reusing server actions. The Validation
* layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}.
*/
@Deprecated
protected final <Req extends ActionRequest, Resp> Resp performRequestAndParseEntity(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<XContentParser, Resp, IOException> entityParser,
Set<Integer> ignores) throws IOException {
return performRequest(request, requestConverter, options,
response -> parseEntity(response.getEntity(), entityParser), ignores);
}
/**
* Defines a helper method for performing a request and then parsing the returned entity using the provided entityParser.
*/
protected final <Req extends Validatable, Resp> Resp performRequestAndParseEntity(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<XContentParser, Resp, IOException> entityParser,
Set<Integer> ignores) throws IOException {
return performRequest(request, requestConverter, options,
response -> parseEntity(response.getEntity(), entityParser), ignores);
}
/**
* @deprecated If creating a new HLRC ReST API call, consider creating new actions instead of reusing server actions. The Validation
* layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}.
*/
@Deprecated
protected final <Req extends ActionRequest, Resp> Resp performRequest(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
Set<Integer> ignores) throws IOException {
ActionRequestValidationException validationException = request.validate();
if (validationException != null && validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
return internalPerformRequest(request, requestConverter, options, responseConverter, ignores);
}
/**
* Defines a helper method for performing a request.
*/
protected final <Req extends Validatable, Resp> Resp performRequest(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
Set<Integer> ignores) throws IOException {
ValidationException validationException = request.validate();
if (validationException != null && validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
return internalPerformRequest(request, requestConverter, options, responseConverter, ignores);
}
/**
* Provides common functionality for performing a request.
*/
private <Req, Resp> Resp internalPerformRequest(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
Set<Integer> ignores) throws IOException {
Request req = requestConverter.apply(request);
req.setOptions(options);
Response response;
try {
response = client.performRequest(req);
} catch (ResponseException e) {
if (ignores.contains(e.getResponse().getStatusLine().getStatusCode())) {
try {
return responseConverter.apply(e.getResponse());
} catch (Exception innerException) {
// the exception is ignored as we now try to parse the response as an error.
// this covers cases like get where 404 can either be a valid document not found response,
// or an error for which parsing is completely different. We try to consider the 404 response as a valid one
// first. If parsing of the response breaks, we fall back to parsing it as an error.
throw parseResponseException(e);
}
}
throw parseResponseException(e);
}
try {
return responseConverter.apply(response);
} catch(Exception e) {
throw new IOException("Unable to parse response body for " + response, e);
}
}
/**
* @deprecated If creating a new HLRC ReST API call, consider creating new actions instead of reusing server actions. The Validation
* layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}.
*/
@Deprecated
protected final <Req extends ActionRequest, Resp> void performRequestAsyncAndParseEntity(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<XContentParser, Resp, IOException> entityParser,
ActionListener<Resp> listener, Set<Integer> ignores) {
performRequestAsync(request, requestConverter, options,
response -> parseEntity(response.getEntity(), entityParser), listener, ignores);
}
/**
* Defines a helper method for asynchronously performing a request.
*/
protected final <Req extends Validatable, Resp> void performRequestAsyncAndParseEntity(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<XContentParser, Resp, IOException> entityParser,
ActionListener<Resp> listener, Set<Integer> ignores) {
performRequestAsync(request, requestConverter, options,
response -> parseEntity(response.getEntity(), entityParser), listener, ignores);
}
/**
* @deprecated If creating a new HLRC ReST API call, consider creating new actions instead of reusing server actions. The Validation
* layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}.
*/
@Deprecated
protected final <Req extends ActionRequest, Resp> void performRequestAsync(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
ActionListener<Resp> listener, Set<Integer> ignores) {
ActionRequestValidationException validationException = request.validate();
if (validationException != null && validationException.validationErrors().isEmpty() == false) {
listener.onFailure(validationException);
return;
}
internalPerformRequestAsync(request, requestConverter, options, responseConverter, listener, ignores);
}
/**
* Defines a helper method for asynchronously performing a request.
*/
protected final <Req extends Validatable, Resp> void performRequestAsync(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
ActionListener<Resp> listener, Set<Integer> ignores) {
ValidationException validationException = request.validate();
if (validationException != null && validationException.validationErrors().isEmpty() == false) {
listener.onFailure(validationException);
return;
}
internalPerformRequestAsync(request, requestConverter, options, responseConverter, listener, ignores);
}
/**
* Provides common functionality for asynchronously performing a request.
*/
private <Req, Resp> void internalPerformRequestAsync(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
ActionListener<Resp> listener, Set<Integer> ignores) {
Request req;
try {
req = requestConverter.apply(request);
} catch (Exception e) {
listener.onFailure(e);
return;
}
req.setOptions(options);
ResponseListener responseListener = wrapResponseListener(responseConverter, listener, ignores);
client.performRequestAsync(req, responseListener);
}
final <Resp> ResponseListener wrapResponseListener(CheckedFunction<Response, Resp, IOException> responseConverter,
ActionListener<Resp> actionListener, Set<Integer> ignores) {
return new ResponseListener() {
@Override
public void onSuccess(Response response) {
try {
actionListener.onResponse(responseConverter.apply(response));
} catch(Exception e) {
IOException ioe = new IOException("Unable to parse response body for " + response, e);
onFailure(ioe);
}
}
@Override
public void onFailure(Exception exception) {
if (exception instanceof ResponseException) {
ResponseException responseException = (ResponseException) exception;
Response response = responseException.getResponse();
if (ignores.contains(response.getStatusLine().getStatusCode())) {
try {
actionListener.onResponse(responseConverter.apply(response));
} catch (Exception innerException) {
// the exception is ignored as we now try to parse the response as an error.
// this covers cases like get where 404 can either be a valid document not found response,
// or an error for which parsing is completely different. We try to consider the 404 response as a valid one
// first. If parsing of the response breaks, we fall back to parsing it as an error.
actionListener.onFailure(parseResponseException(responseException));
}
} else {
actionListener.onFailure(parseResponseException(responseException));
}
} else {
actionListener.onFailure(exception);
}
}
};
}
/**
* Converts a {@link ResponseException} obtained from the low level REST client into an {@link ElasticsearchException}.
* If a response body was returned, tries to parse it as an error returned from Elasticsearch.
* If no response body was returned or anything goes wrong while parsing the error, returns a new {@link ElasticsearchStatusException}
* that wraps the original {@link ResponseException}. The potential exception obtained while parsing is added to the returned
* exception as a suppressed exception. This method is guaranteed to not throw any exception eventually thrown while parsing.
*/
protected final ElasticsearchStatusException parseResponseException(ResponseException responseException) {
Response response = responseException.getResponse();
HttpEntity entity = response.getEntity();
ElasticsearchStatusException elasticsearchException;
if (entity == null) {
elasticsearchException = new ElasticsearchStatusException(
responseException.getMessage(), RestStatus.fromCode(response.getStatusLine().getStatusCode()), responseException);
} else {
try {
elasticsearchException = parseEntity(entity, BytesRestResponse::errorFromXContent);
elasticsearchException.addSuppressed(responseException);
} catch (Exception e) {
RestStatus restStatus = RestStatus.fromCode(response.getStatusLine().getStatusCode());
elasticsearchException = new ElasticsearchStatusException("Unable to parse response body", restStatus, responseException);
elasticsearchException.addSuppressed(e);
}
}
return elasticsearchException;
}
protected final <Resp> Resp parseEntity(final HttpEntity entity,
final CheckedFunction<XContentParser, Resp, IOException> entityParser) throws IOException {
if (entity == null) {
throw new IllegalStateException("Response body expected but not returned");
}
if (entity.getContentType() == null) {
throw new IllegalStateException("Elasticsearch didn't return the [Content-Type] header, unable to parse response body");
}
XContentType xContentType = XContentType.fromMediaTypeOrFormat(entity.getContentType().getValue());
if (xContentType == null) {
throw new IllegalStateException("Unsupported Content-Type: " + entity.getContentType().getValue());
}
try (XContentParser parser = xContentType.xContent().createParser(registry, DEPRECATION_HANDLER, entity.getContent())) {
return entityParser.apply(parser);
}
}
static boolean convertExistsResponse(Response response) {
return response.getStatusLine().getStatusCode() == 200;
}
/**
* Ignores deprecation warnings. This is appropriate because it is only
* used to parse responses from Elasticsearch. Any deprecation warnings
* emitted there just mean that you are talking to an old version of
* Elasticsearch. There isn't anything you can do about the deprecation.
*/
private static final DeprecationHandler DEPRECATION_HANDLER = new DeprecationHandler() {
@Override
public void usedDeprecatedName(String usedName, String modernName) {}
@Override
public void usedDeprecatedField(String usedName, String replacedWith) {}
};
static List<NamedXContentRegistry.Entry> getDefaultNamedXContents() {
Map<String, ContextParser<Object, ? extends Aggregation>> map = new HashMap<>();
map.put(CardinalityAggregationBuilder.NAME, (p, c) -> ParsedCardinality.fromXContent(p, (String) c));
map.put(InternalHDRPercentiles.NAME, (p, c) -> ParsedHDRPercentiles.fromXContent(p, (String) c));
map.put(InternalHDRPercentileRanks.NAME, (p, c) -> ParsedHDRPercentileRanks.fromXContent(p, (String) c));
map.put(InternalTDigestPercentiles.NAME, (p, c) -> ParsedTDigestPercentiles.fromXContent(p, (String) c));
map.put(InternalTDigestPercentileRanks.NAME, (p, c) -> ParsedTDigestPercentileRanks.fromXContent(p, (String) c));
map.put(PercentilesBucketPipelineAggregationBuilder.NAME, (p, c) -> ParsedPercentilesBucket.fromXContent(p, (String) c));
map.put(MinAggregationBuilder.NAME, (p, c) -> ParsedMin.fromXContent(p, (String) c));
map.put(MaxAggregationBuilder.NAME, (p, c) -> ParsedMax.fromXContent(p, (String) c));
map.put(SumAggregationBuilder.NAME, (p, c) -> ParsedSum.fromXContent(p, (String) c));
map.put(AvgAggregationBuilder.NAME, (p, c) -> ParsedAvg.fromXContent(p, (String) c));
map.put(ValueCountAggregationBuilder.NAME, (p, c) -> ParsedValueCount.fromXContent(p, (String) c));
map.put(InternalSimpleValue.NAME, (p, c) -> ParsedSimpleValue.fromXContent(p, (String) c));
map.put(DerivativePipelineAggregationBuilder.NAME, (p, c) -> ParsedDerivative.fromXContent(p, (String) c));
map.put(InternalBucketMetricValue.NAME, (p, c) -> ParsedBucketMetricValue.fromXContent(p, (String) c));
map.put(StatsAggregationBuilder.NAME, (p, c) -> ParsedStats.fromXContent(p, (String) c));
map.put(StatsBucketPipelineAggregationBuilder.NAME, (p, c) -> ParsedStatsBucket.fromXContent(p, (String) c));
map.put(ExtendedStatsAggregationBuilder.NAME, (p, c) -> ParsedExtendedStats.fromXContent(p, (String) c));
map.put(ExtendedStatsBucketPipelineAggregationBuilder.NAME,
(p, c) -> ParsedExtendedStatsBucket.fromXContent(p, (String) c));
map.put(GeoBoundsAggregationBuilder.NAME, (p, c) -> ParsedGeoBounds.fromXContent(p, (String) c));
map.put(GeoCentroidAggregationBuilder.NAME, (p, c) -> ParsedGeoCentroid.fromXContent(p, (String) c));
map.put(HistogramAggregationBuilder.NAME, (p, c) -> ParsedHistogram.fromXContent(p, (String) c));
map.put(DateHistogramAggregationBuilder.NAME, (p, c) -> ParsedDateHistogram.fromXContent(p, (String) c));
map.put(AutoDateHistogramAggregationBuilder.NAME, (p, c) -> ParsedAutoDateHistogram.fromXContent(p, (String) c));
map.put(StringTerms.NAME, (p, c) -> ParsedStringTerms.fromXContent(p, (String) c));
map.put(LongTerms.NAME, (p, c) -> ParsedLongTerms.fromXContent(p, (String) c));
map.put(DoubleTerms.NAME, (p, c) -> ParsedDoubleTerms.fromXContent(p, (String) c));
map.put(MissingAggregationBuilder.NAME, (p, c) -> ParsedMissing.fromXContent(p, (String) c));
map.put(NestedAggregationBuilder.NAME, (p, c) -> ParsedNested.fromXContent(p, (String) c));
map.put(ReverseNestedAggregationBuilder.NAME, (p, c) -> ParsedReverseNested.fromXContent(p, (String) c));
map.put(GlobalAggregationBuilder.NAME, (p, c) -> ParsedGlobal.fromXContent(p, (String) c));
map.put(FilterAggregationBuilder.NAME, (p, c) -> ParsedFilter.fromXContent(p, (String) c));
map.put(InternalSampler.PARSER_NAME, (p, c) -> ParsedSampler.fromXContent(p, (String) c));
map.put(GeoGridAggregationBuilder.NAME, (p, c) -> ParsedGeoHashGrid.fromXContent(p, (String) c));
map.put(RangeAggregationBuilder.NAME, (p, c) -> ParsedRange.fromXContent(p, (String) c));
map.put(DateRangeAggregationBuilder.NAME, (p, c) -> ParsedDateRange.fromXContent(p, (String) c));
map.put(GeoDistanceAggregationBuilder.NAME, (p, c) -> ParsedGeoDistance.fromXContent(p, (String) c));
map.put(FiltersAggregationBuilder.NAME, (p, c) -> ParsedFilters.fromXContent(p, (String) c));
map.put(AdjacencyMatrixAggregationBuilder.NAME, (p, c) -> ParsedAdjacencyMatrix.fromXContent(p, (String) c));
map.put(SignificantLongTerms.NAME, (p, c) -> ParsedSignificantLongTerms.fromXContent(p, (String) c));
map.put(SignificantStringTerms.NAME, (p, c) -> ParsedSignificantStringTerms.fromXContent(p, (String) c));
map.put(ScriptedMetricAggregationBuilder.NAME, (p, c) -> ParsedScriptedMetric.fromXContent(p, (String) c));
map.put(IpRangeAggregationBuilder.NAME, (p, c) -> ParsedBinaryRange.fromXContent(p, (String) c));
map.put(TopHitsAggregationBuilder.NAME, (p, c) -> ParsedTopHits.fromXContent(p, (String) c));
map.put(CompositeAggregationBuilder.NAME, (p, c) -> ParsedComposite.fromXContent(p, (String) c));
List<NamedXContentRegistry.Entry> entries = map.entrySet().stream()
.map(entry -> new NamedXContentRegistry.Entry(Aggregation.class, new ParseField(entry.getKey()), entry.getValue()))
.collect(Collectors.toList());
entries.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField(TermSuggestionBuilder.SUGGESTION_NAME),
(parser, context) -> TermSuggestion.fromXContent(parser, (String)context)));
entries.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField(PhraseSuggestionBuilder.SUGGESTION_NAME),
(parser, context) -> PhraseSuggestion.fromXContent(parser, (String)context)));
entries.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField(CompletionSuggestionBuilder.SUGGESTION_NAME),
(parser, context) -> CompletionSuggestion.fromXContent(parser, (String)context)));
return entries;
}
/**
* Loads and returns the {@link NamedXContentRegistry.Entry} parsers provided by plugins.
*/
static List<NamedXContentRegistry.Entry> getProvidedNamedXContents() {
List<NamedXContentRegistry.Entry> entries = new ArrayList<>();
for (NamedXContentProvider service : ServiceLoader.load(NamedXContentProvider.class)) {
entries.addAll(service.getNamedXContentParsers());
}
return entries;
}
}
| client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest;
import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest;
import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.explain.ExplainRequest;
import org.elasticsearch.action.explain.ExplainResponse;
import org.elasticsearch.action.fieldcaps.FieldCapabilitiesRequest;
import org.elasticsearch.action.fieldcaps.FieldCapabilitiesResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.main.MainRequest;
import org.elasticsearch.action.main.MainResponse;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.ClearScrollResponse;
import org.elasticsearch.action.search.MultiSearchRequest;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.common.CheckedConsumer;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ContextParser;
import org.elasticsearch.common.xcontent.DeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.rankeval.RankEvalRequest;
import org.elasticsearch.index.rankeval.RankEvalResponse;
import org.elasticsearch.plugins.spi.NamedXContentProvider;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.script.mustache.MultiSearchTemplateRequest;
import org.elasticsearch.script.mustache.MultiSearchTemplateResponse;
import org.elasticsearch.script.mustache.SearchTemplateRequest;
import org.elasticsearch.script.mustache.SearchTemplateResponse;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.bucket.adjacency.AdjacencyMatrixAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.adjacency.ParsedAdjacencyMatrix;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.ParsedComposite;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.FiltersAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilters;
import org.elasticsearch.search.aggregations.bucket.geogrid.GeoGridAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.geogrid.ParsedGeoHashGrid;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.ParsedGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.AutoDateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.ParsedAutoDateHistogram;
import org.elasticsearch.search.aggregations.bucket.histogram.ParsedDateHistogram;
import org.elasticsearch.search.aggregations.bucket.histogram.ParsedHistogram;
import org.elasticsearch.search.aggregations.bucket.missing.MissingAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.missing.ParsedMissing;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedReverseNested;
import org.elasticsearch.search.aggregations.bucket.nested.ReverseNestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.range.DateRangeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.range.GeoDistanceAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.range.IpRangeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.range.ParsedBinaryRange;
import org.elasticsearch.search.aggregations.bucket.range.ParsedDateRange;
import org.elasticsearch.search.aggregations.bucket.range.ParsedGeoDistance;
import org.elasticsearch.search.aggregations.bucket.range.ParsedRange;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.sampler.InternalSampler;
import org.elasticsearch.search.aggregations.bucket.sampler.ParsedSampler;
import org.elasticsearch.search.aggregations.bucket.significant.ParsedSignificantLongTerms;
import org.elasticsearch.search.aggregations.bucket.significant.ParsedSignificantStringTerms;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantLongTerms;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.DoubleTerms;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedDoubleTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.avg.ParsedAvg;
import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.ParsedCardinality;
import org.elasticsearch.search.aggregations.metrics.geobounds.GeoBoundsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.geobounds.ParsedGeoBounds;
import org.elasticsearch.search.aggregations.metrics.geocentroid.GeoCentroidAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.geocentroid.ParsedGeoCentroid;
import org.elasticsearch.search.aggregations.metrics.max.MaxAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.max.ParsedMax;
import org.elasticsearch.search.aggregations.metrics.min.MinAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.min.ParsedMin;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.InternalHDRPercentileRanks;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.InternalHDRPercentiles;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.ParsedHDRPercentileRanks;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.ParsedHDRPercentiles;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.InternalTDigestPercentileRanks;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.InternalTDigestPercentiles;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.ParsedTDigestPercentileRanks;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.ParsedTDigestPercentiles;
import org.elasticsearch.search.aggregations.metrics.scripted.ParsedScriptedMetric;
import org.elasticsearch.search.aggregations.metrics.scripted.ScriptedMetricAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.ParsedStats;
import org.elasticsearch.search.aggregations.metrics.stats.StatsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStatsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ParsedExtendedStats;
import org.elasticsearch.search.aggregations.metrics.sum.ParsedSum;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.tophits.ParsedTopHits;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHitsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.valuecount.ParsedValueCount;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.InternalSimpleValue;
import org.elasticsearch.search.aggregations.pipeline.ParsedSimpleValue;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.InternalBucketMetricValue;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.ParsedBucketMetricValue;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.percentile.ParsedPercentilesBucket;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.percentile.PercentilesBucketPipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.ParsedStatsBucket;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.StatsBucketPipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ExtendedStatsBucketPipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ParsedExtendedStatsBucket;
import org.elasticsearch.search.aggregations.pipeline.derivative.DerivativePipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.derivative.ParsedDerivative;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.elasticsearch.search.suggest.phrase.PhraseSuggestion;
import org.elasticsearch.search.suggest.phrase.PhraseSuggestionBuilder;
import org.elasticsearch.search.suggest.term.TermSuggestion;
import org.elasticsearch.search.suggest.term.TermSuggestionBuilder;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toList;
/**
* High level REST client that wraps an instance of the low level {@link RestClient} and allows to build requests and read responses.
* The {@link RestClient} instance is internally built based on the provided {@link RestClientBuilder} and it gets closed automatically
* when closing the {@link RestHighLevelClient} instance that wraps it.
* In case an already existing instance of a low-level REST client needs to be provided, this class can be subclassed and the
* {@link #RestHighLevelClient(RestClient, CheckedConsumer, List)} constructor can be used.
* This class can also be sub-classed to expose additional client methods that make use of endpoints added to Elasticsearch through
* plugins, or to add support for custom response sections, again added to Elasticsearch through plugins.
*/
public class RestHighLevelClient implements Closeable {
private final RestClient client;
private final NamedXContentRegistry registry;
private final CheckedConsumer<RestClient, IOException> doClose;
private final IndicesClient indicesClient = new IndicesClient(this);
private final ClusterClient clusterClient = new ClusterClient(this);
private final IngestClient ingestClient = new IngestClient(this);
private final SnapshotClient snapshotClient = new SnapshotClient(this);
private final TasksClient tasksClient = new TasksClient(this);
private final XPackClient xPackClient = new XPackClient(this);
private final WatcherClient watcherClient = new WatcherClient(this);
private final GraphClient graphClient = new GraphClient(this);
private final LicenseClient licenseClient = new LicenseClient(this);
private final MigrationClient migrationClient = new MigrationClient(this);
private final MachineLearningClient machineLearningClient = new MachineLearningClient(this);
/**
* Creates a {@link RestHighLevelClient} given the low level {@link RestClientBuilder} that allows to build the
* {@link RestClient} to be used to perform requests.
*/
public RestHighLevelClient(RestClientBuilder restClientBuilder) {
this(restClientBuilder, Collections.emptyList());
}
/**
* Creates a {@link RestHighLevelClient} given the low level {@link RestClientBuilder} that allows to build the
* {@link RestClient} to be used to perform requests and parsers for custom response sections added to Elasticsearch through plugins.
*/
protected RestHighLevelClient(RestClientBuilder restClientBuilder, List<NamedXContentRegistry.Entry> namedXContentEntries) {
this(restClientBuilder.build(), RestClient::close, namedXContentEntries);
}
/**
* Creates a {@link RestHighLevelClient} given the low level {@link RestClient} that it should use to perform requests and
* a list of entries that allow to parse custom response sections added to Elasticsearch through plugins.
* This constructor can be called by subclasses in case an externally created low-level REST client needs to be provided.
* The consumer argument allows to control what needs to be done when the {@link #close()} method is called.
* Also subclasses can provide parsers for custom response sections added to Elasticsearch through plugins.
*/
protected RestHighLevelClient(RestClient restClient, CheckedConsumer<RestClient, IOException> doClose,
List<NamedXContentRegistry.Entry> namedXContentEntries) {
this.client = Objects.requireNonNull(restClient, "restClient must not be null");
this.doClose = Objects.requireNonNull(doClose, "doClose consumer must not be null");
this.registry = new NamedXContentRegistry(
Stream.of(getDefaultNamedXContents().stream(), getProvidedNamedXContents().stream(), namedXContentEntries.stream())
.flatMap(Function.identity()).collect(toList()));
}
/**
* Returns the low-level client that the current high-level client instance is using to perform requests
*/
public final RestClient getLowLevelClient() {
return client;
}
@Override
public final void close() throws IOException {
doClose.accept(client);
}
/**
* Provides an {@link IndicesClient} which can be used to access the Indices API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices.html">Indices API on elastic.co</a>
*/
public final IndicesClient indices() {
return indicesClient;
}
/**
* Provides a {@link ClusterClient} which can be used to access the Cluster API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster.html">Cluster API on elastic.co</a>
*/
public final ClusterClient cluster() {
return clusterClient;
}
/**
* Provides a {@link IngestClient} which can be used to access the Ingest API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/ingest.html">Ingest API on elastic.co</a>
*/
public final IngestClient ingest() {
return ingestClient;
}
/**
* Provides a {@link SnapshotClient} which can be used to access the Snapshot API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html">Snapshot API on elastic.co</a>
*/
public final SnapshotClient snapshot() {
return snapshotClient;
}
/**
* Provides a {@link TasksClient} which can be used to access the Tasks API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html">Task Management API on elastic.co</a>
*/
public final TasksClient tasks() {
return tasksClient;
}
/**
* Provides methods for accessing the Elastic Licensed X-Pack Info
* and Usage APIs that are shipped with the default distribution of
* Elasticsearch. All of these APIs will 404 if run against the OSS
* distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/info-api.html">
* Info APIs on elastic.co</a> for more information.
*/
public final XPackClient xpack() {
return xPackClient;
}
/**
* Provides methods for accessing the Elastic Licensed Watcher APIs that
* are shipped with the default distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api.html">
* Watcher APIs on elastic.co</a> for more information.
*/
public WatcherClient watcher() { return watcherClient; }
/**
* Provides methods for accessing the Elastic Licensed Graph explore API that
* is shipped with the default distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/graph-explore-api.html">
* Graph API on elastic.co</a> for more information.
*/
public GraphClient graph() { return graphClient; }
/**
* Provides methods for accessing the Elastic Licensed Licensing APIs that
* are shipped with the default distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/licensing-apis.html">
* Licensing APIs on elastic.co</a> for more information.
*/
public LicenseClient license() { return licenseClient; }
/**
* Provides methods for accessing the Elastic Licensed Licensing APIs that
* are shipped with the default distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/migration-api.html">
* Migration APIs on elastic.co</a> for more information.
*/
public MigrationClient migration() {
return migrationClient;
}
/**
* Provides methods for accessing the Elastic Licensed Machine Learning APIs that
* are shipped with the Elastic Stack distribution of Elasticsearch. All of
* these APIs will 404 if run against the OSS distribution of Elasticsearch.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/ml-apis.html">
* Machine Learning APIs on elastic.co</a> for more information.
*
* @return the client wrapper for making Machine Learning API calls
*/
public MachineLearningClient machineLearning() {
return machineLearningClient;
}
/**
* Executes a bulk request using the Bulk API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html">Bulk API on elastic.co</a>
* @param bulkRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final BulkResponse bulk(BulkRequest bulkRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(bulkRequest, RequestConverters::bulk, options, BulkResponse::fromXContent, emptySet());
}
/**
* Asynchronously executes a bulk request using the Bulk API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html">Bulk API on elastic.co</a>
* @param bulkRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void bulkAsync(BulkRequest bulkRequest, RequestOptions options, ActionListener<BulkResponse> listener) {
performRequestAsyncAndParseEntity(bulkRequest, RequestConverters::bulk, options, BulkResponse::fromXContent, listener, emptySet());
}
/**
* Pings the remote Elasticsearch cluster and returns true if the ping succeeded, false otherwise
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return <code>true</code> if the ping succeeded, false otherwise
* @throws IOException in case there is a problem sending the request
*/
public final boolean ping(RequestOptions options) throws IOException {
return performRequest(new MainRequest(), (request) -> RequestConverters.ping(), options, RestHighLevelClient::convertExistsResponse,
emptySet());
}
/**
* Get the cluster info otherwise provided when sending an HTTP request to '/'
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final MainResponse info(RequestOptions options) throws IOException {
return performRequestAndParseEntity(new MainRequest(), (request) -> RequestConverters.info(), options,
MainResponse::fromXContent, emptySet());
}
/**
* Retrieves a document by id using the Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html">Get API on elastic.co</a>
* @param getRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final GetResponse get(GetRequest getRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(getRequest, RequestConverters::get, options, GetResponse::fromXContent, singleton(404));
}
/**
* Asynchronously retrieves a document by id using the Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html">Get API on elastic.co</a>
* @param getRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void getAsync(GetRequest getRequest, RequestOptions options, ActionListener<GetResponse> listener) {
performRequestAsyncAndParseEntity(getRequest, RequestConverters::get, options, GetResponse::fromXContent, listener,
singleton(404));
}
/**
* Retrieves multiple documents by id using the Multi Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html">Multi Get API on elastic.co</a>
* @param multiGetRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
* @deprecated use {@link #mget(MultiGetRequest, RequestOptions)} instead
*/
@Deprecated
public final MultiGetResponse multiGet(MultiGetRequest multiGetRequest, RequestOptions options) throws IOException {
return mget(multiGetRequest, options);
}
/**
* Retrieves multiple documents by id using the Multi Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html">Multi Get API on elastic.co</a>
* @param multiGetRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final MultiGetResponse mget(MultiGetRequest multiGetRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(multiGetRequest, RequestConverters::multiGet, options, MultiGetResponse::fromXContent,
singleton(404));
}
/**
* Asynchronously retrieves multiple documents by id using the Multi Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html">Multi Get API on elastic.co</a>
* @param multiGetRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @deprecated use {@link #mgetAsync(MultiGetRequest, RequestOptions, ActionListener)} instead
*/
@Deprecated
public final void multiGetAsync(MultiGetRequest multiGetRequest, RequestOptions options, ActionListener<MultiGetResponse> listener) {
mgetAsync(multiGetRequest, options, listener);
}
/**
* Asynchronously retrieves multiple documents by id using the Multi Get API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html">Multi Get API on elastic.co</a>
* @param multiGetRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void mgetAsync(MultiGetRequest multiGetRequest, RequestOptions options, ActionListener<MultiGetResponse> listener) {
performRequestAsyncAndParseEntity(multiGetRequest, RequestConverters::multiGet, options, MultiGetResponse::fromXContent, listener,
singleton(404));
}
/**
* Checks for the existence of a document. Returns true if it exists, false otherwise.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html">Get API on elastic.co</a>
* @param getRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return <code>true</code> if the document exists, <code>false</code> otherwise
* @throws IOException in case there is a problem sending the request
*/
public final boolean exists(GetRequest getRequest, RequestOptions options) throws IOException {
return performRequest(getRequest, RequestConverters::exists, options, RestHighLevelClient::convertExistsResponse, emptySet());
}
/**
* Asynchronously checks for the existence of a document. Returns true if it exists, false otherwise.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html">Get API on elastic.co</a>
* @param getRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void existsAsync(GetRequest getRequest, RequestOptions options, ActionListener<Boolean> listener) {
performRequestAsync(getRequest, RequestConverters::exists, options, RestHighLevelClient::convertExistsResponse, listener,
emptySet());
}
/**
* Index a document using the Index API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html">Index API on elastic.co</a>
* @param indexRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final IndexResponse index(IndexRequest indexRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(indexRequest, RequestConverters::index, options, IndexResponse::fromXContent, emptySet());
}
/**
* Asynchronously index a document using the Index API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html">Index API on elastic.co</a>
* @param indexRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void indexAsync(IndexRequest indexRequest, RequestOptions options, ActionListener<IndexResponse> listener) {
performRequestAsyncAndParseEntity(indexRequest, RequestConverters::index, options, IndexResponse::fromXContent, listener,
emptySet());
}
/**
* Updates a document using the Update API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html">Update API on elastic.co</a>
* @param updateRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final UpdateResponse update(UpdateRequest updateRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(updateRequest, RequestConverters::update, options, UpdateResponse::fromXContent, emptySet());
}
/**
* Asynchronously updates a document using the Update API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html">Update API on elastic.co</a>
* @param updateRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void updateAsync(UpdateRequest updateRequest, RequestOptions options, ActionListener<UpdateResponse> listener) {
performRequestAsyncAndParseEntity(updateRequest, RequestConverters::update, options, UpdateResponse::fromXContent, listener,
emptySet());
}
/**
* Deletes a document by id using the Delete API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html">Delete API on elastic.co</a>
* @param deleteRequest the reuqest
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final DeleteResponse delete(DeleteRequest deleteRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(deleteRequest, RequestConverters::delete, options, DeleteResponse::fromXContent,
singleton(404));
}
/**
* Asynchronously deletes a document by id using the Delete API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html">Delete API on elastic.co</a>
* @param deleteRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void deleteAsync(DeleteRequest deleteRequest, RequestOptions options, ActionListener<DeleteResponse> listener) {
performRequestAsyncAndParseEntity(deleteRequest, RequestConverters::delete, options, DeleteResponse::fromXContent, listener,
Collections.singleton(404));
}
/**
* Executes a search request using the Search API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html">Search API on elastic.co</a>
* @param searchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final SearchResponse search(SearchRequest searchRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(searchRequest, RequestConverters::search, options, SearchResponse::fromXContent, emptySet());
}
/**
* Asynchronously executes a search using the Search API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html">Search API on elastic.co</a>
* @param searchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void searchAsync(SearchRequest searchRequest, RequestOptions options, ActionListener<SearchResponse> listener) {
performRequestAsyncAndParseEntity(searchRequest, RequestConverters::search, options, SearchResponse::fromXContent, listener,
emptySet());
}
/**
* Executes a multi search using the msearch API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html">Multi search API on
* elastic.co</a>
* @param multiSearchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
* @deprecated use {@link #msearch(MultiSearchRequest, RequestOptions)} instead
*/
@Deprecated
public final MultiSearchResponse multiSearch(MultiSearchRequest multiSearchRequest, RequestOptions options) throws IOException {
return msearch(multiSearchRequest, options);
}
/**
* Executes a multi search using the msearch API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html">Multi search API on
* elastic.co</a>
* @param multiSearchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final MultiSearchResponse msearch(MultiSearchRequest multiSearchRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(multiSearchRequest, RequestConverters::multiSearch, options, MultiSearchResponse::fromXContext,
emptySet());
}
/**
* Asynchronously executes a multi search using the msearch API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html">Multi search API on
* elastic.co</a>
* @param searchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @deprecated use {@link #msearchAsync(MultiSearchRequest, RequestOptions, ActionListener)} instead
*/
@Deprecated
public final void multiSearchAsync(MultiSearchRequest searchRequest, RequestOptions options,
ActionListener<MultiSearchResponse> listener) {
msearchAsync(searchRequest, options, listener);
}
/**
* Asynchronously executes a multi search using the msearch API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html">Multi search API on
* elastic.co</a>
* @param searchRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void msearchAsync(MultiSearchRequest searchRequest, RequestOptions options,
ActionListener<MultiSearchResponse> listener) {
performRequestAsyncAndParseEntity(searchRequest, RequestConverters::multiSearch, options, MultiSearchResponse::fromXContext,
listener, emptySet());
}
/**
* Executes a search using the Search Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html">Search Scroll
* API on elastic.co</a>
* @param searchScrollRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
* @deprecated use {@link #scroll(SearchScrollRequest, RequestOptions)} instead
*/
@Deprecated
public final SearchResponse searchScroll(SearchScrollRequest searchScrollRequest, RequestOptions options) throws IOException {
return scroll(searchScrollRequest, options);
}
/**
* Executes a search using the Search Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html">Search Scroll
* API on elastic.co</a>
* @param searchScrollRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final SearchResponse scroll(SearchScrollRequest searchScrollRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(searchScrollRequest, RequestConverters::searchScroll, options, SearchResponse::fromXContent,
emptySet());
}
/**
* Asynchronously executes a search using the Search Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html">Search Scroll
* API on elastic.co</a>
* @param searchScrollRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @deprecated use {@link #scrollAsync(SearchScrollRequest, RequestOptions, ActionListener)} instead
*/
@Deprecated
public final void searchScrollAsync(SearchScrollRequest searchScrollRequest, RequestOptions options,
ActionListener<SearchResponse> listener) {
scrollAsync(searchScrollRequest, options, listener);
}
/**
* Asynchronously executes a search using the Search Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html">Search Scroll
* API on elastic.co</a>
* @param searchScrollRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void scrollAsync(SearchScrollRequest searchScrollRequest, RequestOptions options,
ActionListener<SearchResponse> listener) {
performRequestAsyncAndParseEntity(searchScrollRequest, RequestConverters::searchScroll, options, SearchResponse::fromXContent,
listener, emptySet());
}
/**
* Clears one or more scroll ids using the Clear Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html#_clear_scroll_api">
* Clear Scroll API on elastic.co</a>
* @param clearScrollRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final ClearScrollResponse clearScroll(ClearScrollRequest clearScrollRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(clearScrollRequest, RequestConverters::clearScroll, options, ClearScrollResponse::fromXContent,
emptySet());
}
/**
* Asynchronously clears one or more scroll ids using the Clear Scroll API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html#_clear_scroll_api">
* Clear Scroll API on elastic.co</a>
* @param clearScrollRequest the reuqest
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void clearScrollAsync(ClearScrollRequest clearScrollRequest, RequestOptions options,
ActionListener<ClearScrollResponse> listener) {
performRequestAsyncAndParseEntity(clearScrollRequest, RequestConverters::clearScroll, options, ClearScrollResponse::fromXContent,
listener, emptySet());
}
/**
* Executes a request using the Search Template API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html">Search Template API
* on elastic.co</a>.
* @param searchTemplateRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final SearchTemplateResponse searchTemplate(SearchTemplateRequest searchTemplateRequest,
RequestOptions options) throws IOException {
return performRequestAndParseEntity(searchTemplateRequest, RequestConverters::searchTemplate, options,
SearchTemplateResponse::fromXContent, emptySet());
}
/**
* Asynchronously executes a request using the Search Template API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html">Search Template API
* on elastic.co</a>.
*/
public final void searchTemplateAsync(SearchTemplateRequest searchTemplateRequest, RequestOptions options,
ActionListener<SearchTemplateResponse> listener) {
performRequestAsyncAndParseEntity(searchTemplateRequest, RequestConverters::searchTemplate, options,
SearchTemplateResponse::fromXContent, listener, emptySet());
}
/**
* Executes a request using the Explain API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html">Explain API on elastic.co</a>
* @param explainRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final ExplainResponse explain(ExplainRequest explainRequest, RequestOptions options) throws IOException {
return performRequest(explainRequest, RequestConverters::explain, options,
response -> {
CheckedFunction<XContentParser, ExplainResponse, IOException> entityParser =
parser -> ExplainResponse.fromXContent(parser, convertExistsResponse(response));
return parseEntity(response.getEntity(), entityParser);
},
singleton(404));
}
/**
* Asynchronously executes a request using the Explain API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html">Explain API on elastic.co</a>
* @param explainRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void explainAsync(ExplainRequest explainRequest, RequestOptions options, ActionListener<ExplainResponse> listener) {
performRequestAsync(explainRequest, RequestConverters::explain, options,
response -> {
CheckedFunction<XContentParser, ExplainResponse, IOException> entityParser =
parser -> ExplainResponse.fromXContent(parser, convertExistsResponse(response));
return parseEntity(response.getEntity(), entityParser);
},
listener, singleton(404));
}
/**
* Executes a request using the Ranking Evaluation API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-rank-eval.html">Ranking Evaluation API
* on elastic.co</a>
* @param rankEvalRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final RankEvalResponse rankEval(RankEvalRequest rankEvalRequest, RequestOptions options) throws IOException {
return performRequestAndParseEntity(rankEvalRequest, RequestConverters::rankEval, options, RankEvalResponse::fromXContent,
emptySet());
}
/**
* Executes a request using the Multi Search Template API.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-search-template.html">Multi Search Template API
* on elastic.co</a>.
*/
public final MultiSearchTemplateResponse msearchTemplate(MultiSearchTemplateRequest multiSearchTemplateRequest,
RequestOptions options) throws IOException {
return performRequestAndParseEntity(multiSearchTemplateRequest, RequestConverters::multiSearchTemplate,
options, MultiSearchTemplateResponse::fromXContext, emptySet());
}
/**
* Asynchronously executes a request using the Multi Search Template API
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-search-template.html">Multi Search Template API
* on elastic.co</a>.
*/
public final void msearchTemplateAsync(MultiSearchTemplateRequest multiSearchTemplateRequest,
RequestOptions options,
ActionListener<MultiSearchTemplateResponse> listener) {
performRequestAsyncAndParseEntity(multiSearchTemplateRequest, RequestConverters::multiSearchTemplate,
options, MultiSearchTemplateResponse::fromXContext, listener, emptySet());
}
/**
* Asynchronously executes a request using the Ranking Evaluation API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-rank-eval.html">Ranking Evaluation API
* on elastic.co</a>
* @param rankEvalRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void rankEvalAsync(RankEvalRequest rankEvalRequest, RequestOptions options, ActionListener<RankEvalResponse> listener) {
performRequestAsyncAndParseEntity(rankEvalRequest, RequestConverters::rankEval, options, RankEvalResponse::fromXContent, listener,
emptySet());
}
/**
* Executes a request using the Field Capabilities API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html">Field Capabilities API
* on elastic.co</a>.
* @param fieldCapabilitiesRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public final FieldCapabilitiesResponse fieldCaps(FieldCapabilitiesRequest fieldCapabilitiesRequest,
RequestOptions options) throws IOException {
return performRequestAndParseEntity(fieldCapabilitiesRequest, RequestConverters::fieldCaps, options,
FieldCapabilitiesResponse::fromXContent, emptySet());
}
/**
* Get stored script by id.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html">
* How to use scripts on elastic.co</a>
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public GetStoredScriptResponse getScript(GetStoredScriptRequest request, RequestOptions options) throws IOException {
return performRequestAndParseEntity(request, RequestConverters::getScript, options,
GetStoredScriptResponse::fromXContent, emptySet());
}
/**
* Asynchronously get stored script by id.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html">
* How to use scripts on elastic.co</a>
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public void getScriptAsync(GetStoredScriptRequest request, RequestOptions options,
ActionListener<GetStoredScriptResponse> listener) {
performRequestAsyncAndParseEntity(request, RequestConverters::getScript, options,
GetStoredScriptResponse::fromXContent, listener, emptySet());
}
/**
* Delete stored script by id.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html">
* How to use scripts on elastic.co</a>
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public AcknowledgedResponse deleteScript(DeleteStoredScriptRequest request, RequestOptions options) throws IOException {
return performRequestAndParseEntity(request, RequestConverters::deleteScript, options,
AcknowledgedResponse::fromXContent, emptySet());
}
/**
* Asynchronously delete stored script by id.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html">
* How to use scripts on elastic.co</a>
* @param request the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public void deleteScriptAsync(DeleteStoredScriptRequest request, RequestOptions options,
ActionListener<AcknowledgedResponse> listener) {
performRequestAsyncAndParseEntity(request, RequestConverters::deleteScript, options,
AcknowledgedResponse::fromXContent, listener, emptySet());
}
/**
* Asynchronously executes a request using the Field Capabilities API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html">Field Capabilities API
* on elastic.co</a>.
* @param fieldCapabilitiesRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public final void fieldCapsAsync(FieldCapabilitiesRequest fieldCapabilitiesRequest, RequestOptions options,
ActionListener<FieldCapabilitiesResponse> listener) {
performRequestAsyncAndParseEntity(fieldCapabilitiesRequest, RequestConverters::fieldCaps, options,
FieldCapabilitiesResponse::fromXContent, listener, emptySet());
}
/**
* @deprecated If creating a new HLRC ReST API call, consider creating new actions instead of reusing server actions. The Validation
* layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}.
*/
@Deprecated
protected final <Req extends ActionRequest, Resp> Resp performRequestAndParseEntity(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<XContentParser, Resp, IOException> entityParser,
Set<Integer> ignores) throws IOException {
return performRequest(request, requestConverter, options,
response -> parseEntity(response.getEntity(), entityParser), ignores);
}
/**
* Defines a helper method for performing a request and then parsing the returned entity using the provided entityParser.
*/
protected final <Req extends Validatable, Resp> Resp performRequestAndParseEntity(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<XContentParser, Resp, IOException> entityParser,
Set<Integer> ignores) throws IOException {
return performRequest(request, requestConverter, options,
response -> parseEntity(response.getEntity(), entityParser), ignores);
}
/**
* @deprecated If creating a new HLRC ReST API call, consider creating new actions instead of reusing server actions. The Validation
* layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}.
*/
@Deprecated
protected final <Req extends ActionRequest, Resp> Resp performRequest(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
Set<Integer> ignores) throws IOException {
ActionRequestValidationException validationException = request.validate();
if (validationException != null && validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
return internalPerformRequest(request, requestConverter, options, responseConverter, ignores);
}
/**
* Defines a helper method for performing a request.
*/
protected final <Req extends Validatable, Resp> Resp performRequest(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
Set<Integer> ignores) throws IOException {
ValidationException validationException = request.validate();
if (validationException != null && validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
return internalPerformRequest(request, requestConverter, options, responseConverter, ignores);
}
/**
* Provides common functionality for performing a request.
*/
private <Req, Resp> Resp internalPerformRequest(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
Set<Integer> ignores) throws IOException {
Request req = requestConverter.apply(request);
req.setOptions(options);
Response response;
try {
response = client.performRequest(req);
} catch (ResponseException e) {
if (ignores.contains(e.getResponse().getStatusLine().getStatusCode())) {
try {
return responseConverter.apply(e.getResponse());
} catch (Exception innerException) {
// the exception is ignored as we now try to parse the response as an error.
// this covers cases like get where 404 can either be a valid document not found response,
// or an error for which parsing is completely different. We try to consider the 404 response as a valid one
// first. If parsing of the response breaks, we fall back to parsing it as an error.
throw parseResponseException(e);
}
}
throw parseResponseException(e);
}
try {
return responseConverter.apply(response);
} catch(Exception e) {
throw new IOException("Unable to parse response body for " + response, e);
}
}
/**
* @deprecated If creating a new HLRC ReST API call, consider creating new actions instead of reusing server actions. The Validation
* layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}.
*/
@Deprecated
protected final <Req extends ActionRequest, Resp> void performRequestAsyncAndParseEntity(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<XContentParser, Resp, IOException> entityParser,
ActionListener<Resp> listener, Set<Integer> ignores) {
performRequestAsync(request, requestConverter, options,
response -> parseEntity(response.getEntity(), entityParser), listener, ignores);
}
/**
* Defines a helper method for asynchronously performing a request.
*/
protected final <Req extends Validatable, Resp> void performRequestAsyncAndParseEntity(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<XContentParser, Resp, IOException> entityParser,
ActionListener<Resp> listener, Set<Integer> ignores) {
performRequestAsync(request, requestConverter, options,
response -> parseEntity(response.getEntity(), entityParser), listener, ignores);
}
/**
* @deprecated If creating a new HLRC ReST API call, consider creating new actions instead of reusing server actions. The Validation
* layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}.
*/
@Deprecated
protected final <Req extends ActionRequest, Resp> void performRequestAsync(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
ActionListener<Resp> listener, Set<Integer> ignores) {
ActionRequestValidationException validationException = request.validate();
if (validationException != null && validationException.validationErrors().isEmpty() == false) {
listener.onFailure(validationException);
return;
}
internalPerformRequestAsync(request, requestConverter, options, responseConverter, listener, ignores);
}
/**
* Defines a helper method for asynchronously performing a request.
*/
protected final <Req extends Validatable, Resp> void performRequestAsync(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
ActionListener<Resp> listener, Set<Integer> ignores) {
ValidationException validationException = request.validate();
if (validationException != null && validationException.validationErrors().isEmpty() == false) {
listener.onFailure(validationException);
return;
}
internalPerformRequestAsync(request, requestConverter, options, responseConverter, listener, ignores);
}
/**
* Provides common functionality for asynchronously performing a request.
*/
private <Req, Resp> void internalPerformRequestAsync(Req request,
CheckedFunction<Req, Request, IOException> requestConverter,
RequestOptions options,
CheckedFunction<Response, Resp, IOException> responseConverter,
ActionListener<Resp> listener, Set<Integer> ignores) {
Request req;
try {
req = requestConverter.apply(request);
} catch (Exception e) {
listener.onFailure(e);
return;
}
req.setOptions(options);
ResponseListener responseListener = wrapResponseListener(responseConverter, listener, ignores);
client.performRequestAsync(req, responseListener);
}
final <Resp> ResponseListener wrapResponseListener(CheckedFunction<Response, Resp, IOException> responseConverter,
ActionListener<Resp> actionListener, Set<Integer> ignores) {
return new ResponseListener() {
@Override
public void onSuccess(Response response) {
try {
actionListener.onResponse(responseConverter.apply(response));
} catch(Exception e) {
IOException ioe = new IOException("Unable to parse response body for " + response, e);
onFailure(ioe);
}
}
@Override
public void onFailure(Exception exception) {
if (exception instanceof ResponseException) {
ResponseException responseException = (ResponseException) exception;
Response response = responseException.getResponse();
if (ignores.contains(response.getStatusLine().getStatusCode())) {
try {
actionListener.onResponse(responseConverter.apply(response));
} catch (Exception innerException) {
// the exception is ignored as we now try to parse the response as an error.
// this covers cases like get where 404 can either be a valid document not found response,
// or an error for which parsing is completely different. We try to consider the 404 response as a valid one
// first. If parsing of the response breaks, we fall back to parsing it as an error.
actionListener.onFailure(parseResponseException(responseException));
}
} else {
actionListener.onFailure(parseResponseException(responseException));
}
} else {
actionListener.onFailure(exception);
}
}
};
}
/**
* Converts a {@link ResponseException} obtained from the low level REST client into an {@link ElasticsearchException}.
* If a response body was returned, tries to parse it as an error returned from Elasticsearch.
* If no response body was returned or anything goes wrong while parsing the error, returns a new {@link ElasticsearchStatusException}
* that wraps the original {@link ResponseException}. The potential exception obtained while parsing is added to the returned
* exception as a suppressed exception. This method is guaranteed to not throw any exception eventually thrown while parsing.
*/
protected final ElasticsearchStatusException parseResponseException(ResponseException responseException) {
Response response = responseException.getResponse();
HttpEntity entity = response.getEntity();
ElasticsearchStatusException elasticsearchException;
if (entity == null) {
elasticsearchException = new ElasticsearchStatusException(
responseException.getMessage(), RestStatus.fromCode(response.getStatusLine().getStatusCode()), responseException);
} else {
try {
elasticsearchException = parseEntity(entity, BytesRestResponse::errorFromXContent);
elasticsearchException.addSuppressed(responseException);
} catch (Exception e) {
RestStatus restStatus = RestStatus.fromCode(response.getStatusLine().getStatusCode());
elasticsearchException = new ElasticsearchStatusException("Unable to parse response body", restStatus, responseException);
elasticsearchException.addSuppressed(e);
}
}
return elasticsearchException;
}
protected final <Resp> Resp parseEntity(final HttpEntity entity,
final CheckedFunction<XContentParser, Resp, IOException> entityParser) throws IOException {
if (entity == null) {
throw new IllegalStateException("Response body expected but not returned");
}
if (entity.getContentType() == null) {
throw new IllegalStateException("Elasticsearch didn't return the [Content-Type] header, unable to parse response body");
}
XContentType xContentType = XContentType.fromMediaTypeOrFormat(entity.getContentType().getValue());
if (xContentType == null) {
throw new IllegalStateException("Unsupported Content-Type: " + entity.getContentType().getValue());
}
try (XContentParser parser = xContentType.xContent().createParser(registry, DEPRECATION_HANDLER, entity.getContent())) {
return entityParser.apply(parser);
}
}
private static RequestOptions optionsForHeaders(Header[] headers) {
RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder();
for (Header header : headers) {
Objects.requireNonNull(header, "header cannot be null");
options.addHeader(header.getName(), header.getValue());
}
return options.build();
}
static boolean convertExistsResponse(Response response) {
return response.getStatusLine().getStatusCode() == 200;
}
/**
* Ignores deprecation warnings. This is appropriate because it is only
* used to parse responses from Elasticsearch. Any deprecation warnings
* emitted there just mean that you are talking to an old version of
* Elasticsearch. There isn't anything you can do about the deprecation.
*/
private static final DeprecationHandler DEPRECATION_HANDLER = new DeprecationHandler() {
@Override
public void usedDeprecatedName(String usedName, String modernName) {}
@Override
public void usedDeprecatedField(String usedName, String replacedWith) {}
};
static List<NamedXContentRegistry.Entry> getDefaultNamedXContents() {
Map<String, ContextParser<Object, ? extends Aggregation>> map = new HashMap<>();
map.put(CardinalityAggregationBuilder.NAME, (p, c) -> ParsedCardinality.fromXContent(p, (String) c));
map.put(InternalHDRPercentiles.NAME, (p, c) -> ParsedHDRPercentiles.fromXContent(p, (String) c));
map.put(InternalHDRPercentileRanks.NAME, (p, c) -> ParsedHDRPercentileRanks.fromXContent(p, (String) c));
map.put(InternalTDigestPercentiles.NAME, (p, c) -> ParsedTDigestPercentiles.fromXContent(p, (String) c));
map.put(InternalTDigestPercentileRanks.NAME, (p, c) -> ParsedTDigestPercentileRanks.fromXContent(p, (String) c));
map.put(PercentilesBucketPipelineAggregationBuilder.NAME, (p, c) -> ParsedPercentilesBucket.fromXContent(p, (String) c));
map.put(MinAggregationBuilder.NAME, (p, c) -> ParsedMin.fromXContent(p, (String) c));
map.put(MaxAggregationBuilder.NAME, (p, c) -> ParsedMax.fromXContent(p, (String) c));
map.put(SumAggregationBuilder.NAME, (p, c) -> ParsedSum.fromXContent(p, (String) c));
map.put(AvgAggregationBuilder.NAME, (p, c) -> ParsedAvg.fromXContent(p, (String) c));
map.put(ValueCountAggregationBuilder.NAME, (p, c) -> ParsedValueCount.fromXContent(p, (String) c));
map.put(InternalSimpleValue.NAME, (p, c) -> ParsedSimpleValue.fromXContent(p, (String) c));
map.put(DerivativePipelineAggregationBuilder.NAME, (p, c) -> ParsedDerivative.fromXContent(p, (String) c));
map.put(InternalBucketMetricValue.NAME, (p, c) -> ParsedBucketMetricValue.fromXContent(p, (String) c));
map.put(StatsAggregationBuilder.NAME, (p, c) -> ParsedStats.fromXContent(p, (String) c));
map.put(StatsBucketPipelineAggregationBuilder.NAME, (p, c) -> ParsedStatsBucket.fromXContent(p, (String) c));
map.put(ExtendedStatsAggregationBuilder.NAME, (p, c) -> ParsedExtendedStats.fromXContent(p, (String) c));
map.put(ExtendedStatsBucketPipelineAggregationBuilder.NAME,
(p, c) -> ParsedExtendedStatsBucket.fromXContent(p, (String) c));
map.put(GeoBoundsAggregationBuilder.NAME, (p, c) -> ParsedGeoBounds.fromXContent(p, (String) c));
map.put(GeoCentroidAggregationBuilder.NAME, (p, c) -> ParsedGeoCentroid.fromXContent(p, (String) c));
map.put(HistogramAggregationBuilder.NAME, (p, c) -> ParsedHistogram.fromXContent(p, (String) c));
map.put(DateHistogramAggregationBuilder.NAME, (p, c) -> ParsedDateHistogram.fromXContent(p, (String) c));
map.put(AutoDateHistogramAggregationBuilder.NAME, (p, c) -> ParsedAutoDateHistogram.fromXContent(p, (String) c));
map.put(StringTerms.NAME, (p, c) -> ParsedStringTerms.fromXContent(p, (String) c));
map.put(LongTerms.NAME, (p, c) -> ParsedLongTerms.fromXContent(p, (String) c));
map.put(DoubleTerms.NAME, (p, c) -> ParsedDoubleTerms.fromXContent(p, (String) c));
map.put(MissingAggregationBuilder.NAME, (p, c) -> ParsedMissing.fromXContent(p, (String) c));
map.put(NestedAggregationBuilder.NAME, (p, c) -> ParsedNested.fromXContent(p, (String) c));
map.put(ReverseNestedAggregationBuilder.NAME, (p, c) -> ParsedReverseNested.fromXContent(p, (String) c));
map.put(GlobalAggregationBuilder.NAME, (p, c) -> ParsedGlobal.fromXContent(p, (String) c));
map.put(FilterAggregationBuilder.NAME, (p, c) -> ParsedFilter.fromXContent(p, (String) c));
map.put(InternalSampler.PARSER_NAME, (p, c) -> ParsedSampler.fromXContent(p, (String) c));
map.put(GeoGridAggregationBuilder.NAME, (p, c) -> ParsedGeoHashGrid.fromXContent(p, (String) c));
map.put(RangeAggregationBuilder.NAME, (p, c) -> ParsedRange.fromXContent(p, (String) c));
map.put(DateRangeAggregationBuilder.NAME, (p, c) -> ParsedDateRange.fromXContent(p, (String) c));
map.put(GeoDistanceAggregationBuilder.NAME, (p, c) -> ParsedGeoDistance.fromXContent(p, (String) c));
map.put(FiltersAggregationBuilder.NAME, (p, c) -> ParsedFilters.fromXContent(p, (String) c));
map.put(AdjacencyMatrixAggregationBuilder.NAME, (p, c) -> ParsedAdjacencyMatrix.fromXContent(p, (String) c));
map.put(SignificantLongTerms.NAME, (p, c) -> ParsedSignificantLongTerms.fromXContent(p, (String) c));
map.put(SignificantStringTerms.NAME, (p, c) -> ParsedSignificantStringTerms.fromXContent(p, (String) c));
map.put(ScriptedMetricAggregationBuilder.NAME, (p, c) -> ParsedScriptedMetric.fromXContent(p, (String) c));
map.put(IpRangeAggregationBuilder.NAME, (p, c) -> ParsedBinaryRange.fromXContent(p, (String) c));
map.put(TopHitsAggregationBuilder.NAME, (p, c) -> ParsedTopHits.fromXContent(p, (String) c));
map.put(CompositeAggregationBuilder.NAME, (p, c) -> ParsedComposite.fromXContent(p, (String) c));
List<NamedXContentRegistry.Entry> entries = map.entrySet().stream()
.map(entry -> new NamedXContentRegistry.Entry(Aggregation.class, new ParseField(entry.getKey()), entry.getValue()))
.collect(Collectors.toList());
entries.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField(TermSuggestionBuilder.SUGGESTION_NAME),
(parser, context) -> TermSuggestion.fromXContent(parser, (String)context)));
entries.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField(PhraseSuggestionBuilder.SUGGESTION_NAME),
(parser, context) -> PhraseSuggestion.fromXContent(parser, (String)context)));
entries.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField(CompletionSuggestionBuilder.SUGGESTION_NAME),
(parser, context) -> CompletionSuggestion.fromXContent(parser, (String)context)));
return entries;
}
/**
* Loads and returns the {@link NamedXContentRegistry.Entry} parsers provided by plugins.
*/
static List<NamedXContentRegistry.Entry> getProvidedNamedXContents() {
List<NamedXContentRegistry.Entry> entries = new ArrayList<>();
for (NamedXContentProvider service : ServiceLoader.load(NamedXContentProvider.class)) {
entries.addAll(service.getNamedXContentParsers());
}
return entries;
}
}
| HLRC+MINOR: Remove Unused Private Method (#33165)
* This one seems to be unused since 92eb32477 | client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java | HLRC+MINOR: Remove Unused Private Method (#33165) | <ide><path>lient/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java
<ide>
<ide> package org.elasticsearch.client;
<ide>
<del>import org.apache.http.Header;
<ide> import org.apache.http.HttpEntity;
<ide> import org.elasticsearch.ElasticsearchException;
<ide> import org.elasticsearch.ElasticsearchStatusException;
<ide> }
<ide> }
<ide>
<del> private static RequestOptions optionsForHeaders(Header[] headers) {
<del> RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder();
<del> for (Header header : headers) {
<del> Objects.requireNonNull(header, "header cannot be null");
<del> options.addHeader(header.getName(), header.getValue());
<del> }
<del> return options.build();
<del> }
<del>
<ide> static boolean convertExistsResponse(Response response) {
<ide> return response.getStatusLine().getStatusCode() == 200;
<ide> } |
|
Java | mit | 4a03c5870dfdbbaa89925608df2f1534fdd2a6ae | 0 | bignerdranch/expandable-recycler-view,Reline/realm-expandable-recycler-view,bignerdranch/expandable-recycler-view | package com.bignerdranch.expandablerecyclerview;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import com.bignerdranch.expandablerecyclerview.model.ExpandableWrapper;
import com.bignerdranch.expandablerecyclerview.model.ParentListItem;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* RecyclerView.Adapter implementation that
* adds the ability to expand and collapse list items.
*
* Changes should be notified through:
* {@link #notifyParentItemInserted(int)}
* {@link #notifyParentItemRemoved(int)}
* {@link #notifyParentItemChanged(int)}
* {@link #notifyParentItemRangeInserted(int, int)}
* {@link #notifyChildItemInserted(int, int)}
* {@link #notifyChildItemRemoved(int, int)}
* {@link #notifyChildItemChanged(int, int)}
* methods and not the notify methods of RecyclerView.Adapter.
*
* @author Ryan Brooks
* @version 1.0
* @since 5/27/2015
*/
public abstract class ExpandableRecyclerAdapter<P extends ParentListItem<C>, C, PVH extends ParentViewHolder, CVH extends ChildViewHolder>
extends RecyclerView.Adapter<RecyclerView.ViewHolder>
implements ParentViewHolder.ParentListItemExpandCollapseListener {
private static final String EXPANDED_STATE_MAP = "ExpandableRecyclerAdapter.ExpandedStateMap";
/** Default ViewType for parent rows */
public static final int TYPE_PARENT = 0;
/** Default ViewType for children rows */
public static final int TYPE_CHILD = 1;
/** Start of user-defined view types */
public static final int TYPE_FIRST_USER = 2;
/**
* A {@link List} of all currently expanded parents and their children, in order.
* Changes to this list should be made through the add/remove methods
* available in {@link ExpandableRecyclerAdapter}.
*/
protected List<ExpandableWrapper<P, C>> mItemList;
private List<P> mParentItemList;
private ExpandCollapseListener mExpandCollapseListener;
private List<RecyclerView> mAttachedRecyclerViewPool;
/**
* Allows objects to register themselves as expand/collapse listeners to be
* notified of change events.
* <p>
* Implement this in your {@link android.app.Activity} or {@link android.app.Fragment}
* to receive these callbacks.
*/
public interface ExpandCollapseListener {
/**
* Called when a list item is expanded.
*
* @param position The index of the item in the list being expanded
*/
void onListItemExpanded(int position);
/**
* Called when a list item is collapsed.
*
* @param position The index of the item in the list being collapsed
*/
void onListItemCollapsed(int position);
}
/**
* Primary constructor. Sets up {@link #mParentItemList} and {@link #mItemList}.
*
* Changes to {@link #mParentItemList} should be made through add/remove methods in
* {@link ExpandableRecyclerAdapter}
*
* @param parentItemList List of all parents to be displayed in the RecyclerView that this
* adapter is linked to
*/
public ExpandableRecyclerAdapter(@NonNull List<P> parentItemList) {
super();
mParentItemList = parentItemList;
mItemList = generateParentChildItemList(parentItemList);
mAttachedRecyclerViewPool = new ArrayList<>();
}
/**
* Implementation of Adapter.onCreateViewHolder(ViewGroup, int)
* that determines if the list item is a parent or a child and calls through
* to the appropriate implementation of either {@link #onCreateParentViewHolder(ViewGroup, int)}
* or {@link #onCreateChildViewHolder(ViewGroup, int)}.
*
* @param viewGroup The {@link ViewGroup} into which the new {@link android.view.View}
* will be added after it is bound to an adapter position.
* @param viewType The view type of the new {@code android.view.View}.
* @return A new RecyclerView.ViewHolder
* that holds a {@code android.view.View} of the given view type.
*/
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (isParentViewType(viewType)) {
PVH pvh = onCreateParentViewHolder(viewGroup, viewType);
pvh.setParentListItemExpandCollapseListener(this);
pvh.mExpandableAdapter = this;
return pvh;
} else {
CVH cvh = onCreateChildViewHolder(viewGroup, viewType);
cvh.mExpandableAdapter = this;
return cvh;
}
}
/**
* Implementation of Adapter.onBindViewHolder(RecyclerView.ViewHolder, int)
* that determines if the list item is a parent or a child and calls through
* to the appropriate implementation of either
* {@link #onBindParentViewHolder(ParentViewHolder, int, P)} or
* {@link #onBindChildViewHolder(ChildViewHolder, int, int, C)}.
*
* @param holder The RecyclerView.ViewHolder to bind data to
* @param position The index in the list at which to bind
*/
@Override
@SuppressWarnings("unchecked")
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ExpandableWrapper<P, C> listItem = mItemList.get(position);
if (listItem.isParent()) {
PVH parentViewHolder = (PVH) holder;
if (parentViewHolder.shouldItemViewClickToggleExpansion()) {
parentViewHolder.setMainItemClickToExpand();
}
parentViewHolder.setExpanded(listItem.isExpanded());
parentViewHolder.mParentListItem = listItem.getParentListItem();
onBindParentViewHolder(parentViewHolder, getNearestParentPosition(position), listItem.getParentListItem());
} else {
CVH childViewHolder = (CVH) holder;
childViewHolder.mChildListItem = listItem.getChildListItem();
onBindChildViewHolder(childViewHolder, getNearestParentPosition(position), getChildPosition(position), listItem.getChildListItem());
}
}
/**
* Callback called from {@link #onCreateViewHolder(ViewGroup, int)} when
* the list item created is a parent.
*
* @param parentViewGroup The {@link ViewGroup} in the list for which a {@link PVH} is being
* created
* @return A {@code PVH} corresponding to the parent with the {@code ViewGroup} parentViewGroup
*/
public abstract PVH onCreateParentViewHolder(ViewGroup parentViewGroup, int viewType);
/**
* Callback called from {@link #onCreateViewHolder(ViewGroup, int)} when
* the list item created is a child.
*
* @param childViewGroup The {@link ViewGroup} in the list for which a {@link CVH}
* is being created
* @return A {@code CVH} corresponding to the child list item with the
* {@code ViewGroup} childViewGroup
*/
public abstract CVH onCreateChildViewHolder(ViewGroup childViewGroup, int viewType);
/**
* Callback called from onBindViewHolder(RecyclerView.ViewHolder, int)
* when the list item bound to is a parent.
* <p>
* Bind data to the {@link PVH} here.
*
* @param parentViewHolder The {@code PVH} to bind data to
* @param parentPosition The position of the parent to bind
* @param parentListItem The parent which holds the data to be bound to the {@code PVH}
*/
public abstract void onBindParentViewHolder(PVH parentViewHolder, int parentPosition, P parentListItem);
/**
* Callback called from onBindViewHolder(RecyclerView.ViewHolder, int)
* when the list item bound to is a child.
* <p>
* Bind data to the {@link CVH} here.
*
* @param childViewHolder The {@code CVH} to bind data to
* @param parentPosition The position of the parent that contains the child to bind
* @param childPosition The position of the child to bind
* @param childListItem The child which holds that data to be bound to the {@code CVH}
*/
public abstract void onBindChildViewHolder(CVH childViewHolder, int parentPosition, int childPosition, C childListItem);
/**
* Gets the number of parents and children currently expanded.
*
* @return The size of {@link #mItemList}
*/
@Override
public int getItemCount() {
return mItemList.size();
}
/**
* For multiple view type support look at overriding {@link #getParentItemViewType(int)} and
* {@link #getChildItemViewType(int, int)}. Almost all cases should override those instead
* of this method.
*
* @param position The index in the list to get the view type of
* @return Gets the view type of the item at the given position.
*/
@Override
public int getItemViewType(int position) {
ExpandableWrapper<P, C> listItem = mItemList.get(position);
if (listItem.isParent()) {
return getParentItemViewType(getNearestParentPosition(position));
} else {
return getChildItemViewType(getNearestParentPosition(position), getChildPosition(position));
}
}
/**
* Return the view type of the parent item at {@code parentPosition} for the purposes
* of view recycling.
* <p>
* The default implementation of this method returns {@link #TYPE_PARENT}, making the assumption of
* a single view type for the parent items in this adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
* <p>
* If you are overriding this method make sure to override {@link #isParentViewType(int)} as well.
* <p>
* Start your defined viewtypes at {@link #TYPE_FIRST_USER}
*
* @param parentPosition The index of the parent to query
* @return integer value identifying the type of the view needed to represent the item at
* {@code parentPosition}. Type codes need not be contiguous.
*/
public int getParentItemViewType(int parentPosition) {
return TYPE_PARENT;
}
/**
* Return the view type of the child item {@code parentPosition} contained within the parent
* at {@code parentPosition} for the purposes of view recycling.
* <p>
* The default implementation of this method returns {@link #TYPE_CHILD}, making the assumption of
* a single view type for the children in this adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
* <p>
* Start your defined viewtypes at {@link #TYPE_FIRST_USER}
*
* @param parentPosition The index of the parent continaing the child to query
* @param childPosition The index of the child within the parent to query
* @return integer value identifying the type of the view needed to represent the item at
* {@code parentPosition}. Type codes need not be contiguous.
*/
public int getChildItemViewType(int parentPosition, int childPosition) {
return TYPE_CHILD;
}
/**
* Used to determine whether a viewType is that of a parent or not, for ViewHolder creation purposes.
* <p>
* Only override if {@link #getParentItemViewType(int)} is being overriden
*
* @param viewType the viewType identifier in question
* @return whether the given viewType belongs to a parent view
*/
public boolean isParentViewType(int viewType) {
return viewType == TYPE_PARENT;
}
/**
* Gets the list of parents that is backing this adapter.
* Changes can be made to the list and the adapter notified via the
* {@link #notifyParentItemInserted(int)}
* {@link #notifyParentItemRemoved(int)}
* {@link #notifyParentItemChanged(int)}
* {@link #notifyParentItemRangeInserted(int, int)}
* {@link #notifyChildItemInserted(int, int)}
* {@link #notifyChildItemRemoved(int, int)}
* {@link #notifyChildItemChanged(int, int)}
* methods.
*
*
* @return The list of parents that this adapter represents
*/
public List<P> getParentItemList() {
return mParentItemList;
}
/**
* Implementation of {@link com.bignerdranch.expandablerecyclerview.ParentViewHolder.ParentListItemExpandCollapseListener#onParentListItemExpanded(int)}.
* <p>
* Called when a {@link P} is triggered to expand.
*
* @param position The index of the item in the list being expanded
*/
@Override
public void onParentListItemExpanded(int position) {
int parentWrapperIndex = getParentExpandableWrapperIndex(position);
ExpandableWrapper<P, C> listItem = mItemList.get(parentWrapperIndex);
if (listItem.isParent()) {
expandParentListItem(listItem, position, true);
}
}
/**
* Implementation of {@link com.bignerdranch.expandablerecyclerview.ParentViewHolder.ParentListItemExpandCollapseListener#onParentListItemCollapsed(int)}.
* <p>
* Called when a {@link P} is triggered to collapse.
*
* @param position The index of the item in the list being collapsed
*/
@Override
public void onParentListItemCollapsed(int position) {
int parentWrapperIndex = getParentExpandableWrapperIndex(position);
ExpandableWrapper<P, C> listItem = mItemList.get(parentWrapperIndex);
if (listItem.isParent()) {
collapseParentListItem(listItem, position, true);
}
}
/**
* Implementation of Adapter#onAttachedToRecyclerView(RecyclerView).
* <p>
* Called when this {@link ExpandableRecyclerAdapter} is attached to a RecyclerView.
*
* @param recyclerView The {@code RecyclerView} this {@code ExpandableRecyclerAdapter}
* is being attached to
*/
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mAttachedRecyclerViewPool.add(recyclerView);
}
/**
* Implementation of Adapter.onDetachedFromRecyclerView(RecyclerView)
* <p>
* Called when this ExpandableRecyclerAdapter is detached from a RecyclerView.
*
* @param recyclerView The {@code RecyclerView} this {@code ExpandableRecyclerAdapter}
* is being detached from
*/
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
mAttachedRecyclerViewPool.remove(recyclerView);
}
public void setExpandCollapseListener(ExpandCollapseListener expandCollapseListener) {
mExpandCollapseListener = expandCollapseListener;
}
// region Programmatic Expansion/Collapsing
/**
* Expands the parent with the specified index in the list of parents.
*
* @param parentIndex The index of the parent to expand
*/
public void expandParent(int parentIndex) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentIndex);
ExpandableWrapper<P, C> listItem = mItemList.get(parentWrapperIndex);
if (!listItem.isParent()) {
return;
}
expandViews(listItem, parentWrapperIndex);
}
/**
* Expands the parent associated with a specified {@link P} in the list of parents.
*
* @param parentListItem The {@code P} of the parent to expand
*/
public void expandParent(P parentListItem) {
ExpandableWrapper<P, C> parentWrapper = new ExpandableWrapper<>(parentListItem);
int parentWrapperIndex = mItemList.indexOf(parentWrapper);
if (parentWrapperIndex == -1) {
return;
}
expandViews(mItemList.get(parentWrapperIndex), parentWrapperIndex);
}
/**
* Expands all parents in a range of indices in the list of parents.
*
* @param startParentIndex The index at which to to start expanding parents
* @param parentCount The number of parents to expand
*/
public void expandParentRange(int startParentIndex, int parentCount) {
int endParentIndex = startParentIndex + parentCount;
for (int i = startParentIndex; i < endParentIndex; i++) {
expandParent(i);
}
}
/**
* Expands all parents in the list.
*/
public void expandAllParents() {
for (P parentListItem : mParentItemList) {
expandParent(parentListItem);
}
}
/**
* Collapses the parent with the specified index in the list of parents.
*
* @param parentIndex The index of the parent to collapse
*/
public void collapseParent(int parentIndex) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentIndex);
ExpandableWrapper<P, C> listItem = mItemList.get(parentWrapperIndex);
if (!listItem.isParent()) {
return;
}
collapseViews(listItem, parentWrapperIndex);
}
/**
* Collapses the parent associated with a specified {@link P} in the list of parents.
*
* @param parentListItem The {@code P} of the parent to collapse
*/
public void collapseParent(P parentListItem) {
ExpandableWrapper<P, C> parentWrapper = new ExpandableWrapper<>(parentListItem);
int parentWrapperIndex = mItemList.indexOf(parentWrapper);
if (parentWrapperIndex == -1) {
return;
}
collapseViews(mItemList.get(parentWrapperIndex), parentWrapperIndex);
}
/**
* Collapses all parents in a range of indices in the list of parents.
*
* @param startParentIndex The index at which to to start collapsing parents
* @param parentCount The number of parents to collapse
*/
public void collapseParentRange(int startParentIndex, int parentCount) {
int endParentIndex = startParentIndex + parentCount;
for (int i = startParentIndex; i < endParentIndex; i++) {
collapseParent(i);
}
}
/**
* Collapses all parents in the list.
*/
public void collapseAllParents() {
for (P parentListItem : mParentItemList) {
collapseParent(parentListItem);
}
}
/**
* Stores the expanded state map across state loss.
* <p>
* Should be called from {@link Activity#onSaveInstanceState(Bundle)} in
* the {@link Activity} that hosts the RecyclerView that this
* {@link ExpandableRecyclerAdapter} is attached to.
* <p>
* This will make sure to add the expanded state map as an extra to the
* instance state bundle to be used in {@link #onRestoreInstanceState(Bundle)}.
*
* @param savedInstanceState The {@code Bundle} into which to store the
* expanded state map
*/
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable(EXPANDED_STATE_MAP, generateExpandedStateMap());
}
/**
* Fetches the expandable state map from the saved instance state {@link Bundle}
* and restores the expanded states of all of the list items.
* <p>
* Should be called from {@link Activity#onRestoreInstanceState(Bundle)} in
* the {@link Activity} that hosts the RecyclerView that this
* {@link ExpandableRecyclerAdapter} is attached to.
* <p>
* Assumes that the list of parent list items is the same as when the saved
* instance state was stored.
*
* @param savedInstanceState The {@code Bundle} from which the expanded
* state map is loaded
*/
@SuppressWarnings("unchecked")
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState == null
|| !savedInstanceState.containsKey(EXPANDED_STATE_MAP)) {
return;
}
HashMap<Integer, Boolean> expandedStateMap = (HashMap<Integer, Boolean>) savedInstanceState.getSerializable(EXPANDED_STATE_MAP);
if (expandedStateMap == null) {
return;
}
List<ExpandableWrapper<P, C>> itemList = new ArrayList<>();
int parentListItemCount = mParentItemList.size();
for (int i = 0; i < parentListItemCount; i++) {
ExpandableWrapper<P, C> parentWrapper = new ExpandableWrapper<>(mParentItemList.get(i));
itemList.add(parentWrapper);
if (expandedStateMap.containsKey(i)) {
boolean expanded = expandedStateMap.get(i);
if (expanded) {
parentWrapper.setExpanded(true);
List<ExpandableWrapper<P, C>> childItemList = parentWrapper.getChildItemList();
int childListItemCount = childItemList.size();
for (int j = 0; j < childListItemCount; j++) {
ExpandableWrapper<P, C> childWrapper = childItemList.get(j);
itemList.add(childWrapper);
}
}
}
}
mItemList = itemList;
notifyDataSetChanged();
}
/**
* Gets the list item held at the specified adapter position.
*
* @param position The index of the list item to return
* @return The list item at the specified position
*/
protected Object getListItem(int position) {
boolean indexInRange = position >= 0 && position < mItemList.size();
if (indexInRange) {
ExpandableWrapper<P, C> listItem = mItemList.get(position);
if (listItem.isParent()) {
return listItem.getParentListItem();
} else {
return listItem.getChildListItem();
}
} else {
return null;
}
}
/**
* Calls through to the ParentViewHolder to expand views for each
* RecyclerView the specified parent is a child of.
*
* These calls to the ParentViewHolder are made so that animations can be
* triggered at the ViewHolder level.
*
* @param parentIndex The index of the parent to expand
*/
@SuppressWarnings("unchecked")
private void expandViews(ExpandableWrapper<P, C> parentWrapper, int parentIndex) {
PVH viewHolder;
for (RecyclerView recyclerView : mAttachedRecyclerViewPool) {
viewHolder = (PVH) recyclerView.findViewHolderForAdapterPosition(parentIndex);
if (viewHolder != null && !viewHolder.isExpanded()) {
viewHolder.setExpanded(true);
viewHolder.onExpansionToggled(false);
}
}
expandParentListItem(parentWrapper, parentIndex, false);
}
/**
* Calls through to the ParentViewHolder to collapse views for each
* RecyclerView a specified parent is a child of.
*
* These calls to the ParentViewHolder are made so that animations can be
* triggered at the ViewHolder level.
*
* @param parentIndex The index of the parent to collapse
*/
@SuppressWarnings("unchecked")
private void collapseViews(ExpandableWrapper<P, C> parentWrapper, int parentIndex) {
PVH viewHolder;
for (RecyclerView recyclerView : mAttachedRecyclerViewPool) {
viewHolder = (PVH) recyclerView.findViewHolderForAdapterPosition(parentIndex);
if (viewHolder != null && viewHolder.isExpanded()) {
viewHolder.setExpanded(false);
viewHolder.onExpansionToggled(true);
}
}
collapseParentListItem(parentWrapper, parentIndex, false);
}
/**
* Expands a specified parent. Calls through to the
* ExpandCollapseListener and adds children of the specified parent to the
* total list of items.
*
* @param parentWrapper The ExpandableWrapper of the parent to expand
* @param parentIndex The index of the parent to expand
* @param expansionTriggeredByListItemClick true if expansion was triggered
* by a click event, false otherwise.
*/
private void expandParentListItem(ExpandableWrapper<P, C> parentWrapper, int parentIndex, boolean expansionTriggeredByListItemClick) {
if (!parentWrapper.isExpanded()) {
parentWrapper.setExpanded(true);
List<ExpandableWrapper<P, C>> childItemList = parentWrapper.getChildItemList();
if (childItemList != null) {
int childListItemCount = childItemList.size();
for (int i = 0; i < childListItemCount; i++) {
mItemList.add(parentIndex + i + 1, childItemList.get(i));
}
notifyItemRangeInserted(parentIndex + 1, childListItemCount);
}
if (expansionTriggeredByListItemClick && mExpandCollapseListener != null) {
mExpandCollapseListener.onListItemExpanded(getNearestParentPosition(parentIndex));
}
}
}
/**
* Collapses a specified parent item. Calls through to the
* ExpandCollapseListener and adds children of the specified parent to the
* total list of items.
*
* @param parentWrapper The ExpandableWrapper of the parent to collapse
* @param parentIndex The index of the parent to collapse
* @param collapseTriggeredByListItemClick true if expansion was triggered
* by a click event, false otherwise.
*/
private void collapseParentListItem(ExpandableWrapper<P, C> parentWrapper, int parentIndex, boolean collapseTriggeredByListItemClick) {
if (parentWrapper.isExpanded()) {
parentWrapper.setExpanded(false);
List<ExpandableWrapper<P, C>> childItemList = parentWrapper.getChildItemList();
if (childItemList != null) {
int childListItemCount = childItemList.size();
for (int i = childListItemCount - 1; i >= 0; i--) {
mItemList.remove(parentIndex + i + 1);
}
notifyItemRangeRemoved(parentIndex + 1, childListItemCount);
}
if (collapseTriggeredByListItemClick && mExpandCollapseListener != null) {
mExpandCollapseListener.onListItemCollapsed(getNearestParentPosition(parentIndex));
}
}
}
/**
* Given the index relative to the entire RecyclerView, returns the nearest
* ParentPosition without going past the given index.
*
* If it is the index of a parent, will return the corresponding parent position.
* If it is the index of a child within the RV, will return the position of that child's parent.
*/
int getNearestParentPosition(int fullPosition) {
if (fullPosition == 0) {
return 0;
}
int parentCount = -1;
for (int i = 0; i <= fullPosition; i++) {
ExpandableWrapper<P, C> listItem = mItemList.get(i);
if (listItem.isParent()) {
parentCount++;
}
}
return parentCount;
}
/**
* Given the index relative to the entire RecyclerView for a child item,
* returns the child position within the child list of the parent.
*/
int getChildPosition(int fullPosition) {
if (fullPosition == 0) {
return 0;
}
int childCount = 0;
for (int i = 0; i < fullPosition; i++) {
ExpandableWrapper<P, C> listItem = mItemList.get(i);
if (listItem.isParent()) {
childCount = 0;
} else {
childCount++;
}
}
return childCount;
}
// endregion
// region Data Manipulation
/**
* Notify any registered observers that the parent reflected at {@code parentPosition}
* has been newly inserted. The parent previously at {@code parentPosition} is now at
* position {@code parentPosition + 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.
*
* @param parentPosition Position of the newly inserted parent in the data set, relative
* to the list of parents only.
*
* @see #notifyParentItemRangeInserted(int, int)
*/
public void notifyParentItemInserted(int parentPosition) {
P parentListItem = mParentItemList.get(parentPosition);
int wrapperIndex;
if (parentPosition < mParentItemList.size() - 1) {
wrapperIndex = getParentExpandableWrapperIndex(parentPosition);
} else {
wrapperIndex = mItemList.size();
}
int sizeChanged = addParentWrapper(wrapperIndex, parentListItem);
notifyItemRangeInserted(wrapperIndex, sizeChanged);
}
/**
* Notify any registered observers that the currently reflected {@code itemCount}
* parents starting at {@code parentPositionStart} have been newly inserted.
* The parents previously located at {@code parentPositionStart} and beyond
* can now be found starting at position {@code parentPositionStart + itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPositionStart Position of the first parent that was inserted, relative
* to the list of parents only.
* @param itemCount Number of items inserted
*
* @see #notifyParentItemInserted(int)
*/
public void notifyParentItemRangeInserted(int parentPositionStart, int itemCount) {
int initialWrapperIndex;
if (parentPositionStart < mParentItemList.size() - itemCount) {
initialWrapperIndex = getParentExpandableWrapperIndex(parentPositionStart);
} else {
initialWrapperIndex = mItemList.size();
}
int sizeChanged = 0;
int wrapperIndex = initialWrapperIndex;
int changed;
int parentPositionEnd = parentPositionStart + itemCount;
for (int i = parentPositionStart; i < parentPositionEnd; i++) {
P parentListItem = mParentItemList.get(i);
changed = addParentWrapper(wrapperIndex, parentListItem);
wrapperIndex += changed;
sizeChanged += changed;
}
notifyItemRangeInserted(initialWrapperIndex, sizeChanged);
}
private int addParentWrapper(int wrapperIndex, P parentListItem) {
int sizeChanged = 1;
ExpandableWrapper<P, C> parentWrapper = new ExpandableWrapper<>(parentListItem);
mItemList.add(wrapperIndex, parentWrapper);
if (parentWrapper.isParentInitiallyExpanded()) {
parentWrapper.setExpanded(true);
List<ExpandableWrapper<P, C>> childItemList = parentWrapper.getChildItemList();
mItemList.addAll(wrapperIndex + sizeChanged, childItemList);
sizeChanged += childItemList.size();
}
return sizeChanged;
}
/**
* Notify any registered observers that the parents previously located at {@code parentPosition}
* has been removed from the data set. The parents previously located at and after
* {@code parentPosition} may now be found at {@code oldPosition - 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPosition Position of the parent that has now been removed, relative
* to the list of parents only.
*/
public void notifyParentItemRemoved(int parentPosition) {
int wrapperIndex = getParentExpandableWrapperIndex(parentPosition);
int sizeChanged = removeParentWrapper(wrapperIndex);
notifyItemRangeRemoved(wrapperIndex, sizeChanged);
}
/**
* Notify any registered observers that the {@code itemCount} parents previously
* located at {@code parentPositionStart} have been removed from the data set. The parents
* previously located at and after {@code parentPositionStart + itemCount} may now be
* found at {@code oldPosition - itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPositionStart The previous position of the first parent that was
* removed, relative to list of parents only.
* @param itemCount Number of parents removed from the data set
*/
public void notifyParentItemRangeRemoved(int parentPositionStart, int itemCount) {
int sizeChanged = 0;
int wrapperIndex = getParentExpandableWrapperIndex(parentPositionStart);
for (int i = 0; i < itemCount; i++) {
sizeChanged += removeParentWrapper(wrapperIndex);
}
notifyItemRangeRemoved(wrapperIndex, sizeChanged);
}
private int removeParentWrapper(int parentWrapperIndex) {
int sizeChanged = 1;
ExpandableWrapper<P, C> parentWrapper = mItemList.remove(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
int childListSize = parentWrapper.getChildItemList().size();
for (int i = 0; i < childListSize; i++) {
mItemList.remove(parentWrapperIndex);
sizeChanged++;
}
}
return sizeChanged;
}
/**
* Notify any registered observers that the parent at {@code parentPosition} has changed.
* This will also trigger an item changed for children of the parent list specified.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* reflection of the data at {@code parentPosition} is out of date and should be updated.
* The parent at {@code parentPosition} retains the same identity. This means
* the number of children must stay the same.
*
* @param parentPosition Position of the item that has changed
*/
public void notifyParentItemChanged(int parentPosition) {
P parentListItem = mParentItemList.get(parentPosition);
int wrapperIndex = getParentExpandableWrapperIndex(parentPosition);
int sizeChanged = changeParentWrapper(wrapperIndex, parentListItem);
notifyItemRangeChanged(wrapperIndex, sizeChanged);
}
/**
* Notify any registered observers that the {@code itemCount} parents starting
* at {@code parentPositionStart} have changed. This will also trigger an item changed
* for children of the parent list specified.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* reflection of the data in the given position range is out of date and should be updated.
* The parents in the given range retain the same identity. This means that the number of
* children must stay the same.
*
* @param parentPositionStart Position of the item that has changed
* @param itemCount Number of parents changed in the data set
*/
public void notifyParentItemRangeChanged(int parentPositionStart, int itemCount) {
int initialWrapperIndex = getParentExpandableWrapperIndex(parentPositionStart);
int wrapperIndex = initialWrapperIndex;
int sizeChanged = 0;
int changed;
P parentListItem;
for (int j = 0; j < itemCount; j++) {
parentListItem = mParentItemList.get(parentPositionStart);
changed = changeParentWrapper(wrapperIndex, parentListItem);
sizeChanged += changed;
wrapperIndex += changed;
parentPositionStart++;
}
notifyItemRangeChanged(initialWrapperIndex, sizeChanged);
}
private int changeParentWrapper(int wrapperIndex, P parentListItem) {
ExpandableWrapper<P, C> parentWrapper = mItemList.get(wrapperIndex);
parentWrapper.setParentListItem(parentListItem);
int sizeChanged = 1;
if (parentWrapper.isExpanded()) {
List<ExpandableWrapper<P, C>> childItems = parentWrapper.getChildItemList();
int childListSize = childItems.size();
for (int i = 0; i < childListSize; i++) {
mItemList.set(wrapperIndex + i + 1, childItems.get(i));
sizeChanged++;
}
}
return sizeChanged;
}
/**
* Notify any registered observers that the parent and its children reflected at
* {@code fromParentPosition} has been moved to {@code toParentPosition}.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param fromParentPosition Previous position of the parent, relative to the list of
* parents only.
* @param toParentPosition New position of the parent, relative to the list of parents only.
*/
public void notifyParentItemMoved(int fromParentPosition, int toParentPosition) {
int fromWrapperIndex = getParentExpandableWrapperIndex(fromParentPosition);
ExpandableWrapper<P, C> fromParentWrapper = mItemList.get(fromWrapperIndex);
// If the parent is collapsed we can take advantage of notifyItemMoved otherwise
// we are forced to do a "manual" move by removing and then adding the parent + children
// (no notifyItemRangeMovedAvailable)
boolean isCollapsed = !fromParentWrapper.isExpanded();
boolean isExpandedNoChildren = !isCollapsed && (fromParentWrapper.getChildItemList().size() == 0);
if (isCollapsed || isExpandedNoChildren) {
int toWrapperIndex = getParentExpandableWrapperIndex(toParentPosition);
ExpandableWrapper<P, C> toParentWrapper = mItemList.get(toWrapperIndex);
mItemList.remove(fromWrapperIndex);
int childOffset = 0;
if (toParentWrapper.isExpanded()) {
childOffset = toParentWrapper.getChildItemList().size();
}
mItemList.add(toWrapperIndex + childOffset, fromParentWrapper);
notifyItemMoved(fromWrapperIndex, toWrapperIndex + childOffset);
} else {
// Remove the parent and children
int sizeChanged = 0;
int childListSize = fromParentWrapper.getChildItemList().size();
for (int i = 0; i < childListSize + 1; i++) {
mItemList.remove(fromWrapperIndex);
sizeChanged++;
}
notifyItemRangeRemoved(fromWrapperIndex, sizeChanged);
// Add the parent and children at new position
int toWrapperIndex = getParentExpandableWrapperIndex(toParentPosition);
int childOffset = 0;
if (toWrapperIndex != -1) {
ExpandableWrapper<P, C> toParentWrapper = mItemList.get(toWrapperIndex);
if (toParentWrapper.isExpanded()) {
childOffset = toParentWrapper.getChildItemList().size();
}
} else {
toWrapperIndex = mItemList.size();
}
mItemList.add(toWrapperIndex + childOffset, fromParentWrapper);
List<ExpandableWrapper<P, C>> childItemList = fromParentWrapper.getChildItemList();
sizeChanged = childItemList.size() + 1;
mItemList.addAll(toWrapperIndex + childOffset + 1, childItemList);
notifyItemRangeInserted(toWrapperIndex + childOffset, sizeChanged);
}
}
/**
* Notify any registered observers that the parent reflected at {@code parentPosition}
* has a child list item that has been newly inserted at {@code childPosition}.
* The child list item previously at {@code childPosition} is now at
* position {@code childPosition + 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.
*
* @param parentPosition Position of the parent which has been added a child, relative
* to the list of parents only.
* @param childPosition Position of the child that has been inserted, relative to children
* of the parent specified by {@code parentPosition} only.
*
*/
public void notifyChildItemInserted(int parentPosition, int childPosition) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
ExpandableWrapper<P, C> child = parentWrapper.getChildItemList().get(childPosition);
mItemList.add(parentWrapperIndex + childPosition + 1, child);
notifyItemInserted(parentWrapperIndex + childPosition + 1);
}
}
/**
* Notify any registered observers that the parent reflected at {@code parentPosition}
* has {@code itemCount} child list items that have been newly inserted at {@code childPositionStart}.
* The child list item previously at {@code childPositionStart} and beyond are now at
* position {@code childPositionStart + itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.
*
* @param parentPosition Position of the parent which has been added a child, relative
* to the list of parents only.
* @param childPositionStart Position of the first child that has been inserted,
* relative to children of the parent specified by
* {@code parentPosition} only.
* @param itemCount number of children inserted
*
*/
public void notifyChildItemRangeInserted(int parentPosition, int childPositionStart, int itemCount) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
List<ExpandableWrapper<P, C>> childList = parentWrapper.getChildItemList();
for (int i = 0; i < itemCount; i++) {
ExpandableWrapper<P, C> child = childList.get(childPositionStart + i);
mItemList.add(parentWrapperIndex + childPositionStart + i + 1, child);
}
notifyItemRangeInserted(parentWrapperIndex + childPositionStart + 1, itemCount);
}
}
/**
* Notify any registered observers that the parent located at {@code parentPosition}
* has a child that has been removed from the data set, previously located at {@code childPosition}.
* The child list item previously located at and after {@code childPosition} may
* now be found at {@code childPosition - 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPosition Position of the parent which has a child removed from, relative
* to the list of parents only.
* @param childPosition Position of the child that has been removed, relative to children
* of the parent specified by {@code parentPosition} only.
*/
public void notifyChildItemRemoved(int parentPosition, int childPosition) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
mItemList.remove(parentWrapperIndex + childPosition + 1);
notifyItemRemoved(parentWrapperIndex + childPosition + 1);
}
}
/**
* Notify any registered observers that the parent located at {@code parentPosition}
* has {@code itemCount} children that have been removed from the data set, previously
* located at {@code childPositionStart} onwards. The child previously located at and
* after {@code childPositionStart} may now be found at {@code childPositionStart - itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPosition Position of the parent which has a child removed from, relative
* to the list of parents only.
* @param childPositionStart Position of the first child that has been removed, relative
* to children of the parent specified by {@code parentPosition} only.
* @param itemCount number of children removed
*/
public void notifyChildItemRangeRemoved(int parentPosition, int childPositionStart, int itemCount) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
for (int i = 0; i < itemCount; i++) {
mItemList.remove(parentWrapperIndex + childPositionStart + 1);
}
notifyItemRangeRemoved(parentWrapperIndex + childPositionStart + 1, itemCount);
}
}
/**
* Notify any registered observers that the parent at {@code parentPosition} has
* a child located at {@code childPosition} that has changed.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* reflection of the data at {@code childPosition} is out of date and should be updated.
* The parent at {@code childPosition} retains the same identity.
*
* @param parentPosition Position of the parent which has a child that has changed
* @param childPosition Position of the child that has changed
*/
public void notifyChildItemChanged(int parentPosition, int childPosition) {
P parentListItem = mParentItemList.get(parentPosition);
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
parentWrapper.setParentListItem(parentListItem);
if (parentWrapper.isExpanded()) {
int listChildPosition = parentWrapperIndex + childPosition + 1;
ExpandableWrapper<P, C> child = parentWrapper.getChildItemList().get(childPosition);
mItemList.set(listChildPosition, child);
notifyItemChanged(listChildPosition);
}
}
/**
* Notify any registered observers that the parent at {@code parentPosition} has
* {@code itemCount} children starting at {@code childPositionStart} that have changed.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* The parent at {@code childPositionStart} retains the same identity.
* reflection of the set of {@code itemCount} children starting at {@code childPositionStart}
* are out of date and should be updated.
*
* @param parentPosition Position of the parent who has a child that has changed
* @param childPositionStart Position of the first child that has changed
* @param itemCount number of children changed
*/
public void notifyChildItemRangeChanged(int parentPosition, int childPositionStart, int itemCount) {
P parentListItem = mParentItemList.get(parentPosition);
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
parentWrapper.setParentListItem(parentListItem);
if (parentWrapper.isExpanded()) {
int listChildPosition = parentWrapperIndex + childPositionStart + 1;
for (int i = 0; i < itemCount; i++) {
ExpandableWrapper<P, C> child
= parentWrapper.getChildItemList().get(childPositionStart + i);
mItemList.set(listChildPosition + i, child);
}
notifyItemRangeChanged(listChildPosition, itemCount);
}
}
/**
* Notify any registered observers that the child list item contained within the parent
* at {@code parentPosition} has moved from {@code fromChildPosition} to {@code toChildPosition}.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param parentPosition Position of the parent which has a child that has moved
* @param fromChildPosition Previous position of the child
* @param toChildPosition New position of the child
*/
public void notifyChildItemMoved(int parentPosition, int fromChildPosition, int toChildPosition) {
P parentListItem = mParentItemList.get(parentPosition);
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
parentWrapper.setParentListItem(parentListItem);
if (parentWrapper.isExpanded()) {
ExpandableWrapper<P, C> fromChild = mItemList.remove(parentWrapperIndex + 1 + fromChildPosition);
mItemList.add(parentWrapperIndex + 1 + toChildPosition, fromChild);
notifyItemMoved(parentWrapperIndex + 1 + fromChildPosition, parentWrapperIndex + 1 + toChildPosition);
}
}
// endregion
/**
* Generates a full list of all parents and their children, in order.
*
* @param parentItemList A list of the parents from
* the {@link ExpandableRecyclerAdapter}
* @return A list of all parents and their children, expanded
*/
private List<ExpandableWrapper<P, C>> generateParentChildItemList(List<P> parentItemList) {
List<ExpandableWrapper<P, C>> itemList = new ArrayList<>();
int parentListItemCount = parentItemList.size();
for (int i = 0; i < parentListItemCount; i++) {
ExpandableWrapper<P, C> parentWrapper = new ExpandableWrapper<>(parentItemList.get(i));
itemList.add(parentWrapper);
if (parentWrapper.isParentInitiallyExpanded()) {
parentWrapper.setExpanded(true);
List<ExpandableWrapper<P, C>> childList = parentWrapper.getChildItemList();
int childListItemCount = childList.size();
for (int j = 0; j < childListItemCount; j++) {
ExpandableWrapper<P, C> childWrapper = childList.get(j);
itemList.add(childWrapper);
}
}
}
return itemList;
}
/**
* Generates a HashMap used to store expanded state for items in the list
* on configuration change or whenever onResume is called.
*
* @return A HashMap containing the expanded state of all parents
*/
private HashMap<Integer, Boolean> generateExpandedStateMap() {
HashMap<Integer, Boolean> parentListItemHashMap = new HashMap<>();
int childCount = 0;
int listItemCount = mItemList.size();
for (int i = 0; i < listItemCount; i++) {
if (mItemList.get(i) != null) {
ExpandableWrapper<P, C> listItem = mItemList.get(i);
if (listItem.isParent()) {
parentListItemHashMap.put(i - childCount, listItem.isExpanded());
} else {
childCount++;
}
}
}
return parentListItemHashMap;
}
/**
* Gets the index of a ExpandableWrapper within the helper item list based on
* the index of the ExpandableWrapper.
*
* @param parentIndex The index of the parent in the list of parents
* @return The index of the parent in the list of all views in the adapter
*/
private int getParentExpandableWrapperIndex(int parentIndex) {
int parentCount = 0;
int listItemCount = mItemList.size();
for (int i = 0; i < listItemCount; i++) {
if (mItemList.get(i).isParent()) {
parentCount++;
if (parentCount > parentIndex) {
return i;
}
}
}
return -1;
}
}
| expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java | package com.bignerdranch.expandablerecyclerview;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import com.bignerdranch.expandablerecyclerview.model.ExpandableWrapper;
import com.bignerdranch.expandablerecyclerview.model.ParentListItem;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* RecyclerView.Adapter implementation that
* adds the ability to expand and collapse list items.
*
* Changes should be notified through:
* {@link #notifyParentItemInserted(int)}
* {@link #notifyParentItemRemoved(int)}
* {@link #notifyParentItemChanged(int)}
* {@link #notifyParentItemRangeInserted(int, int)}
* {@link #notifyChildItemInserted(int, int)}
* {@link #notifyChildItemRemoved(int, int)}
* {@link #notifyChildItemChanged(int, int)}
* methods and not the notify methods of RecyclerView.Adapter.
*
* @author Ryan Brooks
* @version 1.0
* @since 5/27/2015
*/
public abstract class ExpandableRecyclerAdapter<P extends ParentListItem<C>, C, PVH extends ParentViewHolder, CVH extends ChildViewHolder>
extends RecyclerView.Adapter<RecyclerView.ViewHolder>
implements ParentViewHolder.ParentListItemExpandCollapseListener {
private static final String EXPANDED_STATE_MAP = "ExpandableRecyclerAdapter.ExpandedStateMap";
/** Default ViewType for parent rows */
public static final int TYPE_PARENT = 0;
/** Default ViewType for children rows */
public static final int TYPE_CHILD = 1;
/** Start of user-defined view types */
public static final int TYPE_FIRST_USER = 2;
/**
* A {@link List} of all currently expanded parents and their children, in order.
* Changes to this list should be made through the add/remove methods
* available in {@link ExpandableRecyclerAdapter}.
*/
protected List<ExpandableWrapper<P, C>> mItemList;
private List<P> mParentItemList;
private ExpandCollapseListener mExpandCollapseListener;
private List<RecyclerView> mAttachedRecyclerViewPool;
/**
* Allows objects to register themselves as expand/collapse listeners to be
* notified of change events.
* <p>
* Implement this in your {@link android.app.Activity} or {@link android.app.Fragment}
* to receive these callbacks.
*/
public interface ExpandCollapseListener {
/**
* Called when a list item is expanded.
*
* @param position The index of the item in the list being expanded
*/
void onListItemExpanded(int position);
/**
* Called when a list item is collapsed.
*
* @param position The index of the item in the list being collapsed
*/
void onListItemCollapsed(int position);
}
/**
* Primary constructor. Sets up {@link #mParentItemList} and {@link #mItemList}.
*
* Changes to {@link #mParentItemList} should be made through add/remove methods in
* {@link ExpandableRecyclerAdapter}
*
* @param parentItemList List of all parents to be displayed in the RecyclerView that this
* adapter is linked to
*/
public ExpandableRecyclerAdapter(@NonNull List<P> parentItemList) {
super();
mParentItemList = parentItemList;
mItemList = generateParentChildItemList(parentItemList);
mAttachedRecyclerViewPool = new ArrayList<>();
}
/**
* Implementation of Adapter.onCreateViewHolder(ViewGroup, int)
* that determines if the list item is a parent or a child and calls through
* to the appropriate implementation of either {@link #onCreateParentViewHolder(ViewGroup, int)}
* or {@link #onCreateChildViewHolder(ViewGroup, int)}.
*
* @param viewGroup The {@link ViewGroup} into which the new {@link android.view.View}
* will be added after it is bound to an adapter position.
* @param viewType The view type of the new {@code android.view.View}.
* @return A new RecyclerView.ViewHolder
* that holds a {@code android.view.View} of the given view type.
*/
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (isParentViewType(viewType)) {
PVH pvh = onCreateParentViewHolder(viewGroup, viewType);
pvh.setParentListItemExpandCollapseListener(this);
pvh.mExpandableAdapter = this;
return pvh;
} else {
CVH cvh = onCreateChildViewHolder(viewGroup, viewType);
cvh.mExpandableAdapter = this;
return cvh;
}
}
/**
* Implementation of Adapter.onBindViewHolder(RecyclerView.ViewHolder, int)
* that determines if the list item is a parent or a child and calls through
* to the appropriate implementation of either
* {@link #onBindParentViewHolder(ParentViewHolder, int, P)} or
* {@link #onBindChildViewHolder(ChildViewHolder, int, int, C)}.
*
* @param holder The RecyclerView.ViewHolder to bind data to
* @param position The index in the list at which to bind
*/
@Override
@SuppressWarnings("unchecked")
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ExpandableWrapper<P, C> listItem = mItemList.get(position);
if (listItem.isParent()) {
PVH parentViewHolder = (PVH) holder;
if (parentViewHolder.shouldItemViewClickToggleExpansion()) {
parentViewHolder.setMainItemClickToExpand();
}
parentViewHolder.setExpanded(listItem.isExpanded());
parentViewHolder.mParentListItem = listItem.getParentListItem();
onBindParentViewHolder(parentViewHolder, getNearestParentPosition(position), listItem.getParentListItem());
} else {
CVH childViewHolder = (CVH) holder;
childViewHolder.mChildListItem = listItem.getChildListItem();
onBindChildViewHolder(childViewHolder, getNearestParentPosition(position), getChildPosition(position), listItem.getChildListItem());
}
}
/**
* Callback called from {@link #onCreateViewHolder(ViewGroup, int)} when
* the list item created is a parent.
*
* @param parentViewGroup The {@link ViewGroup} in the list for which a {@link PVH} is being
* created
* @return A {@code PVH} corresponding to the parent with the {@code ViewGroup} parentViewGroup
*/
public abstract PVH onCreateParentViewHolder(ViewGroup parentViewGroup, int viewType);
/**
* Callback called from {@link #onCreateViewHolder(ViewGroup, int)} when
* the list item created is a child.
*
* @param childViewGroup The {@link ViewGroup} in the list for which a {@link CVH}
* is being created
* @return A {@code CVH} corresponding to the child list item with the
* {@code ViewGroup} childViewGroup
*/
public abstract CVH onCreateChildViewHolder(ViewGroup childViewGroup, int viewType);
/**
* Callback called from onBindViewHolder(RecyclerView.ViewHolder, int)
* when the list item bound to is a parent.
* <p>
* Bind data to the {@link PVH} here.
*
* @param parentViewHolder The {@code PVH} to bind data to
* @param parentPosition The position of the parent to bind
* @param parentListItem The parent which holds the data to be bound to the {@code PVH}
*/
public abstract void onBindParentViewHolder(PVH parentViewHolder, int parentPosition, P parentListItem);
/**
* Callback called from onBindViewHolder(RecyclerView.ViewHolder, int)
* when the list item bound to is a child.
* <p>
* Bind data to the {@link CVH} here.
*
* @param childViewHolder The {@code CVH} to bind data to
* @param parentPosition The position of the parent that contains the child to bind
* @param childPosition The position of the child to bind
* @param childListItem The child which holds that data to be bound to the {@code CVH}
*/
public abstract void onBindChildViewHolder(CVH childViewHolder, int parentPosition, int childPosition, C childListItem);
/**
* Gets the number of parents and children currently expanded.
*
* @return The size of {@link #mItemList}
*/
@Override
public int getItemCount() {
return mItemList.size();
}
/**
* For multiple view type support look at overriding {@link #getParentItemViewType(int)} and
* {@link #getChildItemViewType(int, int)}. Almost all cases should override those instead
* of this method.
*
* @param position The index in the list to get the view type of
* @return Gets the view type of the item at the given position.
*/
@Override
public int getItemViewType(int position) {
ExpandableWrapper<P, C> listItem = mItemList.get(position);
if (listItem.isParent()) {
return getParentItemViewType(getNearestParentPosition(position));
} else {
return getChildItemViewType(getNearestParentPosition(position), getChildPosition(position));
}
}
/**
* Return the view type of the parent item at {@code parentPosition} for the purposes
* of view recycling.
* <p>
* The default implementation of this method returns {@link #TYPE_PARENT}, making the assumption of
* a single view type for the parent items in this adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
* <p>
* If you are overriding this method make sure to override {@link #isParentViewType(int)} as well.
* <p>
* Start your defined viewtypes at {@link #TYPE_FIRST_USER}
*
* @param parentPosition The index of the parent to query
* @return integer value identifying the type of the view needed to represent the item at
* {@code parentPosition}. Type codes need not be contiguous.
*/
public int getParentItemViewType(int parentPosition) {
return TYPE_PARENT;
}
/**
* Return the view type of the child item {@code parentPosition} contained within the parent
* at {@code parentPosition} for the purposes of view recycling.
* <p>
* The default implementation of this method returns {@link #TYPE_CHILD}, making the assumption of
* a single view type for the children in this adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
* <p>
* Start your defined viewtypes at {@link #TYPE_FIRST_USER}
*
* @param parentPosition The index of the parent continaing the child to query
* @param childPosition The index of the child within the parent to query
* @return integer value identifying the type of the view needed to represent the item at
* {@code parentPosition}. Type codes need not be contiguous.
*/
public int getChildItemViewType(int parentPosition, int childPosition) {
return TYPE_CHILD;
}
/**
* Used to determine whether a viewType is that of a parent or not, for ViewHolder creation purposes.
* <p>
* Only override if {@link #getParentItemViewType(int)} is being overriden
*
* @param viewType the viewType identifier in question
* @return whether the given viewType belongs to a parent view
*/
public boolean isParentViewType(int viewType) {
return viewType == TYPE_PARENT;
}
/**
* Gets the list of parents that is backing this adapter.
* Changes can be made to the list and the adapter notified via the
* {@link #notifyParentItemInserted(int)}
* {@link #notifyParentItemRemoved(int)}
* {@link #notifyParentItemChanged(int)}
* {@link #notifyParentItemRangeInserted(int, int)}
* {@link #notifyChildItemInserted(int, int)}
* {@link #notifyChildItemRemoved(int, int)}
* {@link #notifyChildItemChanged(int, int)}
* methods.
*
*
* @return The list of parents that this adapter represents
*/
public List<P> getParentItemList() {
return mParentItemList;
}
/**
* Implementation of {@link com.bignerdranch.expandablerecyclerview.ParentViewHolder.ParentListItemExpandCollapseListener#onParentListItemExpanded(int)}.
* <p>
* Called when a {@link P} is triggered to expand.
*
* @param position The index of the item in the list being expanded
*/
@Override
public void onParentListItemExpanded(int position) {
int parentWrapperIndex = getParentExpandableWrapperIndex(position);
ExpandableWrapper<P, C> listItem = mItemList.get(parentWrapperIndex);
if (listItem.isParent()) {
expandParentListItem(listItem, position, true);
}
}
/**
* Implementation of {@link com.bignerdranch.expandablerecyclerview.ParentViewHolder.ParentListItemExpandCollapseListener#onParentListItemCollapsed(int)}.
* <p>
* Called when a {@link P} is triggered to collapse.
*
* @param position The index of the item in the list being collapsed
*/
@Override
public void onParentListItemCollapsed(int position) {
int parentWrapperIndex = getParentExpandableWrapperIndex(position);
ExpandableWrapper<P, C> listItem = mItemList.get(parentWrapperIndex);
if (listItem.isParent()) {
collapseParentListItem(listItem, position, true);
}
}
/**
* Implementation of Adapter#onAttachedToRecyclerView(RecyclerView).
* <p>
* Called when this {@link ExpandableRecyclerAdapter} is attached to a RecyclerView.
*
* @param recyclerView The {@code RecyclerView} this {@code ExpandableRecyclerAdapter}
* is being attached to
*/
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mAttachedRecyclerViewPool.add(recyclerView);
}
/**
* Implementation of Adapter.onDetachedFromRecyclerView(RecyclerView)
* <p>
* Called when this ExpandableRecyclerAdapter is detached from a RecyclerView.
*
* @param recyclerView The {@code RecyclerView} this {@code ExpandableRecyclerAdapter}
* is being detached from
*/
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
mAttachedRecyclerViewPool.remove(recyclerView);
}
public void setExpandCollapseListener(ExpandCollapseListener expandCollapseListener) {
mExpandCollapseListener = expandCollapseListener;
}
// region Programmatic Expansion/Collapsing
/**
* Expands the parent with the specified index in the list of parents.
*
* @param parentIndex The index of the parent to expand
*/
public void expandParent(int parentIndex) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentIndex);
ExpandableWrapper<P, C> listItem = mItemList.get(parentWrapperIndex);
if (!listItem.isParent()) {
return;
}
expandViews(listItem, parentWrapperIndex);
}
/**
* Expands the parent associated with a specified {@link P} in the list of parents.
*
* @param parentListItem The {@code P} of the parent to expand
*/
public void expandParent(P parentListItem) {
ExpandableWrapper<P, C> parentWrapper = new ExpandableWrapper<>(parentListItem);
int parentWrapperIndex = mItemList.indexOf(parentWrapper);
if (parentWrapperIndex == -1) {
return;
}
expandViews(parentWrapper, parentWrapperIndex);
}
/**
* Expands all parents in a range of indices in the list of parents.
*
* @param startParentIndex The index at which to to start expanding parents
* @param parentCount The number of parents to expand
*/
public void expandParentRange(int startParentIndex, int parentCount) {
int endParentIndex = startParentIndex + parentCount;
for (int i = startParentIndex; i < endParentIndex; i++) {
expandParent(i);
}
}
/**
* Expands all parents in the list.
*/
public void expandAllParents() {
for (P parentListItem : mParentItemList) {
expandParent(parentListItem);
}
}
/**
* Collapses the parent with the specified index in the list of parents.
*
* @param parentIndex The index of the parent to collapse
*/
public void collapseParent(int parentIndex) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentIndex);
ExpandableWrapper<P, C> listItem = mItemList.get(parentWrapperIndex);
if (!listItem.isParent()) {
return;
}
collapseViews(listItem, parentWrapperIndex);
}
/**
* Collapses the parent associated with a specified {@link P} in the list of parents.
*
* @param parentListItem The {@code P} of the parent to collapse
*/
public void collapseParent(P parentListItem) {
ExpandableWrapper<P, C> parentWrapper = new ExpandableWrapper<>(parentListItem);
int parentWrapperIndex = mItemList.indexOf(parentWrapper);
if (parentWrapperIndex == -1) {
return;
}
collapseViews(parentWrapper, parentWrapperIndex);
}
/**
* Collapses all parents in a range of indices in the list of parents.
*
* @param startParentIndex The index at which to to start collapsing parents
* @param parentCount The number of parents to collapse
*/
public void collapseParentRange(int startParentIndex, int parentCount) {
int endParentIndex = startParentIndex + parentCount;
for (int i = startParentIndex; i < endParentIndex; i++) {
collapseParent(i);
}
}
/**
* Collapses all parents in the list.
*/
public void collapseAllParents() {
for (P parentListItem : mParentItemList) {
collapseParent(parentListItem);
}
}
/**
* Stores the expanded state map across state loss.
* <p>
* Should be called from {@link Activity#onSaveInstanceState(Bundle)} in
* the {@link Activity} that hosts the RecyclerView that this
* {@link ExpandableRecyclerAdapter} is attached to.
* <p>
* This will make sure to add the expanded state map as an extra to the
* instance state bundle to be used in {@link #onRestoreInstanceState(Bundle)}.
*
* @param savedInstanceState The {@code Bundle} into which to store the
* expanded state map
*/
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable(EXPANDED_STATE_MAP, generateExpandedStateMap());
}
/**
* Fetches the expandable state map from the saved instance state {@link Bundle}
* and restores the expanded states of all of the list items.
* <p>
* Should be called from {@link Activity#onRestoreInstanceState(Bundle)} in
* the {@link Activity} that hosts the RecyclerView that this
* {@link ExpandableRecyclerAdapter} is attached to.
* <p>
* Assumes that the list of parent list items is the same as when the saved
* instance state was stored.
*
* @param savedInstanceState The {@code Bundle} from which the expanded
* state map is loaded
*/
@SuppressWarnings("unchecked")
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState == null
|| !savedInstanceState.containsKey(EXPANDED_STATE_MAP)) {
return;
}
HashMap<Integer, Boolean> expandedStateMap = (HashMap<Integer, Boolean>) savedInstanceState.getSerializable(EXPANDED_STATE_MAP);
if (expandedStateMap == null) {
return;
}
List<ExpandableWrapper<P, C>> itemList = new ArrayList<>();
int parentListItemCount = mParentItemList.size();
for (int i = 0; i < parentListItemCount; i++) {
ExpandableWrapper<P, C> parentWrapper = new ExpandableWrapper<>(mParentItemList.get(i));
itemList.add(parentWrapper);
if (expandedStateMap.containsKey(i)) {
boolean expanded = expandedStateMap.get(i);
if (expanded) {
parentWrapper.setExpanded(true);
List<ExpandableWrapper<P, C>> childItemList = parentWrapper.getChildItemList();
int childListItemCount = childItemList.size();
for (int j = 0; j < childListItemCount; j++) {
ExpandableWrapper<P, C> childWrapper = childItemList.get(j);
itemList.add(childWrapper);
}
}
}
}
mItemList = itemList;
notifyDataSetChanged();
}
/**
* Gets the list item held at the specified adapter position.
*
* @param position The index of the list item to return
* @return The list item at the specified position
*/
protected Object getListItem(int position) {
boolean indexInRange = position >= 0 && position < mItemList.size();
if (indexInRange) {
ExpandableWrapper<P, C> listItem = mItemList.get(position);
if (listItem.isParent()) {
return listItem.getParentListItem();
} else {
return listItem.getChildItemList();
}
} else {
return null;
}
}
/**
* Calls through to the ParentViewHolder to expand views for each
* RecyclerView the specified parent is a child of.
*
* These calls to the ParentViewHolder are made so that animations can be
* triggered at the ViewHolder level.
*
* @param parentIndex The index of the parent to expand
*/
@SuppressWarnings("unchecked")
private void expandViews(ExpandableWrapper<P, C> parentWrapper, int parentIndex) {
PVH viewHolder;
for (RecyclerView recyclerView : mAttachedRecyclerViewPool) {
viewHolder = (PVH) recyclerView.findViewHolderForAdapterPosition(parentIndex);
if (viewHolder != null && !viewHolder.isExpanded()) {
viewHolder.setExpanded(true);
viewHolder.onExpansionToggled(false);
}
}
expandParentListItem(parentWrapper, parentIndex, false);
}
/**
* Calls through to the ParentViewHolder to collapse views for each
* RecyclerView a specified parent is a child of.
*
* These calls to the ParentViewHolder are made so that animations can be
* triggered at the ViewHolder level.
*
* @param parentIndex The index of the parent to collapse
*/
@SuppressWarnings("unchecked")
private void collapseViews(ExpandableWrapper<P, C> parentWrapper, int parentIndex) {
PVH viewHolder;
for (RecyclerView recyclerView : mAttachedRecyclerViewPool) {
viewHolder = (PVH) recyclerView.findViewHolderForAdapterPosition(parentIndex);
if (viewHolder != null && viewHolder.isExpanded()) {
viewHolder.setExpanded(false);
viewHolder.onExpansionToggled(true);
}
}
collapseParentListItem(parentWrapper, parentIndex, false);
}
/**
* Expands a specified parent. Calls through to the
* ExpandCollapseListener and adds children of the specified parent to the
* total list of items.
*
* @param parentWrapper The ExpandableWrapper of the parent to expand
* @param parentIndex The index of the parent to expand
* @param expansionTriggeredByListItemClick true if expansion was triggered
* by a click event, false otherwise.
*/
private void expandParentListItem(ExpandableWrapper<P, C> parentWrapper, int parentIndex, boolean expansionTriggeredByListItemClick) {
if (!parentWrapper.isExpanded()) {
parentWrapper.setExpanded(true);
List<ExpandableWrapper<P, C>> childItemList = parentWrapper.getChildItemList();
if (childItemList != null) {
int childListItemCount = childItemList.size();
for (int i = 0; i < childListItemCount; i++) {
mItemList.add(parentIndex + i + 1, childItemList.get(i));
}
notifyItemRangeInserted(parentIndex + 1, childListItemCount);
}
if (expansionTriggeredByListItemClick && mExpandCollapseListener != null) {
mExpandCollapseListener.onListItemExpanded(getNearestParentPosition(parentIndex));
}
}
}
/**
* Collapses a specified parent item. Calls through to the
* ExpandCollapseListener and adds children of the specified parent to the
* total list of items.
*
* @param parentWrapper The ExpandableWrapper of the parent to collapse
* @param parentIndex The index of the parent to collapse
* @param collapseTriggeredByListItemClick true if expansion was triggered
* by a click event, false otherwise.
*/
private void collapseParentListItem(ExpandableWrapper<P, C> parentWrapper, int parentIndex, boolean collapseTriggeredByListItemClick) {
if (parentWrapper.isExpanded()) {
parentWrapper.setExpanded(false);
List<ExpandableWrapper<P, C>> childItemList = parentWrapper.getChildItemList();
if (childItemList != null) {
int childListItemCount = childItemList.size();
for (int i = childListItemCount - 1; i >= 0; i--) {
mItemList.remove(parentIndex + i + 1);
}
notifyItemRangeRemoved(parentIndex + 1, childListItemCount);
}
if (collapseTriggeredByListItemClick && mExpandCollapseListener != null) {
mExpandCollapseListener.onListItemCollapsed(getNearestParentPosition(parentIndex));
}
}
}
/**
* Given the index relative to the entire RecyclerView, returns the nearest
* ParentPosition without going past the given index.
*
* If it is the index of a parent, will return the corresponding parent position.
* If it is the index of a child within the RV, will return the position of that child's parent.
*/
int getNearestParentPosition(int fullPosition) {
if (fullPosition == 0) {
return 0;
}
int parentCount = -1;
for (int i = 0; i <= fullPosition; i++) {
ExpandableWrapper<P, C> listItem = mItemList.get(i);
if (listItem.isParent()) {
parentCount++;
}
}
return parentCount;
}
/**
* Given the index relative to the entire RecyclerView for a child item,
* returns the child position within the child list of the parent.
*/
int getChildPosition(int fullPosition) {
if (fullPosition == 0) {
return 0;
}
int childCount = 0;
for (int i = 0; i < fullPosition; i++) {
ExpandableWrapper<P, C> listItem = mItemList.get(i);
if (listItem.isParent()) {
childCount = 0;
} else {
childCount++;
}
}
return childCount;
}
// endregion
// region Data Manipulation
/**
* Notify any registered observers that the parent reflected at {@code parentPosition}
* has been newly inserted. The parent previously at {@code parentPosition} is now at
* position {@code parentPosition + 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.
*
* @param parentPosition Position of the newly inserted parent in the data set, relative
* to the list of parents only.
*
* @see #notifyParentItemRangeInserted(int, int)
*/
public void notifyParentItemInserted(int parentPosition) {
P parentListItem = mParentItemList.get(parentPosition);
int wrapperIndex;
if (parentPosition < mParentItemList.size() - 1) {
wrapperIndex = getParentExpandableWrapperIndex(parentPosition);
} else {
wrapperIndex = mItemList.size();
}
int sizeChanged = addParentWrapper(wrapperIndex, parentListItem);
notifyItemRangeInserted(wrapperIndex, sizeChanged);
}
/**
* Notify any registered observers that the currently reflected {@code itemCount}
* parents starting at {@code parentPositionStart} have been newly inserted.
* The parents previously located at {@code parentPositionStart} and beyond
* can now be found starting at position {@code parentPositionStart + itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPositionStart Position of the first parent that was inserted, relative
* to the list of parents only.
* @param itemCount Number of items inserted
*
* @see #notifyParentItemInserted(int)
*/
public void notifyParentItemRangeInserted(int parentPositionStart, int itemCount) {
int initialWrapperIndex;
if (parentPositionStart < mParentItemList.size() - itemCount) {
initialWrapperIndex = getParentExpandableWrapperIndex(parentPositionStart);
} else {
initialWrapperIndex = mItemList.size();
}
int sizeChanged = 0;
int wrapperIndex = initialWrapperIndex;
int changed;
int parentPositionEnd = parentPositionStart + itemCount;
for (int i = parentPositionStart; i < parentPositionEnd; i++) {
P parentListItem = mParentItemList.get(i);
changed = addParentWrapper(wrapperIndex, parentListItem);
wrapperIndex += changed;
sizeChanged += changed;
}
notifyItemRangeInserted(initialWrapperIndex, sizeChanged);
}
private int addParentWrapper(int wrapperIndex, P parentListItem) {
int sizeChanged = 1;
ExpandableWrapper<P, C> parentWrapper = new ExpandableWrapper<>(parentListItem);
mItemList.add(wrapperIndex, parentWrapper);
if (parentWrapper.isParentInitiallyExpanded()) {
parentWrapper.setExpanded(true);
List<ExpandableWrapper<P, C>> childItemList = parentWrapper.getChildItemList();
mItemList.addAll(wrapperIndex + sizeChanged, childItemList);
sizeChanged += childItemList.size();
}
return sizeChanged;
}
/**
* Notify any registered observers that the parents previously located at {@code parentPosition}
* has been removed from the data set. The parents previously located at and after
* {@code parentPosition} may now be found at {@code oldPosition - 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPosition Position of the parent that has now been removed, relative
* to the list of parents only.
*/
public void notifyParentItemRemoved(int parentPosition) {
int wrapperIndex = getParentExpandableWrapperIndex(parentPosition);
int sizeChanged = removeParentWrapper(wrapperIndex);
notifyItemRangeRemoved(wrapperIndex, sizeChanged);
}
/**
* Notify any registered observers that the {@code itemCount} parents previously
* located at {@code parentPositionStart} have been removed from the data set. The parents
* previously located at and after {@code parentPositionStart + itemCount} may now be
* found at {@code oldPosition - itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPositionStart The previous position of the first parent that was
* removed, relative to list of parents only.
* @param itemCount Number of parents removed from the data set
*/
public void notifyParentItemRangeRemoved(int parentPositionStart, int itemCount) {
int sizeChanged = 0;
int wrapperIndex = getParentExpandableWrapperIndex(parentPositionStart);
for (int i = 0; i < itemCount; i++) {
sizeChanged += removeParentWrapper(wrapperIndex);
}
notifyItemRangeRemoved(wrapperIndex, sizeChanged);
}
private int removeParentWrapper(int parentWrapperIndex) {
int sizeChanged = 1;
ExpandableWrapper<P, C> parentWrapper = mItemList.remove(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
int childListSize = parentWrapper.getChildItemList().size();
for (int i = 0; i < childListSize; i++) {
mItemList.remove(parentWrapperIndex);
sizeChanged++;
}
}
return sizeChanged;
}
/**
* Notify any registered observers that the parent at {@code parentPosition} has changed.
* This will also trigger an item changed for children of the parent list specified.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* reflection of the data at {@code parentPosition} is out of date and should be updated.
* The parent at {@code parentPosition} retains the same identity. This means
* the number of children must stay the same.
*
* @param parentPosition Position of the item that has changed
*/
public void notifyParentItemChanged(int parentPosition) {
P parentListItem = mParentItemList.get(parentPosition);
int wrapperIndex = getParentExpandableWrapperIndex(parentPosition);
int sizeChanged = changeParentWrapper(wrapperIndex, parentListItem);
notifyItemRangeChanged(wrapperIndex, sizeChanged);
}
/**
* Notify any registered observers that the {@code itemCount} parents starting
* at {@code parentPositionStart} have changed. This will also trigger an item changed
* for children of the parent list specified.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* reflection of the data in the given position range is out of date and should be updated.
* The parents in the given range retain the same identity. This means that the number of
* children must stay the same.
*
* @param parentPositionStart Position of the item that has changed
* @param itemCount Number of parents changed in the data set
*/
public void notifyParentItemRangeChanged(int parentPositionStart, int itemCount) {
int initialWrapperIndex = getParentExpandableWrapperIndex(parentPositionStart);
int wrapperIndex = initialWrapperIndex;
int sizeChanged = 0;
int changed;
P parentListItem;
for (int j = 0; j < itemCount; j++) {
parentListItem = mParentItemList.get(parentPositionStart);
changed = changeParentWrapper(wrapperIndex, parentListItem);
sizeChanged += changed;
wrapperIndex += changed;
parentPositionStart++;
}
notifyItemRangeChanged(initialWrapperIndex, sizeChanged);
}
private int changeParentWrapper(int wrapperIndex, P parentListItem) {
ExpandableWrapper<P, C> parentWrapper = mItemList.get(wrapperIndex);
parentWrapper.setParentListItem(parentListItem);
int sizeChanged = 1;
if (parentWrapper.isExpanded()) {
List<ExpandableWrapper<P, C>> childItems = parentWrapper.getChildItemList();
int childListSize = childItems.size();
for (int i = 0; i < childListSize; i++) {
mItemList.set(wrapperIndex + i + 1, childItems.get(i));
sizeChanged++;
}
}
return sizeChanged;
}
/**
* Notify any registered observers that the parent and its children reflected at
* {@code fromParentPosition} has been moved to {@code toParentPosition}.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param fromParentPosition Previous position of the parent, relative to the list of
* parents only.
* @param toParentPosition New position of the parent, relative to the list of parents only.
*/
public void notifyParentItemMoved(int fromParentPosition, int toParentPosition) {
int fromWrapperIndex = getParentExpandableWrapperIndex(fromParentPosition);
ExpandableWrapper<P, C> fromParentWrapper = mItemList.get(fromWrapperIndex);
// If the parent is collapsed we can take advantage of notifyItemMoved otherwise
// we are forced to do a "manual" move by removing and then adding the parent + children
// (no notifyItemRangeMovedAvailable)
boolean isCollapsed = !fromParentWrapper.isExpanded();
boolean isExpandedNoChildren = !isCollapsed && (fromParentWrapper.getChildItemList().size() == 0);
if (isCollapsed || isExpandedNoChildren) {
int toWrapperIndex = getParentExpandableWrapperIndex(toParentPosition);
ExpandableWrapper<P, C> toParentWrapper = mItemList.get(toWrapperIndex);
mItemList.remove(fromWrapperIndex);
int childOffset = 0;
if (toParentWrapper.isExpanded()) {
childOffset = toParentWrapper.getChildItemList().size();
}
mItemList.add(toWrapperIndex + childOffset, fromParentWrapper);
notifyItemMoved(fromWrapperIndex, toWrapperIndex + childOffset);
} else {
// Remove the parent and children
int sizeChanged = 0;
int childListSize = fromParentWrapper.getChildItemList().size();
for (int i = 0; i < childListSize + 1; i++) {
mItemList.remove(fromWrapperIndex);
sizeChanged++;
}
notifyItemRangeRemoved(fromWrapperIndex, sizeChanged);
// Add the parent and children at new position
int toWrapperIndex = getParentExpandableWrapperIndex(toParentPosition);
int childOffset = 0;
if (toWrapperIndex != -1) {
ExpandableWrapper<P, C> toParentWrapper = mItemList.get(toWrapperIndex);
if (toParentWrapper.isExpanded()) {
childOffset = toParentWrapper.getChildItemList().size();
}
} else {
toWrapperIndex = mItemList.size();
}
mItemList.add(toWrapperIndex + childOffset, fromParentWrapper);
List<ExpandableWrapper<P, C>> childItemList = fromParentWrapper.getChildItemList();
sizeChanged = childItemList.size() + 1;
mItemList.addAll(toWrapperIndex + childOffset + 1, childItemList);
notifyItemRangeInserted(toWrapperIndex + childOffset, sizeChanged);
}
}
/**
* Notify any registered observers that the parent reflected at {@code parentPosition}
* has a child list item that has been newly inserted at {@code childPosition}.
* The child list item previously at {@code childPosition} is now at
* position {@code childPosition + 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.
*
* @param parentPosition Position of the parent which has been added a child, relative
* to the list of parents only.
* @param childPosition Position of the child that has been inserted, relative to children
* of the parent specified by {@code parentPosition} only.
*
*/
public void notifyChildItemInserted(int parentPosition, int childPosition) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
ExpandableWrapper<P, C> child = parentWrapper.getChildItemList().get(childPosition);
mItemList.add(parentWrapperIndex + childPosition + 1, child);
notifyItemInserted(parentWrapperIndex + childPosition + 1);
}
}
/**
* Notify any registered observers that the parent reflected at {@code parentPosition}
* has {@code itemCount} child list items that have been newly inserted at {@code childPositionStart}.
* The child list item previously at {@code childPositionStart} and beyond are now at
* position {@code childPositionStart + itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.
*
* @param parentPosition Position of the parent which has been added a child, relative
* to the list of parents only.
* @param childPositionStart Position of the first child that has been inserted,
* relative to children of the parent specified by
* {@code parentPosition} only.
* @param itemCount number of children inserted
*
*/
public void notifyChildItemRangeInserted(int parentPosition, int childPositionStart, int itemCount) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
List<ExpandableWrapper<P, C>> childList = parentWrapper.getChildItemList();
for (int i = 0; i < itemCount; i++) {
ExpandableWrapper<P, C> child = childList.get(childPositionStart + i);
mItemList.add(parentWrapperIndex + childPositionStart + i + 1, child);
}
notifyItemRangeInserted(parentWrapperIndex + childPositionStart + 1, itemCount);
}
}
/**
* Notify any registered observers that the parent located at {@code parentPosition}
* has a child that has been removed from the data set, previously located at {@code childPosition}.
* The child list item previously located at and after {@code childPosition} may
* now be found at {@code childPosition - 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPosition Position of the parent which has a child removed from, relative
* to the list of parents only.
* @param childPosition Position of the child that has been removed, relative to children
* of the parent specified by {@code parentPosition} only.
*/
public void notifyChildItemRemoved(int parentPosition, int childPosition) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
mItemList.remove(parentWrapperIndex + childPosition + 1);
notifyItemRemoved(parentWrapperIndex + childPosition + 1);
}
}
/**
* Notify any registered observers that the parent located at {@code parentPosition}
* has {@code itemCount} children that have been removed from the data set, previously
* located at {@code childPositionStart} onwards. The child previously located at and
* after {@code childPositionStart} may now be found at {@code childPositionStart - itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPosition Position of the parent which has a child removed from, relative
* to the list of parents only.
* @param childPositionStart Position of the first child that has been removed, relative
* to children of the parent specified by {@code parentPosition} only.
* @param itemCount number of children removed
*/
public void notifyChildItemRangeRemoved(int parentPosition, int childPositionStart, int itemCount) {
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
for (int i = 0; i < itemCount; i++) {
mItemList.remove(parentWrapperIndex + childPositionStart + 1);
}
notifyItemRangeRemoved(parentWrapperIndex + childPositionStart + 1, itemCount);
}
}
/**
* Notify any registered observers that the parent at {@code parentPosition} has
* a child located at {@code childPosition} that has changed.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* reflection of the data at {@code childPosition} is out of date and should be updated.
* The parent at {@code childPosition} retains the same identity.
*
* @param parentPosition Position of the parent which has a child that has changed
* @param childPosition Position of the child that has changed
*/
public void notifyChildItemChanged(int parentPosition, int childPosition) {
P parentListItem = mParentItemList.get(parentPosition);
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
parentWrapper.setParentListItem(parentListItem);
if (parentWrapper.isExpanded()) {
int listChildPosition = parentWrapperIndex + childPosition + 1;
ExpandableWrapper<P, C> child = parentWrapper.getChildItemList().get(childPosition);
mItemList.set(listChildPosition, child);
notifyItemChanged(listChildPosition);
}
}
/**
* Notify any registered observers that the parent at {@code parentPosition} has
* {@code itemCount} children starting at {@code childPositionStart} that have changed.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* The parent at {@code childPositionStart} retains the same identity.
* reflection of the set of {@code itemCount} children starting at {@code childPositionStart}
* are out of date and should be updated.
*
* @param parentPosition Position of the parent who has a child that has changed
* @param childPositionStart Position of the first child that has changed
* @param itemCount number of children changed
*/
public void notifyChildItemRangeChanged(int parentPosition, int childPositionStart, int itemCount) {
P parentListItem = mParentItemList.get(parentPosition);
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
parentWrapper.setParentListItem(parentListItem);
if (parentWrapper.isExpanded()) {
int listChildPosition = parentWrapperIndex + childPositionStart + 1;
for (int i = 0; i < itemCount; i++) {
ExpandableWrapper<P, C> child
= parentWrapper.getChildItemList().get(childPositionStart + i);
mItemList.set(listChildPosition + i, child);
}
notifyItemRangeChanged(listChildPosition, itemCount);
}
}
/**
* Notify any registered observers that the child list item contained within the parent
* at {@code parentPosition} has moved from {@code fromChildPosition} to {@code toChildPosition}.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param parentPosition Position of the parent which has a child that has moved
* @param fromChildPosition Previous position of the child
* @param toChildPosition New position of the child
*/
public void notifyChildItemMoved(int parentPosition, int fromChildPosition, int toChildPosition) {
P parentListItem = mParentItemList.get(parentPosition);
int parentWrapperIndex = getParentExpandableWrapperIndex(parentPosition);
ExpandableWrapper<P, C> parentWrapper = mItemList.get(parentWrapperIndex);
parentWrapper.setParentListItem(parentListItem);
if (parentWrapper.isExpanded()) {
ExpandableWrapper<P, C> fromChild = mItemList.remove(parentWrapperIndex + 1 + fromChildPosition);
mItemList.add(parentWrapperIndex + 1 + toChildPosition, fromChild);
notifyItemMoved(parentWrapperIndex + 1 + fromChildPosition, parentWrapperIndex + 1 + toChildPosition);
}
}
// endregion
/**
* Generates a full list of all parents and their children, in order.
*
* @param parentItemList A list of the parents from
* the {@link ExpandableRecyclerAdapter}
* @return A list of all parents and their children, expanded
*/
private List<ExpandableWrapper<P, C>> generateParentChildItemList(List<P> parentItemList) {
List<ExpandableWrapper<P, C>> itemList = new ArrayList<>();
int parentListItemCount = parentItemList.size();
for (int i = 0; i < parentListItemCount; i++) {
ExpandableWrapper<P, C> parentWrapper = new ExpandableWrapper<>(parentItemList.get(i));
itemList.add(parentWrapper);
if (parentWrapper.isParentInitiallyExpanded()) {
parentWrapper.setExpanded(true);
List<ExpandableWrapper<P, C>> childList = parentWrapper.getChildItemList();
int childListItemCount = childList.size();
for (int j = 0; j < childListItemCount; j++) {
ExpandableWrapper<P, C> childWrapper = childList.get(j);
itemList.add(childWrapper);
}
}
}
return itemList;
}
/**
* Generates a HashMap used to store expanded state for items in the list
* on configuration change or whenever onResume is called.
*
* @return A HashMap containing the expanded state of all parents
*/
private HashMap<Integer, Boolean> generateExpandedStateMap() {
HashMap<Integer, Boolean> parentListItemHashMap = new HashMap<>();
int childCount = 0;
int listItemCount = mItemList.size();
for (int i = 0; i < listItemCount; i++) {
if (mItemList.get(i) != null) {
ExpandableWrapper<P, C> listItem = mItemList.get(i);
if (listItem.isParent()) {
parentListItemHashMap.put(i - childCount, listItem.isExpanded());
} else {
childCount++;
}
}
}
return parentListItemHashMap;
}
/**
* Gets the index of a ExpandableWrapper within the helper item list based on
* the index of the ExpandableWrapper.
*
* @param parentIndex The index of the parent in the list of parents
* @return The index of the parent in the list of all views in the adapter
*/
private int getParentExpandableWrapperIndex(int parentIndex) {
int parentCount = 0;
int listItemCount = mItemList.size();
for (int i = 0; i < listItemCount; i++) {
if (mItemList.get(i).isParent()) {
parentCount++;
if (parentCount > parentIndex) {
return i;
}
}
}
return -1;
}
}
| fix collapsing and expanding via object to reference original wrapper
getItem() to return childListItem, not ChildItemList
| expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java | fix collapsing and expanding via object to reference original wrapper getItem() to return childListItem, not ChildItemList | <ide><path>xpandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
<ide> return;
<ide> }
<ide>
<del> expandViews(parentWrapper, parentWrapperIndex);
<add> expandViews(mItemList.get(parentWrapperIndex), parentWrapperIndex);
<ide> }
<ide>
<ide> /**
<ide> return;
<ide> }
<ide>
<del> collapseViews(parentWrapper, parentWrapperIndex);
<add> collapseViews(mItemList.get(parentWrapperIndex), parentWrapperIndex);
<ide> }
<ide>
<ide> /**
<ide> if (listItem.isParent()) {
<ide> return listItem.getParentListItem();
<ide> } else {
<del> return listItem.getChildItemList();
<add> return listItem.getChildListItem();
<ide> }
<ide> } else {
<ide> return null; |
|
Java | mit | error: pathspec 'src/pp/arithmetic/all/_69_mySqrt.java' did not match any file(s) known to git
| 9f9924fb8bacfc3bd0270b461ff3808dd470bb92 | 1 | pphdsny/ArithmeticTest | package pp.arithmetic.all;
/**
* Created by wangpeng on 2019-03-15.
* 69. x 的平方根
* <p>
* 实现 int sqrt(int x) 函数。
* <p>
* 计算并返回 x 的平方根,其中 x 是非负整数。
* <p>
* 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
* <p>
* 示例 1:
* <p>
* 输入: 4
* 输出: 2
* 示例 2:
* <p>
* 输入: 8
* 输出: 2
* 说明: 8 的平方根是 2.82842...,
* 由于返回类型是整数,小数部分将被舍去。
*
* @see <a href="https://leetcode-cn.com/problems/sqrtx/">sqrtx</a>
*/
public class _69_mySqrt {
public static void main(String[] args) {
_69_mySqrt mySqrt = new _69_mySqrt();
System.out.println(mySqrt.mySqrt(8));
}
public int mySqrt(int x) {
double sqrt = Math.sqrt(x);
return (int) sqrt;
}
}
| src/pp/arithmetic/all/_69_mySqrt.java | feat(EASY):
69_mySqrt
| src/pp/arithmetic/all/_69_mySqrt.java | feat(EASY): 69_mySqrt | <ide><path>rc/pp/arithmetic/all/_69_mySqrt.java
<add>package pp.arithmetic.all;
<add>
<add>/**
<add> * Created by wangpeng on 2019-03-15.
<add> * 69. x 的平方根
<add> * <p>
<add> * 实现 int sqrt(int x) 函数。
<add> * <p>
<add> * 计算并返回 x 的平方根,其中 x 是非负整数。
<add> * <p>
<add> * 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
<add> * <p>
<add> * 示例 1:
<add> * <p>
<add> * 输入: 4
<add> * 输出: 2
<add> * 示例 2:
<add> * <p>
<add> * 输入: 8
<add> * 输出: 2
<add> * 说明: 8 的平方根是 2.82842...,
<add> * 由于返回类型是整数,小数部分将被舍去。
<add> *
<add> * @see <a href="https://leetcode-cn.com/problems/sqrtx/">sqrtx</a>
<add> */
<add>public class _69_mySqrt {
<add> public static void main(String[] args) {
<add> _69_mySqrt mySqrt = new _69_mySqrt();
<add> System.out.println(mySqrt.mySqrt(8));
<add> }
<add>
<add> public int mySqrt(int x) {
<add> double sqrt = Math.sqrt(x);
<add> return (int) sqrt;
<add> }
<add>} |
|
JavaScript | mit | 3ccd8c21c8fc57960154e01ddb60323a6ac4b81d | 0 | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | const HELPDESK_ITEMS = [
{
label: gettext('Helpdesk'),
icon: 'fa-headphones',
link: 'support.helpdesk'
}
];
const DASHBOARD_ITEMS = [
{
label: gettext('Dashboard'),
icon: 'fa-th-large',
link: 'support.dashboard'
},
{
label: gettext('Support requests'),
icon: 'fa-list',
link: 'support.list'
}
];
const REPORT_ITEMS = [
{
label: gettext('Users'),
icon: 'fa-users',
link: 'support.users',
feature: 'support.users'
},
{
label: gettext('Resources'),
icon: 'fa-files-o',
link: 'support.resources',
feature: 'resources.legacy'
},
{
label: gettext('Orders'),
icon: 'fa-files-o',
link: 'marketplace-support-order-items',
feature: 'marketplace'
},
{
label: gettext('Resources'),
icon: 'fa-files-o',
link: 'marketplace-support-resources',
feature: 'marketplace'
},
{
label: gettext('Plan capacity'),
icon: 'fa-puzzle-piece',
link: 'marketplace-support-plan-usages',
feature: 'marketplace'
},
{
label: gettext('Usage reports'),
icon: 'fa-puzzle-piece',
link: 'marketplace-support-usage-reports',
feature: 'marketplace'
},
{
label: gettext('Resources usage'),
icon: 'fa-map',
link: 'support.resources-treemap',
feature: 'support.resources-treemap'
},
{
label: gettext('Shared providers'),
icon: 'fa-random',
link: 'support.shared-providers',
feature: 'support.shared-providers'
},
{
label: gettext('Financial overview'),
icon: 'fa-university',
link: 'support.organizations',
feature: 'support.organizations'
},
{
label: gettext('Usage overview'),
icon: 'fa-map',
link: 'support.usage',
feature: 'support.usage',
children: [
{
label: gettext('Flowmap'),
icon: 'fa-sitemap',
link: 'support.flowmap',
feature: 'support.flowmap',
},
{
label: gettext('Heatmap'),
icon: 'fa-fire',
link: 'support.heatmap',
feature: 'support.heatmap',
},
{
label: gettext('Sankey diagram'),
icon: 'fa-code-fork',
link: 'support.sankey-diagram',
feature: 'support.sankey-diagram',
}
]
},
{
label: gettext('VM type overview'),
icon: 'fa-desktop',
link: 'support.vm-type-overview',
feature: 'support.vm-type-overview'
},
];
// This service checks users status and returns different sidebar items and router state
export default class IssueNavigationService {
// @ngInject
constructor($state, usersService, currentStateService, features, SidebarExtensionService) {
this.$state = $state;
this.usersService = usersService;
this.currentStateService = currentStateService;
this.features = features;
this.sidebarExtensionService = SidebarExtensionService;
}
get isVisible() {
if (this.features.isVisible('support')) {
return true;
}
const user = this.usersService.currentUser;
return user && (user.is_staff || user.is_support);
}
gotoDashboard() {
if (!this.features.isVisible('support')) {
if (this.features.isVisible('marketplace')) {
return this.$state.go('marketplace-support-resources');
} else {
return this.$state.go('support.resources');
}
}
return this.usersService.getCurrentUser().then(user => {
if (user.is_staff || user.is_support) {
this.$state.go('support.helpdesk');
} else {
this.$state.go('support.dashboard');
}
});
}
getSidebarItems() {
return this.usersService.getCurrentUser().then(user => {
this.currentUser = user;
if (!this.features.isVisible('support')) {
return [];
}
const dashboardItems = this.sidebarExtensionService.filterItems(DASHBOARD_ITEMS);
const helpdeskItems = this.sidebarExtensionService.filterItems(HELPDESK_ITEMS);
if (user.is_support && !user.is_staff) {
return helpdeskItems;
} else if (user.is_support && user.is_staff) {
return [...helpdeskItems, ...dashboardItems];
} else {
return dashboardItems;
}
}).then(items => {
items = angular.copy(items);
if (this.getBackItemLabel()) {
items.unshift(this.getBackItem());
}
return items;
}).then(items => {
if (this.currentUser.is_support || this.currentUser.is_staff) {
return [...items, ...this.sidebarExtensionService.filterItems(REPORT_ITEMS)];
}
return items;
});
}
setPrevState(state, params) {
if (state.data && state.data.workspace && state.data.workspace !== 'support') {
this.prevState = state;
this.prevParams = params;
this.prevWorkspace = state.data.workspace;
}
}
getBackItem() {
return {
label: this.getBackItemLabel(),
icon: 'fa-arrow-left',
action: () => this.$state.go(this.prevState, this.prevParams)
};
}
getBackItemLabel() {
const prevWorkspace = this.prevWorkspace;
if (prevWorkspace === 'project') {
return gettext('Back to project');
} else if (prevWorkspace === 'organization' &&
(this.currentStateService.getOwnerOrStaff() || this.currentUser.is_support)) {
return gettext('Back to organization');
} else if (prevWorkspace === 'user') {
return gettext('Back to personal dashboard');
}
}
}
// @ngInject
export function attachStateUtils($rootScope, IssueNavigationService) {
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
IssueNavigationService.setPrevState(fromState, fromParams);
});
}
| src/issues/workspace/issue-navigation-service.js | const HELPDESK_ITEMS = [
{
label: gettext('Helpdesk'),
icon: 'fa-headphones',
link: 'support.helpdesk'
}
];
const DASHBOARD_ITEMS = [
{
label: gettext('Dashboard'),
icon: 'fa-th-large',
link: 'support.dashboard'
},
{
label: gettext('Support requests'),
icon: 'fa-list',
link: 'support.list'
}
];
const REPORT_ITEMS = [
{
label: gettext('Users'),
icon: 'fa-users',
link: 'support.users',
feature: 'support.users'
},
{
label: gettext('Resources'),
icon: 'fa-files-o',
link: 'support.resources',
feature: 'resources.legacy'
},
{
label: gettext('Orders'),
icon: 'fa-files-o',
link: 'marketplace-support-order-items',
feature: 'marketplace'
},
{
label: gettext('Resources'),
icon: 'fa-files-o',
link: 'marketplace-support-resources',
feature: 'marketplace'
},
{
label: gettext('Plan capacity'),
icon: 'fa-puzzle-piece',
link: 'marketplace-support-plan-usages',
feature: 'marketplace'
},
{
label: gettext('Usage reports'),
icon: 'fa-puzzle-piece',
link: 'marketplace-support-usage-reports',
feature: 'marketplace'
},
{
label: gettext('Resources usage'),
icon: 'fa-map',
link: 'support.resources-treemap',
feature: 'support.resources-treemap'
},
{
label: gettext('Shared providers'),
icon: 'fa-random',
link: 'support.shared-providers',
feature: 'support.shared-providers'
},
{
label: gettext('Financial overview'),
icon: 'fa-university',
link: 'support.organizations',
feature: 'support.organizations'
},
{
label: gettext('Usage overview'),
icon: 'fa-map',
link: 'support.usage',
feature: 'support.usage',
children: [
{
label: gettext('Flowmap'),
icon: 'fa-sitemap',
link: 'support.flowmap',
feature: 'support.flowmap',
},
{
label: gettext('Heatmap'),
icon: 'fa-fire',
link: 'support.heatmap',
feature: 'support.heatmap',
},
{
label: gettext('Sankey diagram'),
icon: 'fa-code-fork',
link: 'support.sankey-diagram',
feature: 'support.sankey-diagram',
}
]
},
{
label: gettext('VM type overview'),
icon: 'fa-desktop',
link: 'support.vm-type-overview',
feature: 'support.vm-type-overview'
},
];
// This service checks users status and returns different sidebar items and router state
export default class IssueNavigationService {
// @ngInject
constructor($state, usersService, currentStateService, features, SidebarExtensionService) {
this.$state = $state;
this.usersService = usersService;
this.currentStateService = currentStateService;
this.features = features;
this.sidebarExtensionService = SidebarExtensionService;
}
get isVisible() {
if (this.features.isVisible('support')) {
return true;
}
const user = this.usersService.currentUser;
return user && (user.is_staff || user.is_support);
}
gotoDashboard() {
if (!this.features.isVisible('support')) {
return this.$state.go('support.resources');
}
return this.usersService.getCurrentUser().then(user => {
if (user.is_staff || user.is_support) {
this.$state.go('support.helpdesk');
} else {
this.$state.go('support.dashboard');
}
});
}
getSidebarItems() {
return this.usersService.getCurrentUser().then(user => {
this.currentUser = user;
if (!this.features.isVisible('support')) {
return [];
}
const dashboardItems = this.sidebarExtensionService.filterItems(DASHBOARD_ITEMS);
const helpdeskItems = this.sidebarExtensionService.filterItems(HELPDESK_ITEMS);
if (user.is_support && !user.is_staff) {
return helpdeskItems;
} else if (user.is_support && user.is_staff) {
return [...helpdeskItems, ...dashboardItems];
} else {
return dashboardItems;
}
}).then(items => {
items = angular.copy(items);
if (this.getBackItemLabel()) {
items.unshift(this.getBackItem());
}
return items;
}).then(items => {
if (this.currentUser.is_support || this.currentUser.is_staff) {
return [...items, ...this.sidebarExtensionService.filterItems(REPORT_ITEMS)];
}
return items;
});
}
setPrevState(state, params) {
if (state.data && state.data.workspace && state.data.workspace !== 'support') {
this.prevState = state;
this.prevParams = params;
this.prevWorkspace = state.data.workspace;
}
}
getBackItem() {
return {
label: this.getBackItemLabel(),
icon: 'fa-arrow-left',
action: () => this.$state.go(this.prevState, this.prevParams)
};
}
getBackItemLabel() {
const prevWorkspace = this.prevWorkspace;
if (prevWorkspace === 'project') {
return gettext('Back to project');
} else if (prevWorkspace === 'organization' &&
(this.currentStateService.getOwnerOrStaff() || this.currentUser.is_support)) {
return gettext('Back to organization');
} else if (prevWorkspace === 'user') {
return gettext('Back to personal dashboard');
}
}
}
// @ngInject
export function attachStateUtils($rootScope, IssueNavigationService) {
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
IssueNavigationService.setPrevState(fromState, fromParams);
});
}
| Redirect by default to marketplace resource list in support workspace [WAL-2346]
| src/issues/workspace/issue-navigation-service.js | Redirect by default to marketplace resource list in support workspace [WAL-2346] | <ide><path>rc/issues/workspace/issue-navigation-service.js
<ide>
<ide> gotoDashboard() {
<ide> if (!this.features.isVisible('support')) {
<del> return this.$state.go('support.resources');
<add> if (this.features.isVisible('marketplace')) {
<add> return this.$state.go('marketplace-support-resources');
<add> } else {
<add> return this.$state.go('support.resources');
<add> }
<ide> }
<ide> return this.usersService.getCurrentUser().then(user => {
<ide> if (user.is_staff || user.is_support) { |
|
JavaScript | agpl-3.0 | f83cd274158862cf1d2b98a4bf4a50d035324475 | 0 | mupi/timtec,hacklabr/timtec,mupi/tecsaladeaula,virgilio/timtec,AllanNozomu/tecsaladeaula,AllanNozomu/tecsaladeaula,hacklabr/timtec,hacklabr/timtec,GustavoVS/timtec,mupi/timtec,mupi/tecsaladeaula,mupi/escolamupi,virgilio/timtec,AllanNozomu/tecsaladeaula,hacklabr/timtec,mupi/escolamupi,GustavoVS/timtec,mupi/timtec,AllanNozomu/tecsaladeaula,mupi/tecsaladeaula,virgilio/timtec,mupi/tecsaladeaula,virgilio/timtec,mupi/timtec,GustavoVS/timtec,GustavoVS/timtec | (function(angular){
var app = angular.module('edit-lesson');
app.controller('EditLessonController', ['$scope', 'Course', 'CourseProfessor', 'Lesson', 'VideoData', 'youtubePlayerApi',
function($scope, Course, CourseProfessor, Lesson, VideoData, youtubePlayerApi){
$scope.errors = {};
var httpErrors = {
'400': 'Os campos não foram preenchidos corretamente.',
'403': 'Você não tem permissão para ver conteúdo nesta página.',
'404': 'Este curso não existe!'
};
// load youtube
$scope.playerReady = false;
youtubePlayerApi.loadPlayer().then(function(p){
$scope.playerReady = true;
});
// end load youtube
$scope.play = function(youtube_id) {
youtubePlayerApi.loadPlayer().then(function(player){
if(player.getVideoData().video_id === youtube_id) return;
player.cueVideoById(youtube_id);
});
};
$scope.course = new Course();
$scope.lesson = new Lesson();
$scope.currentUnit = {};
$scope.courseProfessors = [];
$scope.activityTypes = [
{'name': 'simplechoice', 'label': 'Escolha simples'},
{'name': 'multiplechoice', 'label': 'Múltipla escolha'},
{'name': 'trueorfalse', 'label': 'Verdadeiro ou falso'},
{'name': 'relationship', 'label': 'Relacionar sentenças'},
{'name': 'html5', 'label': 'HTML5'}
];
/* Methods */
$scope.setLesson = function(l) {
$scope.lesson = l;
if(l.units.length > 0) {
$scope.selectUnit(l.units[0]);
} else {
$scope.addUnit();
}
};
$scope.saveLesson = function() {
var unitIndex = $scope.lesson.units.indexOf($scope.currentUnit);
$scope.lesson.saveOrUpdate()
.then(function(){
$scope.alert.success('Alterações salvas com sucesso.');
$scope.selectUnit($scope.lesson.units[unitIndex]);
})
.catch(function(resp){
$scope.alert.error(httpErrors[resp.status.toString()]);
});
};
$scope.selectUnit = function(u) {
$scope.currentUnit = u;
$scope.play(u.video.youtube_id);
};
$scope.addUnit = function() {
if(!$scope.lesson.units) {
$scope.lesson.units = [];
}
$scope.currentUnit = {};
$scope.lesson.units.push($scope.currentUnit);
};
$scope.removeCurrentUnit = function() {
if(!$scope.lesson.units) return;
if(!confirm('Apagar unidade?')) return;
var index = $scope.lesson.units.indexOf($scope.currentUnit);
$scope.lesson.units.splice(index,1);
index = index > 0 ? index - 1 : 0;
if(index < $scope.lesson.units.length) {
$scope.selectUnit($scope.lesson.units[index]);
}
};
$scope.setCurrentUnitVideo = function(youtube_id) {
if(!$scope.currentUnit.video) {
$scope.currentUnit.video = {};
}
$scope.currentUnit.video.youtube_id = youtube_id;
VideoData.load(youtube_id).then(function(data){
$scope.currentUnit.video.name = data.entry.title.$t;
});
$scope.play(youtube_id);
};
$scope.loadActivityTemplateUrl = function() {
if(!$scope.currentUnit.activity) return;
return '/static/templates/activities/activity_{0}.html'
.format($scope.currentUnit.activity.type);
};
$scope.addNewActivity = function() {
if(!$scope.currentUnit) return;
var type = $scope.newActivityType;
$scope.currentUnit.activity = {
'type': type,
'data': {
'question': '',
'alternatives': [],
'column1': [],
'column2': []
},
'expected': (type==='simplechoice' || type==='html5') ? '' : []
};
};
/* End Methods */
// vv como faz isso de uma formula angular ?
var match = document.location.href.match(/courses\/(\d+)\/lessons\/(new|\d+)/);
if( match ) {
$scope.isNewLesson = ('new' === match[2]);
$scope.course.$get({id: match[1]})
.then(function(course){
$scope.courseProfessors = CourseProfessor.query({ course: course.id });
$scope.lesson.course = course.slug;
return $scope.courseProfessors.$promise;
});
Lesson.query({course__id: match[1]}).$promise
.then(function(lessons){
$scope.lessons = lessons;
lessons.forEach(function(lesson){
if(lesson.id === parseInt(match[2], 10)) {
$scope.setLesson(lesson);
}
});
if($scope.isNewLesson) {
$scope.addUnit();
}
})
.catch(function(resp){
$scope.alert.error(httpErrors[resp.status.toString()]);
});
}
// ^^ como faz isso de uma formula angular ?
}
]);
})(window.angular);
| administration/static/js/edit-lesson/controllers.js | (function(angular){
var app = angular.module('edit-lesson');
app.controller('EditLessonController', ['$scope', 'Course', 'CourseProfessor', 'Lesson', 'VideoData', 'youtubePlayerApi',
function($scope, Course, CourseProfessor, Lesson, VideoData, youtubePlayerApi){
$scope.errors = {};
var httpErrors = {
'400': 'Os campos não foram preenchidos corretamente.',
'403': 'Você não tem permissão para ver conteúdo nesta página.',
'404': 'Este curso não existe!'
};
// load youtube
$scope.playerReady = false;
youtubePlayerApi.loadPlayer().then(function(p){
$scope.playerReady = true;
});
// end load youtube
$scope.play = function(youtube_id) {
youtubePlayerApi.loadPlayer().then(function(player){
if(player.getVideoData().video_id === youtube_id) return;
player.cueVideoById(youtube_id);
});
};
$scope.course = new Course();
$scope.lesson = new Lesson();
$scope.currentUnit = {};
$scope.courseProfessors = [];
$scope.activityTypes = [
{'name': 'simplechoice', 'label': 'Escolha simples'},
{'name': 'multiplechoice', 'label': 'Múltipla escolha'},
{'name': 'trueorfalse', 'label': 'Verdadeiro ou falso'},
{'name': 'relationship', 'label': 'Relacionar sentenças'},
{'name': 'html5', 'label': 'HTML5'}
];
/* Methods */
$scope.setLesson = function(l) {
$scope.lesson = l;
if(l.units.length > 0) {
$scope.selectUnit(l.units[0]);
} else {
$scope.addUnit();
}
};
$scope.saveLesson = function() {
$scope.lesson.saveOrUpdate()
.then(function(){
$scope.alert.success('Alterações salvas com sucesso.');
})
.catch(function(resp){
$scope.alert.error(httpErrors[resp.status.toString()]);
});
};
$scope.selectUnit = function(u) {
$scope.currentUnit = u;
$scope.play(u.video.youtube_id);
};
$scope.addUnit = function() {
if(!$scope.lesson.units) {
$scope.lesson.units = [];
}
$scope.currentUnit = {};
$scope.lesson.units.push($scope.currentUnit);
};
$scope.removeCurrentUnit = function() {
if(!$scope.lesson.units) return;
if(!confirm('Apagar unidade?')) return;
var index = $scope.lesson.units.indexOf($scope.currentUnit);
$scope.lesson.units.splice(index,1);
index = index > 0 ? index - 1 : 0;
if(index < $scope.lesson.units.length) {
$scope.selectUnit($scope.lesson.units[index]);
}
};
$scope.setCurrentUnitVideo = function(youtube_id) {
if(!$scope.currentUnit.video) {
$scope.currentUnit.video = {};
}
$scope.currentUnit.video.youtube_id = youtube_id;
VideoData.load(youtube_id).then(function(data){
$scope.currentUnit.video.name = data.entry.title.$t;
});
$scope.play(youtube_id);
};
$scope.loadActivityTemplateUrl = function() {
if(!$scope.currentUnit.activity) return;
return '/static/templates/activities/activity_{0}.html'
.format($scope.currentUnit.activity.type);
};
$scope.addNewActivity = function() {
if(!$scope.currentUnit) return;
var type = $scope.newActivityType;
$scope.currentUnit.activity = {
'type': type,
'data': {
'question': '',
'alternatives': [],
'column1': [],
'column2': []
},
'expected': (type==='simplechoice' || type==='html5') ? '' : []
};
};
/* End Methods */
// vv como faz isso de uma formula angular ?
var match = document.location.href.match(/courses\/(\d+)\/lessons\/(new|\d+)/);
if( match ) {
$scope.isNewLesson = ('new' === match[2]);
$scope.course.$get({id: match[1]})
.then(function(course){
$scope.courseProfessors = CourseProfessor.query({ course: course.id });
$scope.lesson.course = course.slug;
return $scope.courseProfessors.$promise;
});
Lesson.query({course__id: match[1]}).$promise
.then(function(lessons){
$scope.lessons = lessons;
lessons.forEach(function(lesson){
if(lesson.id === parseInt(match[2], 10)) {
$scope.setLesson(lesson);
}
});
if($scope.isNewLesson) {
$scope.addUnit();
}
})
.catch(function(resp){
$scope.alert.error(httpErrors[resp.status.toString()]);
});
}
// ^^ como faz isso de uma formula angular ?
}
]);
})(window.angular);
| re-select unit after save lesson
| administration/static/js/edit-lesson/controllers.js | re-select unit after save lesson | <ide><path>dministration/static/js/edit-lesson/controllers.js
<ide> };
<ide>
<ide> $scope.saveLesson = function() {
<add> var unitIndex = $scope.lesson.units.indexOf($scope.currentUnit);
<add>
<ide> $scope.lesson.saveOrUpdate()
<ide> .then(function(){
<ide> $scope.alert.success('Alterações salvas com sucesso.');
<add> $scope.selectUnit($scope.lesson.units[unitIndex]);
<ide> })
<ide> .catch(function(resp){
<ide> $scope.alert.error(httpErrors[resp.status.toString()]); |
|
Java | lgpl-2.1 | e0bf822d7bce71f99eea31a35ab4bbd087850649 | 0 | xwiki-contrib/currikiorg,xwiki-contrib/currikiorg,xwiki-contrib/currikiorg,xwiki-contrib/currikiorg,i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork,xwiki-contrib/currikiorg,xwiki-contrib/currikiorg,i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork | /**
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* <p/>
* This is free software;you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation;either version2.1of
* the License,or(at your option)any later version.
* <p/>
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY;without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
* Lesser General Public License for more details.
* <p/>
* You should have received a copy of the GNU Lesser General Public
* License along with this software;if not,write to the Free
* Software Foundation,Inc.,51 Franklin St,Fifth Floor,Boston,MA
* 02110-1301 USA,or see the FSF site:http://www.fsf.org.
*/
package org.xwiki.plugin.spacemanager.impl;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.user.api.XWikiGroupService;
import com.xpn.xwiki.api.Api;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.plugin.XWikiDefaultPlugin;
import com.xpn.xwiki.plugin.XWikiPluginInterface;
import org.xwiki.plugin.spacemanager.api.*;
import org.xwiki.plugin.spacemanager.plugin.SpaceManagerPluginApi;
import java.util.*;
/**
* Manages spaces
*/
public class SpaceManagerImpl extends XWikiDefaultPlugin implements SpaceManager {
public final static String SPACEMANAGER_EXTENSION_CFG_PROP = "xwiki.spacemanager.extension";
public final static String SPACEMANAGER_DEFAULT_EXTENSION = "org.xwiki.plugin.spacemanager.impl.SpaceManagerExtensionImpl";
/**
* The extension that defines specific functions for this space manager
*/
protected SpaceManagerExtension spaceManagerExtension;
/**
* Space manager constructor
* @param name
* @param className
* @param context
*/
public SpaceManagerImpl(String name, String className, XWikiContext context)
{
super(name, className, context);
}
/**
* Flushes cache
*/
public void flushCache() {
super.flushCache();
}
/**
*
* @param context Xwiki context
* @return Returns the Space Class as defined by the extension
* @throws XWikiException
*/
protected BaseClass getSpaceClass(XWikiContext context) throws XWikiException {
XWikiDocument doc;
XWiki xwiki = context.getWiki();
boolean needsUpdate = false;
try {
doc = xwiki.getDocument(getSpaceClassName(), context);
} catch (Exception e) {
doc = new XWikiDocument();
doc.setFullName(getSpaceClassName());
needsUpdate = true;
}
BaseClass bclass = doc.getxWikiClass();
bclass.setName(getSpaceClassName());
needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_DISPLAYTITLE, "Display Name", 64);
needsUpdate |= bclass.addTextAreaField(SpaceImpl.SPACE_DESCRIPTION, "Description", 45, 4);
needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_TYPE, "Group or plain space", 32);
needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_URLSHORTCUT, "URL Shortcut", 128);
needsUpdate |= bclass.addStaticListField(SpaceImpl.SPACE_POLICY, "Membership Policy", 1, false, "open=Open membership|closed=Closed membership","radio");
needsUpdate |= bclass.addStaticListField(SpaceImpl.SPACE_LANGUAGE, "Language", "eng=English|zho=Chinese|nld=Dutch|fra=French|deu=German|ita=Italian|jpn=Japanese|kor=Korean|por=Portuguese|rus=Russian|spa=Spanish");
String content = doc.getContent();
if ((content == null) || (content.equals(""))) {
needsUpdate = true;
doc.setContent("1 XWikiSpaceClass");
}
if (needsUpdate)
xwiki.saveDocument(doc, context);
return bclass;
}
/**
* Gets the space type from the space manager extension
* @return
*/
public String getSpaceTypeName() {
return getSpaceManagerExtension().getSpaceTypeName();
}
/**
* Gets the space type from the space manager extension
* @return
*/
public String getSpaceClassName() {
return getSpaceManagerExtension().getSpaceClassName();
}
/**
* Checks if this space manager has custom mapping
* @return
*/
public boolean hasCustomMapping() {
return getSpaceManagerExtension().hasCustomMapping();
}
/**
* Initializes the plugin on the main wiki
* @param context Xwiki context
*/
public void init(XWikiContext context) {
try {
getSpaceManagerExtension(context);
getSpaceManagerExtension().init(context);
SpaceManagers.addSpaceManager(this);
getSpaceClass(context);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initializes the plugin on a virtual wiki
* @param context Xwiki context
*/
public void virtualInit(XWikiContext context) {
try {
getSpaceClass(context);
getSpaceManagerExtension().virtualInit(context);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Gets the space plugin Api
* @param plugin The plugin interface
* @param context Xwiki context
* @return
*/
public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) {
return new SpaceManagerPluginApi((SpaceManager) plugin, context);
}
/**
* Loads the SpaceManagerExtension specified in the config file
* @return Returns the space manager extension
* @throws SpaceManagerException
*/
public SpaceManagerExtension getSpaceManagerExtension(XWikiContext context) throws SpaceManagerException
{
if (spaceManagerExtension==null) {
String extensionName = context.getWiki().Param(SPACEMANAGER_EXTENSION_CFG_PROP,SPACEMANAGER_DEFAULT_EXTENSION);
try {
if (extensionName!=null)
spaceManagerExtension = (SpaceManagerExtension) Class.forName(extensionName).newInstance();
} catch (Throwable e){
try{
spaceManagerExtension = (SpaceManagerExtension) Class.forName(SPACEMANAGER_DEFAULT_EXTENSION).newInstance();
} catch(Throwable e2){
}
}
}
if (spaceManagerExtension==null) {
spaceManagerExtension = new SpaceManagerExtensionImpl();
}
return spaceManagerExtension;
}
public SpaceManagerExtension getSpaceManagerExtension(){
return spaceManagerExtension;
}
/**
* Gets the name of the space manager
* @return
*/
public String getName()
{
return "spacemanager";
}
private Object notImplemented() throws SpaceManagerException {
throw new SpaceManagerException(SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_XWIKI_NOT_IMPLEMENTED, "not implemented");
}
/**
* Returns the wikiname of a space
* @param spaceTitle The name of the space
* @param unique make space title unique
* @param context XWiki Context
* @return
*/
public String getSpaceWikiName(String spaceTitle, boolean unique, XWikiContext context) {
return getSpaceManagerExtension().getSpaceWikiName(spaceTitle,unique, context);
}
/**
* Gets the name of the space document for a specific space
* @param spaceName The name of the space
* @return
*/
protected String getSpaceDocumentName(String spaceName) {
return spaceName + ".WebPreferences";
}
/**
* Creates a new space from scratch
* @param spaceTitle The name(display title) of the new space
* @param context The XWiki Context
* @return Returns the newly created space
* @throws SpaceManagerException
*/
public Space createSpace(String spaceTitle, XWikiContext context) throws SpaceManagerException {
// Init out space object by creating the space
// this will throw an exception when the space exists
Space newspace = newSpace(null, spaceTitle, true, context);
// Make sure we set the type
newspace.setType(getSpaceTypeName());
try {
newspace.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
// we need to add the creator as a member and as an admin
addAdmin(newspace.getSpaceName(), context.getUser(), context);
addMember(newspace.getSpaceName(), context.getUser(), context);
return newspace;
}
/**
* Creates a new space based on an already existing space.
* @param spaceTitle The name(display title) of the new space
* @param templateSpaceName The name of the space that will be cloned
* @param context The XWiki Context
* @return Returns the newly created space
* @throws SpaceManagerException
*/
public Space createSpaceFromTemplate(String spaceTitle, String templateSpaceName, XWikiContext context) throws SpaceManagerException {
// Init out space object by creating the space
// this will throw an exception when the space exists
Space newspace = newSpace(null, spaceTitle, false, context);
// Make sure this space does not already exist
if (!newspace.isNew())
throw new SpaceManagerException(SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_ALREADY_EXISTS, "Space already exists");
// Copy over template data over our current data
try {
context.getWiki().copyWikiWeb(templateSpaceName, context.getDatabase(), context.getDatabase(), null, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
// Make sure we set the type
newspace.setType(getSpaceTypeName());
newspace.setDisplayTitle(spaceTitle);
newspace.setCreator(context.getUser());
try {
newspace.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
// we need to add the creator as a member and as an admin
addAdmin(newspace.getSpaceName(), context.getUser(), context);
addMember(newspace.getSpaceName(), context.getUser(), context);
return newspace;
}
/**
*
*/
public Space createSpaceFromApplication(String spaceTitle, String applicationName, XWikiContext context) throws SpaceManagerException {
notImplemented();
return null;
}
/**
* Creates a new space based on the data send in the request (possibly from a form)
* @param context The XWiki Context
* @return Returns the newly created space
* @throws SpaceManagerException
*/
public Space createSpaceFromRequest(String templateSpaceName, XWikiContext context) throws SpaceManagerException {
// Init out space object by creating the space
// this will throw an exception when the space exists
String spaceTitle = context.getRequest().get(spaceManagerExtension.getSpaceClassName() + "_0_displayTitle");
if (spaceTitle==null) {
throw new SpaceManagerException(SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_TITLE_MISSING, "Space title is missing");
}
Space newspace = newSpace(null, spaceTitle, true, context);
newspace.updateSpaceFromRequest();
if (!newspace.validateSpaceData())
throw new SpaceManagerException(SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_DATA_INVALID, "Space data is not valid");
// Copy over template data over our current data
if(templateSpaceName != null){
try {
List list = context.getWiki().getStore().searchDocumentsNames("where doc.web='" + templateSpaceName + "'", context);
for (Iterator it = list.iterator(); it.hasNext();) {
String docname = (String) it.next();
XWikiDocument doc = context.getWiki().getDocument(docname, context);
context.getWiki().copyDocument(doc.getFullName(), newspace.getSpaceName() + "." + doc.getName(), context);
}
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
// Make sure we set the type
newspace.setType(getSpaceTypeName());
// we need to do it twice because data could have been overwritten by copyWikiWeb
newspace.updateSpaceFromRequest();
try {
newspace.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
// we need to add the creator as a member and as an admin
addAdmin(newspace.getSpaceName(), context.getUser(), context);
addMember(newspace.getSpaceName(), context.getUser(), context);
return newspace;
}
protected Space newSpace(String spaceName, String spaceTitle, boolean create, XWikiContext context) throws SpaceManagerException {
return new SpaceImpl(spaceName, spaceTitle, create, this, context );
}
/**
* Creates a new space based on the data send in the request (possibly from a form)
* @param context The XWiki Context
* @return Returns the newly created space
* @throws SpaceManagerException
*/
public Space createSpaceFromRequest(XWikiContext context) throws SpaceManagerException {
return createSpaceFromRequest(null, context);
}
/**
* Deletes a space
* @param spaceName The name of the space to be deleted
* @param deleteData Full delete (all the space data will be deleted)
* @param context The XWiki Context
* @throws SpaceManagerException
*/
public void deleteSpace(String spaceName, boolean deleteData, XWikiContext context) throws SpaceManagerException {
if (deleteData) {
// we are not implementing full delete yet
throw new SpaceManagerException(SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_XWIKI_NOT_IMPLEMENTED, "Not implemented");
}
Space space = getSpace(spaceName, context);
if (!space.isNew()) {
space.setType("deleted");
try {
space.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
}
/**
* Deletes a space without deleting the data
* @param spaceName The name of the space to be deleted
* @param context The XWiki Context
* @throws SpaceManagerException
*/
public void deleteSpace(String spaceName, XWikiContext context) throws SpaceManagerException {
deleteSpace(spaceName, false, context);
}
/**
* Restores a space that hasn't been fully deleted
* @param spaceName The name of the space to be restored
* @param context The XWiki Context
* @throws SpaceManagerException
*/
public void undeleteSpace(String spaceName, XWikiContext context) throws SpaceManagerException {
Space space = getSpace(spaceName, context);
if (space.isDeleted()) {
space.setType(getSpaceTypeName());
try {
space.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
}
/**
* Returns the space with the spaceName
* @param spaceName The name of the space to be deleted
* @param context The XWiki Context
* @throws SpaceManagerException
*/
public Space getSpace(String spaceName, XWikiContext context) throws SpaceManagerException {
// Init the space object but do not create anything if it does not exist
return newSpace(spaceName, spaceName, false, context);
}
/**
* Returns a list of nb spaces starting at start
* @param nb Number of spaces to be returned
* @param start Index at which we will start the search
* @param context The XWiki Context
* @return list of Space objects
* @throws SpaceManagerException
*/
public List getSpaces(int nb, int start, XWikiContext context) throws SpaceManagerException {
List spaceNames = getSpaceNames(nb, start, context);
return getSpaceObjects(spaceNames, context);
}
/**
* Returns a list of nb space names starting at start
* @param context The XWiki Context
* @return list of Space objects
* @throws SpaceManagerException
*/
protected List getSpaceObjects(List spaceNames, XWikiContext context) throws SpaceManagerException {
if (spaceNames==null)
return null;
List spaceList = new ArrayList();
for (int i=0;i<spaceNames.size();i++) {
String spaceName = (String) spaceNames.get(i);
Space space = getSpace(spaceName, context);
spaceList.add(space);
}
return spaceList;
}
/**
* Gets the names of nb spaces starting at start
* @param nb Number of spaces to be returned
* @param start Index at which we will start the search
* @param context The XWiki Context
* @return list of Strings (space names)
* @throws SpaceManagerException
*/
public List getSpaceNames(int nb, int start, XWikiContext context) throws SpaceManagerException {
String type = getSpaceTypeName();
String className = getSpaceClassName();
String sql;
if (hasCustomMapping())
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, " + className + " as space where doc.fullName = obj.name and obj.className='"
+ className + "' and obj.id = space.id and space.type='" + type + "'";
else
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty typeprop where doc.fullName=obj.name and obj.className = '"
+ className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'";
List spaceList = null;
try {
spaceList = context.getWiki().getStore().search(sql, nb, start, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
return spaceList;
}
/**
* Performs a hql search and returns the matching Space objects
* @param fromsql
*@param wherehql
* @param nb Number of objects to be returned
* @param start Index at which we will start the search
* @param context The XWiki Context @return list of Space objects
* @throws SpaceManagerException
*/
public List searchSpaces(String fromsql, String wherehql, int nb, int start, XWikiContext context) throws SpaceManagerException {
List spaceNames = searchSpaceNames(fromsql, wherehql, nb, start, context);
return getSpaceObjects(spaceNames, context);
}
/**
* Performs a hql search and returns the matching space names
* @param fromsql
*@param wheresql
* @param nb Number of objects to be returned
* @param start Index at which we will start the search
* @param context The XWiki Context @return list of Strings (space names)
* @throws SpaceManagerException
*/
public List searchSpaceNames(String fromsql, String wheresql, int nb, int start, XWikiContext context) throws SpaceManagerException {
String type = getSpaceTypeName();
String className = getSpaceClassName();
String sql;
if (hasCustomMapping())
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, " + className + " as space" + fromsql + " where doc.fullName = obj.name and obj.className='"
+ className + "' and obj.id = space.id and space.type='" + type + "'" + wheresql;
else
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as typeprop" + fromsql + " where doc.fullName=obj.name and obj.className = '"
+ className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'" + wheresql;
List spaceList = null;
try {
spaceList = context.getWiki().getStore().search(sql, nb, start, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
return spaceList;
}
/**
* Gets a list of spaces in which a specific user has a specific role
* @param userName The username of the targeted user
* @param role The role which the user must have
* @param context The XWiki Context
* @return list of Space objects
* @throws SpaceManagerException
*/
public List getSpaces(String userName, String role, XWikiContext context) throws SpaceManagerException {
List spaceNames = getSpaceNames(userName, role, context);
return getSpaceObjects(spaceNames, context);
}
/**
* Gets a list of spaces names in which a specific user has a specific role
* @param userName The username of the targeted user
* @param role The role which the user must have
* @param context The XWiki Context
* @return list of Strings (space names)
* @throws SpaceManagerException
*/
public List getSpaceNames(String userName, String role, XWikiContext context) throws SpaceManagerException {
String sql;
if (role==null)
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as memberprop where doc.name='MemberGroup' and doc.fullName=obj.name and obj.className = 'XWiki.XWikiGroups'"
+ " and obj.id=memberprop.id.id and memberprop.id.name='member' and memberprop.value='" + userName + "'";
else {
String roleGroupName = getRoleGroupName("", role).substring(1);
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as memberprop where doc.name='" + roleGroupName + "' and doc.fullName=obj.name and obj.className = 'XWiki.XWikiGroups'"
+ " and obj.id=memberprop.id.id and memberprop.id.name='member' and memberprop.value='" + userName + "'";
}
List spaceList = null;
try {
spaceList = context.getWiki().getStore().search(sql, 0, 0, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
return spaceList;
}
public void updateSpaceFromRequest(Space space, XWikiContext context) throws SpaceManagerException {
space.updateSpaceFromRequest();
}
public boolean validateSpaceData(Space space, XWikiContext context) throws SpaceManagerException {
return space.validateSpaceData();
}
/**
* Saves a space
* @param space Name of the space to be saved
* @throws SpaceManagerException
*/
public void saveSpace(Space space, XWikiContext context) throws SpaceManagerException {
try {
space.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public void addAdmin(String spaceName, String username, XWikiContext context) throws SpaceManagerException {
try {
addUserToGroup(username, getAdminGroupName(spaceName), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public void addAdmins(String spaceName, List usernames, XWikiContext context) throws SpaceManagerException {
for(int i=0;i<usernames.size();i++) {
addAdmin(spaceName, (String) usernames.get(i), context);
}
}
public Collection getAdmins(String spaceName, XWikiContext context) throws SpaceManagerException {
try {
return getGroupService(context).getAllMembersNamesForGroup(getAdminGroupName(spaceName), 0, 0, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public void addUserToRole(String spaceName, String username, String role, XWikiContext context) throws SpaceManagerException {
try {
addUserToGroup(username, getRoleGroupName(spaceName, role), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public void addUsersToRole(String spaceName, List usernames, String role, XWikiContext context) throws SpaceManagerException {
for(int i=0;i<usernames.size();i++) {
addUserToRole(spaceName, (String) usernames.get(i), role, context);
}
}
public Collection getUsersForRole(String spaceName, String role, XWikiContext context) throws SpaceManagerException {
try {
return getGroupService(context).getAllMembersNamesForGroup(getMemberGroupName(spaceName), 0, 0, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public boolean isMember(String spaceName, String username, XWikiContext context) throws SpaceManagerException {
try {
return isMemberOfGroup(username, getMemberGroupName(spaceName), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public void addUserToRoles(String spaceName, String username, List roles, XWikiContext context) throws SpaceManagerException {
for(int i=0;i<roles.size();i++) {
addUserToRole(spaceName, username, (String) roles.get(i), context);
}
}
public void addUsersToRoles(String spaceName, List usernames, List roles, XWikiContext context) throws SpaceManagerException {
for(int i=0;i<usernames.size();i++) {
addUserToRoles(spaceName, (String) usernames.get(i), roles, context);
}
}
public void addMember(String spaceName, String username, XWikiContext context) throws SpaceManagerException {
try {
addUserToGroup(username, getMemberGroupName(spaceName), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
private boolean isMemberOfGroup(String username, String groupname, XWikiContext context) throws XWikiException {
Collection coll = context.getWiki().getGroupService(context).getAllGroupsNamesForMember(username, 0, 0, context);
Iterator it = coll.iterator();
while (it.hasNext()) {
if (groupname.equals((String) it.next()))
return true;
}
return false;
}
/**
* High speed user adding without resaving the whole groups doc
* @param username
* @param groupName
* @param context
* @throws XWikiException
*/
private void addUserToGroup(String username, String groupName, XWikiContext context) throws XWikiException
{
// don't add if he is already a member
if (isMemberOfGroup(username, groupName, context))
return;
XWiki xwiki = context.getWiki();
BaseClass groupClass = xwiki.getGroupClass(context);
XWikiDocument groupDoc = xwiki.getDocument(groupName, context);
BaseObject memberObject = (BaseObject) groupClass.newObject(context);
memberObject.setClassName(groupClass.getName());
memberObject.setName(groupDoc.getFullName());
memberObject.setStringValue("member", username);
groupDoc.addObject(groupClass.getName(), memberObject);
if (groupDoc.isNew()) {
xwiki.saveDocument(groupDoc, context.getMessageTool().get("core.comment.addedUserToGroup"),
context);
} else {
xwiki.getHibernateStore().saveXWikiObject(memberObject, context, true);
}
// we need to make sure we add the user to the group cache
xwiki.getGroupService(context).addUserToGroup(username, context.getDatabase(), groupName, context);
}
public void addMembers(String spaceName, List usernames, XWikiContext context) throws SpaceManagerException {
for(int i=0;i<usernames.size();i++) {
addMember(spaceName, (String) usernames.get(i), context);
}
}
public Collection getMembers(String spaceName, XWikiContext context) throws SpaceManagerException {
try {
return getGroupService(context).getAllMembersNamesForGroup(getMemberGroupName(spaceName), 0, 0, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public String getMemberGroupName(String spaceName) {
return getSpaceManagerExtension().getMemberGroupName(spaceName);
}
public String getAdminGroupName(String spaceName) {
return getSpaceManagerExtension().getAdminGroupName(spaceName);
}
public String getRoleGroupName(String spaceName, String role) {
return getSpaceManagerExtension().getRoleGroupName(spaceName, role);
}
protected XWikiGroupService getGroupService(XWikiContext context) throws XWikiException {
return context.getWiki().getGroupService(context);
}
public SpaceUserProfile getSpaceUserProfile(String spaceName, String username, XWikiContext context) throws SpaceManagerException {
return newUserSpaceProfile(username, spaceName, context);
}
public String getSpaceUserProfilePageName(String userName, String spaceName) {
return getSpaceManagerExtension().getSpaceUserProfilePageName(userName, spaceName);
}
protected SpaceUserProfile newUserSpaceProfile(String user, String space, XWikiContext context) throws SpaceManagerException {
try {
return new SpaceUserProfileImpl(user, space, this, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public List getLastModifiedDocuments(String spaceName, XWikiContext context, boolean recursive, int nb, int start) throws SpaceManagerException {
//notImplemented();
return null;
}
public Collection getRoles(String spaceName, XWikiContext context) throws SpaceManagerException {
notImplemented();
return null;
}
public List getLastModifiedDocuments(String spaceName, XWikiContext context) throws SpaceManagerException {
notImplemented();
return null;
}
public List searchDocuments(String spaceName, String hql, XWikiContext context) throws SpaceManagerException {
notImplemented();
return null;
}
public int countSpaces(XWikiContext context) throws SpaceManagerException {
String type = getSpaceTypeName();
String className = getSpaceClassName();
String sql;
if (hasCustomMapping())
sql = "select count(*) from XWikiDocument as doc, BaseObject as obj, " + className + " as space"
+ " where doc.fullName = obj.name and obj.className='" + className + "' and obj.id = space.id and space.type='" + type + "'";
else
sql = "select count(*) from XWikiDocument as doc, BaseObject as obj, StringProperty as typeprop"
+ " where doc.fullName=obj.name and obj.className = '" + className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'";
try {
List result = context.getWiki().search(sql, context);
Integer res = (Integer) result.get(0);
return res.intValue();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
}
| plugins/spacemanager/src/main/java/org/xwiki/plugin/spacemanager/impl/SpaceManagerImpl.java | /**
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* <p/>
* This is free software;you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation;either version2.1of
* the License,or(at your option)any later version.
* <p/>
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY;without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
* Lesser General Public License for more details.
* <p/>
* You should have received a copy of the GNU Lesser General Public
* License along with this software;if not,write to the Free
* Software Foundation,Inc.,51 Franklin St,Fifth Floor,Boston,MA
* 02110-1301 USA,or see the FSF site:http://www.fsf.org.
*/
package org.xwiki.plugin.spacemanager.impl;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.user.api.XWikiGroupService;
import com.xpn.xwiki.api.Api;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.plugin.XWikiDefaultPlugin;
import com.xpn.xwiki.plugin.XWikiPluginInterface;
import org.xwiki.plugin.spacemanager.api.*;
import org.xwiki.plugin.spacemanager.plugin.SpaceManagerPluginApi;
import java.util.*;
/**
* Manages spaces
*/
public class SpaceManagerImpl extends XWikiDefaultPlugin implements SpaceManager {
public final static String SPACEMANAGER_EXTENSION_CFG_PROP = "xwiki.spacemanager.extension";
public final static String SPACEMANAGER_DEFAULT_EXTENSION = "org.xwiki.plugin.spacemanager.impl.SpaceManagerExtensionImpl";
/**
* The extension that defines specific functions for this space manager
*/
protected SpaceManagerExtension spaceManagerExtension;
/**
* Space manager constructor
* @param name
* @param className
* @param context
*/
public SpaceManagerImpl(String name, String className, XWikiContext context)
{
super(name, className, context);
}
/**
* Flushes cache
*/
public void flushCache() {
super.flushCache();
}
/**
*
* @param context Xwiki context
* @return Returns the Space Class as defined by the extension
* @throws XWikiException
*/
protected BaseClass getSpaceClass(XWikiContext context) throws XWikiException {
XWikiDocument doc;
XWiki xwiki = context.getWiki();
boolean needsUpdate = false;
try {
doc = xwiki.getDocument(getSpaceClassName(), context);
} catch (Exception e) {
doc = new XWikiDocument();
doc.setFullName(getSpaceClassName());
needsUpdate = true;
}
BaseClass bclass = doc.getxWikiClass();
bclass.setName(getSpaceClassName());
needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_DISPLAYTITLE, "Display Name", 64);
needsUpdate |= bclass.addTextAreaField(SpaceImpl.SPACE_DESCRIPTION, "Description", 45, 4);
needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_TYPE, "Group or plain space", 32);
needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_URLSHORTCUT, "URL Shortcut", 128);
needsUpdate |= bclass.addStaticListField(SpaceImpl.SPACE_POLICY, "Membership Policy", 1, false, "open=Open membership|closed=Closed membership","radio");
needsUpdate |= bclass.addStaticListField(SpaceImpl.SPACE_LANGUAGE, "Language", "eng=English|zho=Chinese|nld=Dutch|fra=French|deu=German|ita=Italian|jpn=Japanese|kor=Korean|por=Portuguese|rus=Russian|spa=Spanish");
String content = doc.getContent();
if ((content == null) || (content.equals(""))) {
needsUpdate = true;
doc.setContent("1 XWikiSpaceClass");
}
if (needsUpdate)
xwiki.saveDocument(doc, context);
return bclass;
}
/**
* Gets the space type from the space manager extension
* @return
*/
public String getSpaceTypeName() {
return getSpaceManagerExtension().getSpaceTypeName();
}
/**
* Gets the space type from the space manager extension
* @return
*/
public String getSpaceClassName() {
return getSpaceManagerExtension().getSpaceClassName();
}
/**
* Checks if this space manager has custom mapping
* @return
*/
public boolean hasCustomMapping() {
return getSpaceManagerExtension().hasCustomMapping();
}
/**
* Initializes the plugin on the main wiki
* @param context Xwiki context
*/
public void init(XWikiContext context) {
try {
getSpaceManagerExtension(context);
getSpaceManagerExtension().init(context);
SpaceManagers.addSpaceManager(this);
getSpaceClass(context);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initializes the plugin on a virtual wiki
* @param context Xwiki context
*/
public void virtualInit(XWikiContext context) {
try {
getSpaceClass(context);
getSpaceManagerExtension().virtualInit(context);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Gets the space plugin Api
* @param plugin The plugin interface
* @param context Xwiki context
* @return
*/
public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) {
return new SpaceManagerPluginApi((SpaceManager) plugin, context);
}
/**
* Loads the SpaceManagerExtension specified in the config file
* @return Returns the space manager extension
* @throws SpaceManagerException
*/
public SpaceManagerExtension getSpaceManagerExtension(XWikiContext context) throws SpaceManagerException
{
if (spaceManagerExtension==null) {
String extensionName = context.getWiki().Param(SPACEMANAGER_EXTENSION_CFG_PROP,SPACEMANAGER_DEFAULT_EXTENSION);
try {
if (extensionName!=null)
spaceManagerExtension = (SpaceManagerExtension) Class.forName(extensionName).newInstance();
} catch (Throwable e){
try{
spaceManagerExtension = (SpaceManagerExtension) Class.forName(SPACEMANAGER_DEFAULT_EXTENSION).newInstance();
} catch(Throwable e2){
}
}
}
if (spaceManagerExtension==null) {
spaceManagerExtension = new SpaceManagerExtensionImpl();
}
return spaceManagerExtension;
}
public SpaceManagerExtension getSpaceManagerExtension(){
return spaceManagerExtension;
}
/**
* Gets the name of the space manager
* @return
*/
public String getName()
{
return "spacemanager";
}
private Object notImplemented() throws SpaceManagerException {
throw new SpaceManagerException(SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_XWIKI_NOT_IMPLEMENTED, "not implemented");
}
/**
* Returns the wikiname of a space
* @param spaceTitle The name of the space
* @param unique make space title unique
* @param context XWiki Context
* @return
*/
public String getSpaceWikiName(String spaceTitle, boolean unique, XWikiContext context) {
return getSpaceManagerExtension().getSpaceWikiName(spaceTitle,unique, context);
}
/**
* Gets the name of the space document for a specific space
* @param spaceName The name of the space
* @return
*/
protected String getSpaceDocumentName(String spaceName) {
return spaceName + ".WebPreferences";
}
/**
* Creates a new space from scratch
* @param spaceTitle The name(display title) of the new space
* @param context The XWiki Context
* @return Returns the newly created space
* @throws SpaceManagerException
*/
public Space createSpace(String spaceTitle, XWikiContext context) throws SpaceManagerException {
// Init out space object by creating the space
// this will throw an exception when the space exists
Space newspace = newSpace(null, spaceTitle, true, context);
// Make sure we set the type
newspace.setType(getSpaceTypeName());
try {
newspace.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
// we need to add the creator as a member and as an admin
addAdmin(newspace.getSpaceName(), context.getUser(), context);
addMember(newspace.getSpaceName(), context.getUser(), context);
return newspace;
}
/**
* Creates a new space based on an already existing space.
* @param spaceTitle The name(display title) of the new space
* @param templateSpaceName The name of the space that will be cloned
* @param context The XWiki Context
* @return Returns the newly created space
* @throws SpaceManagerException
*/
public Space createSpaceFromTemplate(String spaceTitle, String templateSpaceName, XWikiContext context) throws SpaceManagerException {
// Init out space object by creating the space
// this will throw an exception when the space exists
Space newspace = newSpace(null, spaceTitle, false, context);
// Make sure this space does not already exist
if (!newspace.isNew())
throw new SpaceManagerException(SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_ALREADY_EXISTS, "Space already exists");
// Copy over template data over our current data
try {
context.getWiki().copyWikiWeb(templateSpaceName, context.getDatabase(), context.getDatabase(), null, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
// Make sure we set the type
newspace.setType(getSpaceTypeName());
newspace.setDisplayTitle(spaceTitle);
newspace.setCreator(context.getUser());
try {
newspace.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
// we need to add the creator as a member and as an admin
addAdmin(newspace.getSpaceName(), context.getUser(), context);
addMember(newspace.getSpaceName(), context.getUser(), context);
return newspace;
}
/**
*
*/
public Space createSpaceFromApplication(String spaceTitle, String applicationName, XWikiContext context) throws SpaceManagerException {
notImplemented();
return null;
}
/**
* Creates a new space based on the data send in the request (possibly from a form)
* @param context The XWiki Context
* @return Returns the newly created space
* @throws SpaceManagerException
*/
public Space createSpaceFromRequest(String templateSpaceName, XWikiContext context) throws SpaceManagerException {
// Init out space object by creating the space
// this will throw an exception when the space exists
String spaceTitle = context.getRequest().get(spaceManagerExtension.getSpaceClassName() + "_0_displayTitle");
if (spaceTitle==null) {
throw new SpaceManagerException(SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_TITLE_MISSING, "Space title is missing");
}
Space newspace = newSpace(null, spaceTitle, true, context);
newspace.updateSpaceFromRequest();
if (!newspace.validateSpaceData())
throw new SpaceManagerException(SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_DATA_INVALID, "Space data is not valid");
// Copy over template data over our current data
if(templateSpaceName != null){
try {
List list = context.getWiki().getStore().searchDocumentsNames("where doc.web='" + templateSpaceName + "'", context);
for (Iterator it = list.iterator(); it.hasNext();) {
String docname = (String) it.next();
XWikiDocument doc = context.getWiki().getDocument(docname, context);
context.getWiki().copyDocument(doc.getFullName(), newspace.getSpaceName() + "." + doc.getName(), context);
}
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
// Make sure we set the type
newspace.setType(getSpaceTypeName());
// we need to do it twice because data could have been overwritten by copyWikiWeb
newspace.updateSpaceFromRequest();
try {
newspace.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
// we need to add the creator as a member and as an admin
addAdmin(newspace.getSpaceName(), context.getUser(), context);
addMember(newspace.getSpaceName(), context.getUser(), context);
return newspace;
}
protected Space newSpace(String spaceName, String spaceTitle, boolean create, XWikiContext context) throws SpaceManagerException {
return new SpaceImpl(spaceName, spaceTitle, create, this, context );
}
/**
* Creates a new space based on the data send in the request (possibly from a form)
* @param context The XWiki Context
* @return Returns the newly created space
* @throws SpaceManagerException
*/
public Space createSpaceFromRequest(XWikiContext context) throws SpaceManagerException {
return createSpaceFromRequest(null, context);
}
/**
* Deletes a space
* @param spaceName The name of the space to be deleted
* @param deleteData Full delete (all the space data will be deleted)
* @param context The XWiki Context
* @throws SpaceManagerException
*/
public void deleteSpace(String spaceName, boolean deleteData, XWikiContext context) throws SpaceManagerException {
if (deleteData) {
// we are not implementing full delete yet
throw new SpaceManagerException(SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_XWIKI_NOT_IMPLEMENTED, "Not implemented");
}
Space space = getSpace(spaceName, context);
if (!space.isNew()) {
space.setType("deleted");
try {
space.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
}
/**
* Deletes a space without deleting the data
* @param spaceName The name of the space to be deleted
* @param context The XWiki Context
* @throws SpaceManagerException
*/
public void deleteSpace(String spaceName, XWikiContext context) throws SpaceManagerException {
deleteSpace(spaceName, false, context);
}
/**
* Restores a space that hasn't been fully deleted
* @param spaceName The name of the space to be restored
* @param context The XWiki Context
* @throws SpaceManagerException
*/
public void undeleteSpace(String spaceName, XWikiContext context) throws SpaceManagerException {
Space space = getSpace(spaceName, context);
if (space.isDeleted()) {
space.setType(getSpaceTypeName());
try {
space.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
}
/**
* Returns the space with the spaceName
* @param spaceName The name of the space to be deleted
* @param context The XWiki Context
* @throws SpaceManagerException
*/
public Space getSpace(String spaceName, XWikiContext context) throws SpaceManagerException {
// Init the space object but do not create anything if it does not exist
return newSpace(spaceName, spaceName, false, context);
}
/**
* Returns a list of nb spaces starting at start
* @param nb Number of spaces to be returned
* @param start Index at which we will start the search
* @param context The XWiki Context
* @return list of Space objects
* @throws SpaceManagerException
*/
public List getSpaces(int nb, int start, XWikiContext context) throws SpaceManagerException {
List spaceNames = getSpaceNames(nb, start, context);
return getSpaceObjects(spaceNames, context);
}
/**
* Returns a list of nb space names starting at start
* @param context The XWiki Context
* @return list of Space objects
* @throws SpaceManagerException
*/
protected List getSpaceObjects(List spaceNames, XWikiContext context) throws SpaceManagerException {
if (spaceNames==null)
return null;
List spaceList = new ArrayList();
for (int i=0;i<spaceNames.size();i++) {
String spaceName = (String) spaceNames.get(i);
Space space = getSpace(spaceName, context);
spaceList.add(space);
}
return spaceList;
}
/**
* Gets the names of nb spaces starting at start
* @param nb Number of spaces to be returned
* @param start Index at which we will start the search
* @param context The XWiki Context
* @return list of Strings (space names)
* @throws SpaceManagerException
*/
public List getSpaceNames(int nb, int start, XWikiContext context) throws SpaceManagerException {
String type = getSpaceTypeName();
String className = getSpaceClassName();
String sql;
if (hasCustomMapping())
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, " + className + " as space where doc.fullName = obj.name and obj.className='"
+ className + "' and obj.id = space.id and space.type='" + type + "'";
else
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty typeprop where doc.fullName=obj.name and obj.className = '"
+ className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'";
List spaceList = null;
try {
spaceList = context.getWiki().getStore().search(sql, nb, start, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
return spaceList;
}
/**
* Performs a hql search and returns the matching Space objects
* @param fromsql
*@param wherehql
* @param nb Number of objects to be returned
* @param start Index at which we will start the search
* @param context The XWiki Context @return list of Space objects
* @throws SpaceManagerException
*/
public List searchSpaces(String fromsql, String wherehql, int nb, int start, XWikiContext context) throws SpaceManagerException {
List spaceNames = searchSpaceNames(fromsql, wherehql, nb, start, context);
return getSpaceObjects(spaceNames, context);
}
/**
* Performs a hql search and returns the matching space names
* @param fromsql
*@param wheresql
* @param nb Number of objects to be returned
* @param start Index at which we will start the search
* @param context The XWiki Context @return list of Strings (space names)
* @throws SpaceManagerException
*/
public List searchSpaceNames(String fromsql, String wheresql, int nb, int start, XWikiContext context) throws SpaceManagerException {
String type = getSpaceTypeName();
String className = getSpaceClassName();
String sql;
if (hasCustomMapping())
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, " + className + " as space" + fromsql + " where doc.fullName = obj.name and obj.className='"
+ className + "' and obj.id = space.id and space.type='" + type + "'" + wheresql;
else
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as typeprop" + fromsql + " where doc.fullName=obj.name and obj.className = '"
+ className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'" + wheresql;
List spaceList = null;
try {
spaceList = context.getWiki().getStore().search(sql, nb, start, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
return spaceList;
}
/**
* Gets a list of spaces in which a specific user has a specific role
* @param userName The username of the targeted user
* @param role The role which the user must have
* @param context The XWiki Context
* @return list of Space objects
* @throws SpaceManagerException
*/
public List getSpaces(String userName, String role, XWikiContext context) throws SpaceManagerException {
List spaceNames = getSpaceNames(userName, role, context);
return getSpaceObjects(spaceNames, context);
}
/**
* Gets a list of spaces names in which a specific user has a specific role
* @param userName The username of the targeted user
* @param role The role which the user must have
* @param context The XWiki Context
* @return list of Strings (space names)
* @throws SpaceManagerException
*/
public List getSpaceNames(String userName, String role, XWikiContext context) throws SpaceManagerException {
String sql;
if (role==null)
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as memberprop where doc.name='MemberGroup' and doc.fullName=obj.name and obj.className = 'XWiki.XWikiGroups'"
+ " and obj.id=memberprop.id.id and memberprop.id.name='member' and memberprop.value='" + userName + "'";
else {
String roleGroupName = getRoleGroupName("", role).substring(1);
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as memberprop where doc.name='" + roleGroupName + "' and doc.fullName=obj.name and obj.className = 'XWiki.XWikiGroups'"
+ " and obj.id=memberprop.id.id and memberprop.id.name='member' and memberprop.value='" + userName + "'";
}
List spaceList = null;
try {
spaceList = context.getWiki().getStore().search(sql, 0, 0, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
return spaceList;
}
public void updateSpaceFromRequest(Space space, XWikiContext context) throws SpaceManagerException {
space.updateSpaceFromRequest();
}
public boolean validateSpaceData(Space space, XWikiContext context) throws SpaceManagerException {
return space.validateSpaceData();
}
/**
* Saves a space
* @param space Name of the space to be saved
* @throws SpaceManagerException
*/
public void saveSpace(Space space, XWikiContext context) throws SpaceManagerException {
try {
space.save();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public void addAdmin(String spaceName, String username, XWikiContext context) throws SpaceManagerException {
try {
addUserToGroup(username, getAdminGroupName(spaceName), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public void addAdmins(String spaceName, List usernames, XWikiContext context) throws SpaceManagerException {
for(int i=0;i<usernames.size();i++) {
addAdmin(spaceName, (String) usernames.get(i), context);
}
}
public Collection getAdmins(String spaceName, XWikiContext context) throws SpaceManagerException {
try {
return getGroupService(context).getAllMembersNamesForGroup(getAdminGroupName(spaceName), 0, 0, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public void addUserToRole(String spaceName, String username, String role, XWikiContext context) throws SpaceManagerException {
try {
addUserToGroup(username, getRoleGroupName(spaceName, role), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public void addUsersToRole(String spaceName, List usernames, String role, XWikiContext context) throws SpaceManagerException {
for(int i=0;i<usernames.size();i++) {
addUserToRole(spaceName, (String) usernames.get(i), role, context);
}
}
public Collection getUsersForRole(String spaceName, String role, XWikiContext context) throws SpaceManagerException {
try {
return getGroupService(context).getAllMembersNamesForGroup(getMemberGroupName(spaceName), 0, 0, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public boolean isMember(String spaceName, String username, XWikiContext context) throws SpaceManagerException {
try {
return isMemberOfGroup(username, getMemberGroupName(spaceName), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public void addUserToRoles(String spaceName, String username, List roles, XWikiContext context) throws SpaceManagerException {
for(int i=0;i<roles.size();i++) {
addUserToRole(spaceName, username, (String) roles.get(i), context);
}
}
public void addUsersToRoles(String spaceName, List usernames, List roles, XWikiContext context) throws SpaceManagerException {
for(int i=0;i<usernames.size();i++) {
addUserToRoles(spaceName, (String) usernames.get(i), roles, context);
}
}
public void addMember(String spaceName, String username, XWikiContext context) throws SpaceManagerException {
try {
addUserToGroup(username, getMemberGroupName(spaceName), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
private boolean isMemberOfGroup(String username, String groupname, XWikiContext context) throws XWikiException {
Collection coll = context.getWiki().getGroupService(context).getAllGroupsNamesForMember(username, 0, 0, context);
Iterator it = coll.iterator();
while (it.hasNext()) {
if (groupname.equals((String) it.next()))
return true;
}
return false;
}
/**
* High speed user adding without resaving the whole groups doc
* @param username
* @param groupName
* @param context
* @throws XWikiException
*/
private void addUserToGroup(String username, String groupName, XWikiContext context) throws XWikiException
{
// don't add if he is already a member
if (isMemberOfGroup(username, groupName, context))
return;
XWiki xwiki = context.getWiki();
BaseClass groupClass = xwiki.getGroupClass(context);
XWikiDocument groupDoc = xwiki.getDocument(groupName, context);
BaseObject memberObject = (BaseObject) groupClass.newObject(context);
memberObject.setClassName(groupClass.getName());
memberObject.setName(groupDoc.getFullName());
memberObject.setStringValue("member", username);
groupDoc.addObject(groupClass.getName(), memberObject);
if (groupDoc.isNew()) {
xwiki.saveDocument(groupDoc, context.getMessageTool().get("core.comment.addedUserToGroup"),
context);
} else {
xwiki.getHibernateStore().saveXWikiObject(memberObject, context, true);
}
}
public void addMembers(String spaceName, List usernames, XWikiContext context) throws SpaceManagerException {
for(int i=0;i<usernames.size();i++) {
addMember(spaceName, (String) usernames.get(i), context);
}
}
public Collection getMembers(String spaceName, XWikiContext context) throws SpaceManagerException {
try {
return getGroupService(context).getAllMembersNamesForGroup(getMemberGroupName(spaceName), 0, 0, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public String getMemberGroupName(String spaceName) {
return getSpaceManagerExtension().getMemberGroupName(spaceName);
}
public String getAdminGroupName(String spaceName) {
return getSpaceManagerExtension().getAdminGroupName(spaceName);
}
public String getRoleGroupName(String spaceName, String role) {
return getSpaceManagerExtension().getRoleGroupName(spaceName, role);
}
protected XWikiGroupService getGroupService(XWikiContext context) throws XWikiException {
return context.getWiki().getGroupService(context);
}
public SpaceUserProfile getSpaceUserProfile(String spaceName, String username, XWikiContext context) throws SpaceManagerException {
return newUserSpaceProfile(username, spaceName, context);
}
public String getSpaceUserProfilePageName(String userName, String spaceName) {
return getSpaceManagerExtension().getSpaceUserProfilePageName(userName, spaceName);
}
protected SpaceUserProfile newUserSpaceProfile(String user, String space, XWikiContext context) throws SpaceManagerException {
try {
return new SpaceUserProfileImpl(user, space, this, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public List getLastModifiedDocuments(String spaceName, XWikiContext context, boolean recursive, int nb, int start) throws SpaceManagerException {
//notImplemented();
return null;
}
public Collection getRoles(String spaceName, XWikiContext context) throws SpaceManagerException {
notImplemented();
return null;
}
public List getLastModifiedDocuments(String spaceName, XWikiContext context) throws SpaceManagerException {
notImplemented();
return null;
}
public List searchDocuments(String spaceName, String hql, XWikiContext context) throws SpaceManagerException {
notImplemented();
return null;
}
public int countSpaces(XWikiContext context) throws SpaceManagerException {
String type = getSpaceTypeName();
String className = getSpaceClassName();
String sql;
if (hasCustomMapping())
sql = "select count(*) from XWikiDocument as doc, BaseObject as obj, " + className + " as space"
+ " where doc.fullName = obj.name and obj.className='" + className + "' and obj.id = space.id and space.type='" + type + "'";
else
sql = "select count(*) from XWikiDocument as doc, BaseObject as obj, StringProperty as typeprop"
+ " where doc.fullName=obj.name and obj.className = '" + className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'";
try {
List result = context.getWiki().search(sql, context);
Integer res = (Integer) result.get(0);
return res.intValue();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
}
| CURRIKI-1179 Added call to add user to group cache when adding to group
svn@6461
| plugins/spacemanager/src/main/java/org/xwiki/plugin/spacemanager/impl/SpaceManagerImpl.java | CURRIKI-1179 Added call to add user to group cache when adding to group | <ide><path>lugins/spacemanager/src/main/java/org/xwiki/plugin/spacemanager/impl/SpaceManagerImpl.java
<ide> } else {
<ide> xwiki.getHibernateStore().saveXWikiObject(memberObject, context, true);
<ide> }
<add> // we need to make sure we add the user to the group cache
<add> xwiki.getGroupService(context).addUserToGroup(username, context.getDatabase(), groupName, context);
<ide> }
<ide>
<ide> |
|
JavaScript | bsd-3-clause | caca0d72d9890577d8062c4333703b725f19e57c | 0 | huntergdavis/Quick-Grapher | //var parsedEquation = undefined;
// I put the passed in values into separate arrays
// we should move them to objects
// if we need them after the initial parse
var variableMinHash = [];
var variableMaxHash = [];
var variableStepHash = [];
var variableLastHash = [];
var variableVisHash = [];
/* LoadTitleBarHash loads in passed-in title bar equation */
function loadTitleBarHash()
{
// Get location and search string. I think there is a faster way to do this.
var encodedBar = window.location.href,
equationStart = encodedBar.indexOf("?")+1,
encodedString = encodedBar.substring(equationStart,encodedBar.length),
addressBar = encodedString;
// Demunge
addressBar = addressBar.replace(/'%/g,"+");
// do we have multiple equations?
var multipleEquations = 0;
var equationEnd = addressBar.indexOf("="),
varsStart = equationEnd + 1,
varsStop = addressBar.indexOf("]"),
equationString = "",
equationValid = 0;
var loadRandom = false;
/* ensure we've got an equation to parse*/
if(equationStart < 1)
{
var exNumber;
if(loadRandom)
{
// let's load a random example instead
var exLen = examples.length;
var exRand = Math.floor(Math.random() * exLen);
if (exRand == 0)
{
exRand++;
}
exNumber = exRand;
}
else
{
exNumber = 5;
}
// Assume we have the address we need currently
var URL = window.location.href,
// Pull off any existing URI params
end = URL.indexOf("?");
if(end != -1)
{
URL = URL.substring(0,end);
}
newURL = URL + "?" + examples[exNumber].url;
window.location = newURL;
return;
}
/* assume the equation is the entire bar if no other hash material
* (for people hotlinking or apis to work later) */
if(equationEnd < 1)
{
equationEnd = addressBar.length;
}
/* Pull out our equation and set to be valid*/
var equationArrayString = addressBar.substring(0,equationEnd);
// parse out all the equations with a separator
var equationStringArray = returnArrayOfEquations(equationArrayString);
var esaLength = equationStringArray.length;
// allow each function to have its own name
var functionName = "Unnamed Function";
var equationStringSplit = equationStringArray[0].split("[");
var equationStringZero = equationStringSplit[0];
var equationString = equationStringZero;
if(equationStringSplit.length > 1)
{
functionName = equationStringSplit[1];
}
if (esaLength > 1)
{
multipleEquations = 1;
// the base equation div name
var eqNameBase = "#mainEquation";
var nameNameBase = "#equationName";
for(var i = 0;i<esaLength;i++)
{
var eqName;
var nameName;
if(i == 0)
{
eqName = eqNameBase;
nameName = nameNameBase;
}
else
{
eqName = eqNameBase + (i+1).toString();
nameName = nameNameBase + (i+1).toString();
}
// set each eq val and name to be correct
equationStringSplit = equationStringArray[i].split("[");
equationString = equationStringSplit[0];
if(equationStringSplit.length > 1)
{
functionName = equationStringSplit[1];
functionName = functionName.replace(/%20/g," ");
}
$(eqName).val(equationString);
$(nameName).val(functionName);
}
}
// replace plus signs in equation they are not usually supported
//equationString = equationString.replace(/%2B/g,"+");
equationValid = 1;
/* if we have variable hashes passed in, deal with them */
if(varsStart > 1)
{
var variableString = addressBar.substring(varsStart,varsStop),
minStart = 0,
minStop = variableString.indexOf("{"),
maxStart = minStop + 1,
maxStop = variableString.indexOf("}"),
stepStart = maxStop + 1,
stepStop = variableString.indexOf("["),
lastStart = stepStop + 1,
lastStop = variableString.indexOf(";"),
visStart = lastStop + 1,
visStop = variableString.indexOf("="),
nameStart = visStop + 1,
nameStop = variableString.length;
/* grab the minimum address*/
var parseBlock = variableString.substring(minStart,minStop);
parseAndAddToHash(parseBlock,":",variableMinHash);
/* grab the maximum address*/
parseBlock = variableString.substring(maxStart,maxStop);
parseAndAddToHash(parseBlock,":",variableMaxHash);
/* grab the step address*/
parseBlock = variableString.substring(stepStart,stepStop);
parseAndAddToHash(parseBlock,":",variableStepHash);
/* grab the last address*/
parseBlock = variableString.substring(lastStart,lastStop);
parseAndAddToHash(parseBlock,":",variableLastHash);
/* grab the visibility*/
parseBlock = variableString.substring(visStart,visStop);
parseAndAddToHash(parseBlock,":",variableVisHash);
/* grab the name*/
var tempName = variableString.substring(nameStart,nameStop);
tempName = tempName.replace(/%20/g," ");
}
if(equationValid > 0)
{
$("#mainEquation").val(equationStringZero);
$("#totalName").val(tempName);
if(typeof equationString != "undefined")
{
if(!multipleEquations)
{
// parse the equation
parsedEquation = QGSolver.parse(equationStringZero);
// Create sliders
createSliders(parsedEquation.variables());
// Solve equation
solveEquation();
}
else
{
parseMultipleEquations();
}
}
//$("#graphBtn").click();
}
}
function returnArrayOfEquations(equationArrayString)
{
// local array storage
var localArray = new Array();
// look for a split delimiter
if(equationArrayString.indexOf(";") > 0)
{
localArray = equationArrayString.split(";");
}
else
{
localArray.push(equationArrayString);
}
return localArray;
}
/* function parseAndAddToHash parses a string at delimeter and adds to a hash*/
function parseAndAddToHash(stringToParse,delimiter,hashToGrow)
{
/* should we continue parsing? */
var stillParsing = true;
/* local variable for splitting */
var parseBlock = stringToParse
/* loop through a string and split at indicies */
while(stillParsing)
{
/* break down the string and go to next delimiter*/
var nextDelimiter = parseBlock.indexOf(delimiter);
if(nextDelimiter > -1)
{
var hashValue = parseBlock.substring(0,nextDelimiter);
parseBlock = parseBlock.substring(nextDelimiter+1,parseBlock.length);
hashToGrow.push(hashValue);
}
else
{
stillParsing = false;
}
}
}
/* showValue changes the sibling span text of a slider to be its value and recalculates the equation*/
/* The overall formula based on the
change in this variable */
function showValue(sliderValue, sliderId)
{
var v = sliderId.substring(0,sliderId.indexOf("_")),
sliderLabel = $("#" + v + "_slider_value"),
step = parseFloat($("#" + v + "_step").val()),
dynamicUpdate = $("#dynamic_update");
sliderLabel.empty();
sliderLabel.append(parseInput(sliderValue,step));
var update = dynamicUpdate.is(":checked");
if(update)
{
solveEquation();
}
}
/* clearEqAndScreen clears out equation and all named elements */
function clearEqAndScreen()
{
// clear out equation and equation fxn name
$("#mainEquation").val("");
$("#equationName").val("Function");
// clear out all named elements
clearScreen();
}
/* clearScreen clears out all named elements */
function clearScreen()
{
var graphParent = $("#graph_container"),
sliderParent = $("#variables");
// Clear existing graph
graphParent.empty();
// Clear solved result display
$("#result").hide();
// Hide legend title
//$("#legendTitle").hide();
// Clear sliders
$("tr.variable").empty();
$("tr.variable").remove();
// Clear variables
$("#variable_list").empty();
// clear all global saved hashes
variableMinHash = [];
variableMaxHash = [];
variableStepHash = [];
variableLastHash = [];
variableVisHash = [];
}
function parseInput(input, step)
{
var val = parseFloat(input),
prec = val / step,
str = prec + "",
decimal,
rounded = Math.round(parseFloat(str)),
result = val;
if(step < 1)
{
str = rounded + "";
decimal = str.indexOf(".");
if(decimal != -1)
{
result = parseInt(str.substring(0,decimal)) * step;
}
else
{
result = parseInt(str) * step;
}
// Do final rounding check
str = result + "";
var len = str.length;
decimal = str.indexOf(".");
// We have a possible rounding error
if(decimal != -1 && len > decimal + 3)
{
// As long as we find zeros
var i;
for(i = len - 2; i > -1; i--)
{
if(str.charAt(i) != "0")
{
i++;
break;
}
}
// If we found a 0 chain at the end
if(i != len - 2)
{
result = parseFloat(str.substring(0,i));
}
}
}
return result;
}
function convertToPNG()
{
var parentElement = $("#subgraph_graph")[0];
if(typeof parentElement != "undefined")
{
var pngDataURL = parentElement.toDataURL("image/png");
window.open(pngDataURL);
// the below works in firefox, but you can't name it...
//var pngDataFile = pngDataURL.replace("image/png","image/octet-stream");
//document.location.href = pngDataFile;
}
else
{
alert("Please Graph Something First, Thanks!");
}
}
function updateSolution(name, equation, context, solution)
{
// document.getElementById("formula").innerText = equation.toString(context);
// document.getElementById("solution").innerText = solution;
// document.getElementById("function_name").innerText = $("#equationName").val();
var fxn = $("#fxn_" + name)[0],
inner = equation.toHTML(name,"p", context)
inner += " = " + solution;
fxn.innerHTML = inner;
//$("#" + name + "_solution").text(solution);
// var v, vars = equation.variables(),
// varLen = vars.length,
// varList = "";
// for(var i = 0; i < varLen; i++)
// {
// v = vars[i];
// varList += "<font id='" + v + "_param'>";
// varList += context[v];
// varList += "</font>";
// if(i != varLen - 1)
// {
// varList += ", ";
// }
// }
//document.getElementById("variable_list").innerHTML = varList;
//$("#result").show();
// Clear display property to fix stupid jQuery bug
//$("#result").css({display: ""});
}
function createContext(eq, vars)
{
var context = new Context(vars),
varLen = vars.length,
v, slider, val, step,
data = eq.fxnData.context;
for(var i = 0; i < varLen; i++)
{
v = vars[i];
//step = parseFloat($("#" + v + "_step").val());
//slider = $("#" + v + "_slider_value");//$("#" + v + "_slider");
//val = parseInput(slider.text(),step);
val = data[v];
context.set(v, val);
}
return context;
}
function solveEquation(equationElement, parsedEquation)
{
if(typeof parsedEquation != "undefined")
{
// Create context
var vars = parsedEquation.variables();
var context = createContext(equationElement, vars);
QGSolver.logDebugMessage("Context: " + context.toString());
// Solve
var solution = undefined;
try
{
solution = QGSolver.solve(parsedEquation, context.toObj());
}
catch(exception)
{
alert("Solve failed: " + exception);
}
// If we solved the equation, update page
if(typeof solution != "undefined")
{
// automatically generate a test case for any graph created
if(QGSolver.TESTGENERATION)
{
// add the name to the test case
var testCase = "\nTestExamples.push({name:\"";
testCase += $("#equationName").val() + "\",";
// add the function to the test case
testCase += "fxn : \"";
testCase += parsedEquation.toString() + "\",";
// add the curValContext to the test case
testCase += "curVarContext : [";
for(var j = 0;j<vars.length;j++)
{
testCase += $("#" + vars[j] + "_slider_value").text();
if(j < vars.length-1)
{
testCase += ",";
}
}
testCase += "],";
// add the parse Solution to the test case
testCase += "parseSol : \""
testCase += parsedEquation.toString(context.toObj()) + "\",";
// add the numerical Solution to the test case
testCase += "numSol : \"";
testCase += solution + "\"";
// close out the brackets
testCase += "});\n";
console.log(testCase);
}
// Update solution display
var name = equationElement.fxnData.name;
updateSolution(name, parsedEquation, context.toObj(), solution);
// Update graph
addFunctionToGraph(name, parsedEquation, context);
// Update row color
var color = $("#subgraph").color(name);
if(typeof color == "undefined")
{
color = "rgb(255,255,255)";
}
var cs = {};
cs["background-color"] = color;
$("#fxn_" + name).css(cs);
// update all graphs
//updateAllGraphs(parsedEquation, context);
}
// generate a hash
generateHashURL(parsedEquation.variables(),0);
}
}
function solveEqInMult()
{
if(typeof parsedEquation != "undefined")
{
// Create context
var vars = parsedEquation.variables();
var context = createContext(vars);
QGSolver.logDebugMessage("Context: " + context.toString());
// Solve
var solution = undefined;
try
{
solution = QGSolver.solve(context.toObj());
}
catch(exception)
{
alert("Solve failed: " + exception);
}
// If we solved the equation, update page
if(typeof solution != "undefined")
{
// Update solution display
updateSolution(parsedEquation, context.toObj(), solution);
// update all graphs
updateAllGraphs(parsedEquation, context);
}
// generate a hash
generateHashURL(parsedEquation.variables(),1);
}
}
/* clear the screen and parse the equation */
function clearAndParseEquation(equationElement, equation)
{
if(typeof equation != "undefined")
{
// clear the screen
clearScreen();
// parse the equation
parsedEquation = QGSolver.parse(equation);
// Create sliders
createSliders(parsedEquation.variables());
// Solve equation
solveEquation(equationElement, parsedEquation);
}
else
{
alert("Please enter a formula");
}
}
function clearAndParseMultipleEquations()
{
clearScreen();
parseMultipleEquations();
}
/* clear the screen then parse later */
function parseMultipleEquations()
{
// put all variables into single array
var allVariables = [];
// the base equation div name
var eqNameBase = "mainEquation";
// loop once over equations and grab all variables
for(var i = 1;i<6;i++)
{
var eqName;
if(i == 1)
{
eqName = eqNameBase;
}
else
{
eqName = eqNameBase + i.toString();
}
var singleEq = document.getElementById(eqName).value;
if(typeof singleEq != "undefined")
{
// parse the equation
parsedEquation = QGSolver.parse(singleEq);
// concat the variables
allVariables += parsedEquation.variables();
}
else
{
alert("Please enter a formula for " + eqName);
return;
}
}
// now that we've concatenated all variables...
// remove duplicates
var cleanVarArray = removeDuplicateVariables(allVariables);
// Create slidersFunction
createSliders(cleanVarArray);
// loop second time over equations and solve top down
for(var i = 1;i<6;i++)
{
var eqName;
if(i > 1)
{
eqName = eqNameBase + i.toString();
}
else
{
eqName = eqNameBase;
}
var singleEq = document.getElementById(eqName).value;
if(typeof singleEq != "undefined")
{
// parse the equation
parsedEquation = QGSolver.parse(singleEq);
// Solve equation
solveEqInMult();
}
}
}
function removeDuplicateVariables(dupArray)
{
var a = [];
var l = dupArray.length;
for(var i=0; i<l; i++) {
var found = 0;
for(var j=i+1; j<l; j++) {
// If this[i] is found later in the array
if (dupArray[i] == dupArray[j])
{
found = 1;
}
if(dupArray[i] == ",")
{
found = 1;
}
}
if(found == 0)
{
a.push(dupArray[i]);
}
}
return a;
}
function toggleDraw(toggleID)
{
solveEquation(this);
}
function updateMinimum(inputID)
{
// Retrieve variable name
var v = inputID.substring(0,inputID.indexOf("_")),
minField = $("#" + v + "_min"),
min = parseFloat(minField.val()),
maxField = $("#" + v + "_max"),
max = parseFloat(maxField.val()),
step = parseFloat($("#" + v + "_step").val()),
slider = $("#" + v + "_slider"),
curr = parseInput(slider.val(), step);
// Make sure the value is less than the maximum
if(min >= max)
{
min = max - 1;
minField.val(min);
}
// Make sure slider value is within new range
if(curr < min)
{
slider.val(min);
}
// Update slider values
slider[0].setAttribute("min", min);
// Resolve with new parameters
solve();
// if we changed the value we need to change the display
if(curr < min)
{
// update visually
showValue(min, inputID);
}
}
function updateMaximum(inputID)
{
// Retrieve variable name
var v = inputID.substring(0,inputID.indexOf("_")),
minField = $("#" + v + "_min"),
min = parseFloat(minField.val()),
maxField = $("#" + v + "_max"),
max = parseFloat(maxField.val()),
step = parseFloat($("#" + v + "_step").val()),
slider = $("#" + v + "_slider"),
curr = parseInput(slider.val(), step);
// Make sure the value is grater than the minimum
if(max <= min)
{
max = min + 1;
maxField.val(max);
}
// Make sure slider value is within new range
if(curr > max)
{
slider.val(max);
}
// Update slider values
slider[0].setAttribute("max", max);
// Resolve with new parameters
solve();
// if we changed the value we need to change the display
if(curr > max)
{
// update visually
showValue(max, inputID);
}
}
function updateStep(inputID)
{
// Retrieve variable name
var v = inputID.substring(0,inputID.indexOf("_")),
stepField = $("#" + v + "_step"),
slider = $("#" + v + "_slider");
// Update slider values
slider[0].setAttribute("step", parseFloat(stepField.val()));
// Resolve with new parameters
solve();
}
/* function generateHashURL generates a save hash url for the current equation, receives variables as argument*/
function generateHashURL(vars,multi)
{
// do NOT use window.location.href
// it FAILS to on redirection sites
//var URL = window.location.href,
var URL = "www.quickgrapher.com/index.html?";
// Pull off any existing URI params
end = URL.indexOf("?");
if(end != -1)
{
URL = URL.substring(0,end+1);
}
else
{
URL = URL + "?";
}
// add equation(s) to url
if(multi == 1)
{
// the base equation div name
var eqNameBase = "#mainEquation";
// the base name div name
var nameNameBase = "#equationName";
// loop once over equations and grab all variables
for(var i = 1;i<6;i++)
{
var eqName;
var nameName;
if(i == 1)
{
eqName = eqNameBase;
nameName = nameNameBase;
}
else
{
eqName = eqNameBase + i.toString();
nameName = nameNameBase + i.toString();
}
var localEquation = $(eqName).val();
if(typeof localEquation != "undefined")
{
URL += compressName(localEquation);
var localName = $(nameName).val();
localName = localName.replace(/\s/g,"%20");
if(typeof localName != "undefined")
{
URL += "[";
URL += localName;
}
URL += ";"
}
}
URL += "=";
}
else
{
var localEquation = $("#mainEquation").val();
if(typeof localEquation != "undefined")
{
URL += compressName(localEquation) + "=";
}
}
// variables to store hash values
var delimiter = ":",
minString = "",
maxString = "",
stepString = "",
lastString = "",
visString = "";
// Loop over variables
var name = "",
v, varLen = vars.length,
step, minVal, maxVal, last;
for(var i = 0; i < varLen; i++)
{
// Current variable
v = vars[i];
// get current variable's values
lastVal = parseFloat($("#" + v + "_slider").val()),
minVal = parseFloat($("#" + v + "_min").val()),
stepVal = parseFloat($("#" + v + "_step").val()),
maxVal = parseFloat($("#" + v + "_max").val());
var visVal;
if($("#" + v + "_graph_checkbox").is(":checked"))
{
visVal = 1;
}
else
{
visVal = 0;
}
// add current values to correct hash strings
minString = minString + minVal + delimiter;
maxString = maxString + maxVal + delimiter;
stepString = stepString + stepVal + delimiter;
lastString = lastString + lastVal + delimiter;
visString = visString + visVal + delimiter;
}
// replace spaces with %20 for web addresses
//var graphName = $("#totalName").val(),
//cleanGraphName = graphName.replace(/\s/g,"%20");
var cleanGraphName = "";
// clean up the plusses in URL for email clients
URL = URL.replace(/\+/g,"'%");
// add the fully constituted strings to URL
URL += minString + "{" + maxString + "}" + stepString + "[" + lastString + ";" + visString + "=" + cleanGraphName + "]";
// sneak the url into the instructions block
$("#instruct").attr("href", URL);
//updateShare(URL,graphName);
// sneak the url into social sharing services
$("#twitter_share").attr("st_url",URL);
$("#facebook_share").attr("st_url",URL);
$("#linkedin_share").attr("st_url",URL);
$("#gbuzz_share").attr("st_url",URL);
$("#email_share").attr("st_url",URL);
$("#sharethis_share").attr("st_url",URL);
$("#reddit_share").attr("st_url",URL);
$("#slashdot_share").attr("st_url",URL);
}
// update our share icon dynamically
function updateShare(url, title)
{
if(typeof SHARETHIS != "undefined")
{
var object = SHARETHIS.addEntry({
title: title,
url: url
});
object.attachButton(document.getElementById('blank_share'));
}
}
function createFunctionRow(name, fxn, parsed)
{
var v, vars = parsed.variables(),
varsLen = vars.length, ctx,
el, elParent = $("#function_list"),
row,
style;
// Create context
ctx = {};
for(var i = 0; i < varsLen; i++)
{
v = vars[i];
// Default value is 1
ctx[v] = 1;
}
// Row container
el = document.createElement("div");
el.id = "row_" + name;
el.className = "fxn_row";
el.fxnData = {
name: name,
fxn: fxn,
eq: parsed,
context: ctx
};
row = el;
el = $(el);
elParent.append(el);
elParent = el;
// Row table
el = document.createElement("table");
elParent.append(el);
elParent = $(el);
// Table row
el = document.createElement("tr");
elParent.append(el);
elParent = $(el);
// Icon column
el = document.createElement("td");
el.id = "icons_" + name;
el.className = "fxn_icons";
el = $(el);
elParent.append(el);
// Function column
el = document.createElement("td");
el.id = "fxn_" + name;
el.className = "fxn_highlight";
// Function HTML string (id prefix, element open tag, element close tag, context(optional) )
var inner = parsed.toHTML(name,"p")
inner += " = ";
el.innerHTML = inner;
el = $(el);
// modified later by graph
style = {
background: "rgb(255,255,255)"
};
el.css(style);
elParent.append(el);
// Remove column
el = document.createElement("td");
el.id = "remove_" + name;
el.className = "fxn_remove";
elParent.append(el);
el.innerHTML = "-";
return row;
}
function createSliders(vars)
{
var v, varsLen = vars.length,
sliderParent = $("#variables"),
el, inp, first,
sliderLabel, sliderValue,
graphCheck, graphCheckLabel;
for(var i = 0; i < varsLen; i++)
{
// each variable may have a stored min, max, step, last
var minValue = "";
var maxValue = "";
var stepValue = "";
var lastValue = "";
var visValue = 1;
// if not, use the default values
// default min value
if(!variableMinHash[i]) {
minValue = 0;
}
else
{
minValue = variableMinHash[i];
}
// default max value
if(typeof variableMaxHash[i] == "undefined") {
maxValue = 100;
}
else
{
maxValue = variableMaxHash[i];
}
// default step value
if(typeof variableStepHash[i] == "undefined") {
stepValue = 1;
}
else
{
stepValue = variableStepHash[i];
}
// default last value
if(typeof variableLastHash[i] == "undefined") {
lastValue = 1;
}
else
{
lastValue = variableLastHash[i];
}
if(typeof variableVisHash[i] == "undefined") {
visValue = 1;
}
else
{
visValue = variableVisHash[i];
}
v = vars[i];
// Create slider list item
first = document.createElement("tr");
first.setAttribute("class","variable");
sliderParent.append(first);
first = $(first);
// Create show checkbox
inp = document.createElement("input");
inp.setAttribute("class","show_select");
inp.id = v + "_graph_checkbox";
inp.setAttribute("type", "checkbox");
inp.setAttribute("onclick", "toggleInclude(this.id)");
inp.setAttribute("alt", "Draw " + v);
inp.setAttribute("title", "Draw " + v);
if(visValue == 1)
{
inp.setAttribute("checked", "checked");
}
// Variable name and value (added checkbox here)
el = document.createElement("td");
el.setAttribute("rowspan","2");
el = $(el);
el.append(inp);
inp = document.createElement("div");
inp.innerHTML = v + "<font style='font-size: 7pt; margin-left:2px;'> = </font>";
inp.id = v + "_variable_name";
el.append(inp);
inp = $(inp);
var cs = {
width:"100%",
// Need to load this from graph
color:"rgb" + "(0,0,0)",
display: "inline"
};
cs["font-size"] = "13pt";
inp.css(cs);
inp = document.createElement("div");
inp.setAttribute("class","variable_value");
inp.innerHTML = lastValue;
inp.id = v + "_slider_value";
el.append(inp);
inp = $(inp);
first.append(el);
el = document.createElement("td");
el.setAttribute("class","minimum");
el = $(el);
inp = document.createElement("input");
inp.setAttribute("id", v + "_min");
inp.setAttribute("type", "text");
inp.setAttribute("class", "range_input");
inp.setAttribute("size", "10");
inp.setAttribute("value", minValue);
inp.setAttribute("onchange", "updateMinimum(this.id)");
inp.setAttribute("alt", "Set minimum value for " + v);
inp.setAttribute("title", "Set minimum value for " + v);
el.append(inp);
first.append(el);
el = document.createElement("td");
el.setAttribute("class","step");
el = $(el);
inp = document.createElement("input");
inp.setAttribute("id", v + "_step");
inp.setAttribute("type", "text");
inp.setAttribute("class", "range_input");
inp.setAttribute("size", "10");
inp.setAttribute("value", stepValue);
inp.setAttribute("onchange", "updateStep(this.id)");
inp.setAttribute("alt", "Set step value for " + v);
inp.setAttribute("title", "Set step value for " + v);
el.append(inp);
first.append(el);
el = document.createElement("td");
el.setAttribute("class","maximum");
el = $(el);
inp = document.createElement("input");
inp.setAttribute("id", v + "_max");
inp.setAttribute("type", "text");
inp.setAttribute("class", "range_input");
inp.setAttribute("size", "10");
inp.setAttribute("value", maxValue);
inp.setAttribute("onchange", "updateMaximum(this.id)");
inp.setAttribute("alt", "Set maximum value for " + v);
inp.setAttribute("title", "Set maximum value for " + v);
el.append(inp);
first.append(el);
first = document.createElement("tr");
first.setAttribute("class","variable");
sliderParent.append(first);
first = $(first);
el = document.createElement("td");
el.setAttribute("class","range");
el.setAttribute("colspan","3");
el = $(el);
inp = document.createElement("input");
inp.id = v + "_slider";
inp.setAttribute("type", "range");
inp.setAttribute("min", minValue); //variableMinHash[i]);
inp.setAttribute("max", maxValue); //variableMaxHash[i]);
inp.setAttribute("step", stepValue); //variableStepHash[i]);
inp.setAttribute("value", lastValue);
inp.setAttribute("alt", "Adjust " + v);
inp.setAttribute("title", "Adjust " + v);
el.append(inp);
first.append(el);
inp = $(inp);
// Set initial value
inp.val(lastValue);
// Add change listener
inp[0].setAttribute("onchange", "showValue(this.value, this.id)");
}
// Verify slider compatibility with browser
//If range isnt supported
if(!Modernizr.inputtypes.range)
{
$('input[type=range]').each(function() {
var $input = $(this);
var $slider = $('<div id="' + $input.attr('id') + '" class="' + $input.attr('class') + '"></div>');
var step = $input.attr('step');
$input.after($slider).hide();
$slider.slider({
min: parseFloat($input.attr('min')),
max: parseFloat($input.attr('max')),
step: parseFloat($input.attr('step')),
value: parseFloat($input.attr('value')),
change: function(e, ui) {
showValue(ui.value, this.id);
}
});
});
}
}
function verifyGraph()
{
var graphID = "subgraph";
// Check if we already have a graph element
graph = $("#" + graphID);
if(graph.length == 0)
{
// Create graph element
var parentElement = $("#graph_container");
graph = document.createElement("div");
graph.id = graphID;
graph.style.position = "relative";
graph.style.width = "100%";
graph.style.height = "100%";
// Add to canvas
parentElement.append(graph);
// Register with Graph
var graphName = $("#equationName").val();
graph = $(graph);
var opts = {name: graphName};
opts['hue-increment'] = 45;
opts['hue-base'] = 22;
opts['value-base'] = 95;
opts['title'] = "What to put for title?"; //$("#equationName").val() + " ( " + vars.join(", ") +" )";
graph.graphify(opts).realHover({
hover: Graph.highlightNearest,
out: Graph.removeHighlight
});
// Set variable colors from plot
// var color;
// for(var i = 0; i < varLen; i++)
// {
// v = vars[i];
// color = $("#subgraph").color(v);
// if(typeof color == "undefined")
// {
// color = "rgb(0,0,0)";
// }
//
// $("#" + v + "_slider_value").css({color: color});
// }
}
}
function addFunctionToGraph(name, equation, context)
{
verifyGraph();
}
// updates graphs for all variables
function updateAllGraphs(equation, context)
{
var unifiedGraph = true,
graph,
// Retrieve variables
v, vars = equation.variables(),
varLen = vars.length;
if(unifiedGraph)
{
var graphID = "subgraph";
// Check if we already have a graph element
graph = $("#" + graphID);
if(graph.length == 0)
{
// Create graph element
var parentElement = $("#graph_container");
graph = document.createElement("div");
graph.id = graphID;
graph.style.position = "relative";
graph.style.width = "100%";
graph.style.height = "100%";
// Add to canvas
parentElement.append(graph);
// Register with Graph
var graphName = $("#equationName").val();
graph = $(graph);
var opts = {name: graphName};
opts['hue-increment'] = 45;
opts['hue-base'] = 22;
opts['value-base'] = 95;
opts['title'] = $("#equationName").val() + " ( " + vars.join(", ") +" )";
graph.graphify(opts)/*.attach_legend({
'legend-mode': false,
'legend-container': $("#legend"),
})*/.realHover({
hover: Graph.highlightNearest,
out: Graph.removeHighlight
});
// Set variable colors from plot
var color;
for(var i = 0; i < varLen; i++)
{
v = vars[i];
color = $("#subgraph").color(v);
if(typeof color == "undefined")
{
color = "rgb(0,0,0)";
}
$("#" + v + "_slider_value").css({color: color});
}
}
else
{
// Update graph title
graph.graph_option("title",$("#equationName").val() + " ( " + vars.join(", ") +" )");
}
}
/// Loop over variable
var name = "",
localContext = context.toObj(),
step, min, max;
for(var i = 0; i < varLen; i++)
{
// Current variable
v = vars[i];
// If we are supposed to draw this variable
if($("#" + v + "_graph_checkbox").is(":checked")
|| (typeof graph.color(v) == "undefined"))
{
// Adjust context
var fixedPt = localContext[v],
min = parseFloat($("#" + v + "_min").val()),
step = parseFloat($("#" + v + "_step").val()),
max = parseFloat($("#" + v + "_max").val()),
steps = ((max - min)/step) + 1;
// Substitute iterator
localContext[v] = new VariableIterator(min,step);
// Create graph
updateGraph(graphID, v, equation, localContext, steps);
// Replace values into local context for next loop step
localContext[v] = fixedPt;
}
if(!$("#" + v + "_graph_checkbox").is(":checked"))
{
// Make sure we have cleared the data for this variable
graph.hide_data(v);
}
}
}
// updates a single graph
function updateGraph(graphID, graphVariable, equation, context, steps)
{
// Retrieve reference to graph object
var graph = $("#" + graphID),
currVarValue, solution, data = [];
// Solve for the specified points
for(var i = 0; i < steps; i++)
{
currVarValue = context[graphVariable].value;
try
{
solution = equation.solve(context);
} catch(error)
{
solution = undefined;
QGSolver.logDebugMessage("Solve Error: [var: "+graphVariable+", value: "+currVarValue+"] " + error);
}
// Only add the point if it is a valid solution
if((typeof solution != "undefined") && isFinite(solution))
{
data.push([currVarValue, solution]);
}
// Step variable
context[graphVariable].step();
}
var lbl = "",
v, vars = equation.variables(),
varLen = vars.length;
lbl += graphVariable;
// Add plot for this variable (will overwrite existing ones)
var cs = {label : lbl};
cs['plot-type'] = 'line';
graph.plot(
graphVariable,
data,
cs
);
// Set variable colors from plot
var color = $("#subgraph").color(lbl);
if(typeof color == "undefined")
{
color = "rgb(0,0,0)";
}
//$("#" + lbl + "_variable_name").css({"color": color});
$("#" + lbl + "_slider_value").css({color: color});
cs = {color: color};
cs["font-weight"] = "bold";
$("#" + lbl + "_param").css(cs);
}
function toggle(exampleID)
{
var ex = $("#" + exampleID);
if(ex.is(":visible"))
{
ex.hide();
}
else
{
// Hide all others
$(".menu_item").hide();
// Show this one
ex.show();
}
return false;
}
function showExamples(exampleID)
{
var ex = $("#" + exampleID);
ex.show();
return false;
}
function hideExamples(exampleID)
{
var ex = $("#" + exampleID);
ex.hide();
return false;
}
function nextExamples()
{
var exLen = examples.length;
if((curr_page + 1) * 5 < exLen)
{
curr_page = curr_page + 1;
// Clear display
var list = $("#examplelist").empty();
var ex, example;
for(var i = (curr_page * 5); i < exLen && i < (curr_page + 1)*5; i++)
{
ex = examples[i];
createExampleLink(ex, list);
}
if( curr_page > 0 )
{
$("#prevExamples").show();
}
if( ((curr_page+1)*5) > exLen )
{
$("#nextExamples").hide();
}
}
return false;
}
function prevExamples()
{
var exLen = examples.length;
if(curr_page > 0)
{
curr_page = curr_page - 1;
// Clear display
var list = $("#examplelist").empty();
var ex, example;
for(var i = (curr_page * 5); i < exLen && i < (curr_page + 1)*5; i++)
{
ex = examples[i];
createExampleLink(ex, list);
}
$("#nextExamples").show();
if( curr_page == 0 )
{
$("#prevExamples").hide();
}
}
return false;
}
var examples,
functions,
curr_page;
function loadExamples()
{
// Load examples
examples = Examples;
// If there was nothing to load, just create empty array
if(typeof examples == "undefined")
{
examples = [];
}
if(examples.length > 0)
{
resetExamples();
}
}
function loadFunctions()
{
// Load functions
functions = Functions;
// If there was nothing to load, just create empty array
if(typeof functions == "undefined")
{
functions = {};
}
var list = $("#functionlist"), fxn,
col, row = 0, cols = 5,
fxnCount = 0, colSize = 1, colWidth,
emptied = false, margins;
// Count functions
for(var f in functions)
{
fxnCount++;
}
colSize = Math.ceil(fxnCount / cols);
var item = list,
w = item.width();
while(w == 0 || item.css("width").indexOf("%") != -1)
{
if(typeof item.parent() != "undefined")
{
item = item.parent();
w = item.width();
}
else
{
break;
}
}
colWidth = Math.floor(item.width() / cols);
if(colSize < 1)
{
colSize = 1;
}
// Create links
for(var fxnName in functions)
{
if(!emptied)
{
list.empty();
emptied = true;
}
margins = "margin-top: ";
col = Math.floor(row/colSize);
var top = 0;
if(row > 0 && row % colSize == 0)
{
top = -14 * colSize;
}
margins += top + "px;";
margins += " margin-left: " + (col * colWidth + 5) + "px;";
// If last row
var next = row + 1;
if(next == fxnCount && next % colSize != 0)
{
margins += " margin-bottom: " + (14 * (colSize - (next%colSize))) + "px;";
}
createFunctionLink(fxnName, margins, list);
row++;
}
}
function insertFunction(linkID)
{
var fxnName = linkID.substring(linkID.indexOf("_")+1,linkID.length),
fxn = functions[fxnName];
if(typeof fxn != "undefined")
{
var append = "",
eq = $("#mainEquation"),
// Add a space if none there
curr = eq.val(),
cursorOffset = 0;
if(curr.length > 0 && curr.charAt(curr.length - 1) != " ")
{
append += " ";
}
append += fxnName;
if(fxn.prefix)
{
append += "()";
cursorOffset = -2;
}
append += " ";
curr += append;
eq.val(curr);
// Focus
eq.focus();
// Set cursor
eq[0].selectionStart = curr.length + cursorOffset;
eq[0].selectionEnd = curr.length + cursorOffset;
}
}
function compressName(name)
{
// Remove spaces
var compressed = name.replace(/\s/g,"");
return compressed;
}
function createFunctionLink(fxnStr, style, parent)
{
var ex = document.createElement("li");
ex.setAttribute("id","fxn_" + fxnStr);
ex.setAttribute("onclick","insertFunction(this.id)");
ex.setAttribute("style",style);
// Text to add
ex.innerHTML = fxnStr;
parent.append(ex);
}
function createExampleLink(example, parent)
{
var ex = document.createElement("li"),
inner = "<a href='http://www.quickgrapher.com/index.html?";
inner += compressName(example.url);
inner += "'>"
inner += example.name;
inner += "</a>";
ex.innerHTML = inner;
ex.setAttribute("id","example_" + compressName(example.name));
parent.append(ex);
}
function resetExamples()
{
curr_page = 0;
// Clear display
var list = $("#examplelist");
list.empty();
// Display
var exLen = examples.length,
ex, example;
for(var i = (curr_page * 5); i < exLen && i < (curr_page + 1)*5; i++)
{
ex = examples[i];
createExampleLink(ex, list);
}
if( exLen > 5 )
{
$("#nextExamples").show();
}
}
function loadExample(exampleID)
{
var exampleName = exampleID.substring(8,exampleID.length),
ex, exLen = examples.length;
// Close examples list
var p = $("#" + exampleID).parent();
hideExamples(p.id());
// Load display
for(var i = 0; i < exLen; i++)
{
ex = examples[i];
if(compressName(ex.name) == exampleName)
{
$("#mainEquation").val(ex.fxn);
$("#graphBtn").click();
break;
}
}
return false;
}
function getViewportDimensions()
{
var dims = {};
// Compliant browsers use innerWidth
if (typeof window.innerWidth != 'undefined')
{
dims.width = window.innerWidth,
dims.height = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0)
{
dims.width = document.documentElement.clientWidth,
dims.height = document.documentElement.clientHeight
}
// For older versions of IE
else
{
dims.width = document.getElementsByTagName('body')[0].clientWidth,
dims.height = document.getElementsByTagName('body')[0].clientHeight
}
return dims;
}
var fullscreen_active = false,
// To prevent re-entrance issues if the person clicks link rapidly
toggling = false;
function resizeFullscreen()
{
// Calculate available width
var dims = getViewportDimensions(),
w = dims.width,
h = dims.height,
// Graph & equation get 75%
graphW = Math.floor(0.75 * w),
// Solution and variables get other 25%
resultsW = w - graphW - 5;
// Adjust for vertical screens
var vertical = false;
// Start adjusting graph compression
// Minimum width the variable bar can manage is 240px
if(resultsW < 250)
{
resultsW = 250;
graphW = w - resultsW - 5;
}
if(h > 1.05*w)
{
vertical = true;
}
// Fix styles
var style;
if(vertical)
{
$("#result").removeClass("result_fullscreen");
$("#solution_column").addClass("solution_column");
$("#solution_column").removeClass("solution_column_fullscreen");
$("#variables_column").addClass("variables_column_fullscreen_vert");
$("#variables_column").removeClass("variables_column");
$("#variables_column").removeClass("variables_column_fullscreen");
style = {
width : Math.floor(w - 300)
};
$("#variables_column").css(style);
style = {
width : Math.floor(w - 10),
height : Math.floor(0.65 * h)
};
$("#graph_container").css(style);
style = {width : w - 260};
$("#mainEquation").css(style);
// Remove background logo
style = {};
style["background-image"] = "";
$("#fullscreen_container").css(style);
}
else
{
$("#result").addClass("result_fullscreen");
$("#solution_column").removeClass("solution_column");
$("#solution_column").addClass("solution_column_fullscreen");
$("#variables_column").removeClass("variables_column");
$("#variables_column").removeClass("variables_column_fullscreen_vert");
$("#variables_column").addClass("variables_column_fullscreen");
style = {width : ""};
$("#mainEquation").css(style);
style = {width : graphW - 30};
$("#equation").css(style);
style = {
width : graphW,
height : h - 40
};
$("#graph_container").css(style);
style = {width : resultsW};
$("#result").css(style);
$("#solution_column").css(style);
$("#variables_column").css(style);
// Add background logo
style = {};
style["background-image"] = "url('images/logo_1.png')";
$("#fullscreen_container").css(style);
}
}
function toggleFullscreen()
{
if(!toggling)
{
toggling = true;
if(!fullscreen_active)
{
// Update toggle
fullscreen_active = true;
$("#fullscreen_toggle").text("X");
var style = {};
style["background-color"] = "rgb(255,0,0)";
style["color"] = "rgb(255,255,255)";
style["border"] = "0px";
$("#fullscreen_toggle").css(style);
// Hide normal elements
$("#container").hide();
$("#footer").hide();
$("#beta_box").hide();
// Move necessary elements to fullscreen block
var fsc = $("#fullscreen_container");
// -- Equation
fsc.append($("#equation"));
// -- Graph
fsc.append($("#graph_container"));
// -- Solutions & Variables
fsc.append($("#result"));
// -- Variables
// Calculate available width
var dims = getViewportDimensions(),
w = dims.width,
h = dims.height,
vertical = false,
// Graph & equation get 75%
graphW = Math.floor(0.75 * w),
// Solution and variables get other 25%
resultsW = w - graphW - 5;
if(h > 1.05*w)
{
vertical = true;
}
// Fix styles
style = {};
// Background style
if(vertical)
{
// Remove background logo
style["background-image"] = "";
$("#fullscreen_container").css(style);
}
else
{
// Add background logo
style["background-image"] = "url('images/logo_1.png')";
$("#fullscreen_container").css(style);
}
// Input style
style = {};
style["margin"] = "2px 0px 0px 30px";
$("#equation").css(style);
// Graph style
style = {};
style["margin"] = "5px 5px 5px 5px";
style["display"] = "inline";
$("#graph_container").css(style);
// Results and variables display
if(!vertical)
{
$("#result").addClass("result_fullscreen");
}
$("#mainEquation").removeClass("equation_input");
$("#mainEquation").addClass("equation_input_fullscreen");
if(!vertical)
{
$("#solution_column").removeClass("solution_column");
$("#solution_column").addClass("solution_column_fullscreen");
$("#variables_column").removeClass("variables_column");
$("#variables_column").addClass("variables_column_fullscreen");
}
resizeFullscreen();
// Show fullscreen block
$("#fullscreen_container").show();
// Fire resize handler
$("#subgraph").trigger("resize");
}
else
{
// Update toggle
fullscreen_active = false;
$("#fullscreen_toggle").text("Fullscreen");
var style = {};
style["background-color"] = "";
style["color"] = "";
style["border"] = "";
$("#fullscreen_toggle").css(style);
// Hide fullscreen block
$("#fullscreen_container").hide();
// Move elements to normal location
// -- Equation
$("#equation").insertAfter("#functions");
// -- Graph
$("#graph_container").insertAfter("#equation");
// -- Solution & variables
$("#result").insertAfter("#graph_break");
// // -- Variables
// Fix styles
style = {};
style["margin"] = "";
style["width"] = "";
$("#equation").css(style);
style = {};
style["margin"] = "";
style["width"] = "";
style["height"] = "";
style["display"] = "";
$("#graph_container").css(style);
// Fire resize handler
$("#subgraph").trigger("resize");
style = {};
style["width"] = "";
$("#result").removeClass("result_fullscreen");
$("#mainEquation").addClass("equation_input");
$("#mainEquation").removeClass("equation_input_fullscreen");
$("#result").css(style);
$("#solution_column").addClass("solution_column");
$("#solution_column").removeClass("solution_column_fullscreen");
$("#solution_column").css(style);
$("#variables_column").addClass("variables_column");
$("#variables_column").removeClass("variables_column_fullscreen");
$("#variables_column").removeClass("variables_column_fullscreen_vert");
$("#variables_column").css(style);
// Show normal elements
$("#container").show();
$("#footer").show();
$("#beta_box").show();
// Fire resize handler
$("#subgraph").trigger("resize");
}
toggling = false;
}
}
$(window).resize(function() {
if(fullscreen_active && !toggling)
{
toggling = true;
resizeFullscreen();
toggling = false;
}
});
/* From page */
function clearAndParse()
{
clearAndParseEquation(this, document.getElementById('mainEquation').value);
}
function clearAndParseMultiple()
{
clearAndParseMultipleEquations();
}
function solve()
{
solveEquation(this);
}
function solveMult()
{
solveEqInMult();
}
function toggleInclude(toggleID)
{
toggleDraw(toggleID);
}
function addFunction() {
var fxn = $('#mainEquation').val(),
name = $('#equationName').val();
// parse the equation
var parsed = QGSolver.parse(fxn);
// Create sliders
var row = createFunctionRow(name, fxn, parsed);
// Solve equation
solveEquation(row, parsed);
}
$(document).ready(function() {
// Turn on debug
//QGSolver.DEBUG = true;
QGSolver.DEBUG = false;
// enable random load
// Turn on Test Generation
QGSolver.TESTGENERATION = false;
// Load examples
loadExamples();
// Load functions
loadFunctions();
// Load From TitleBar
loadTitleBarHash();
// Add key listeners
$("#equationName").keyup(function(event){
if(event.keyCode == 13){
var eq = $("#mainEquation");
if(eq.val().length == 0)
{
eq.focus();
}
else
{
$("#graphBtn").click();
}
}
});
$("#mainEquation").keyup(function(event){
if(event.keyCode == 13){
var name = $("#equationName");
if(name.val().length == 0)
{
name.focus();
}
else
{
$("#graphBtn").click();
}
}
});
});
| js/plain/quick_graph.js | //var parsedEquation = undefined;
// I put the passed in values into separate arrays
// we should move them to objects
// if we need them after the initial parse
var variableMinHash = [];
var variableMaxHash = [];
var variableStepHash = [];
var variableLastHash = [];
var variableVisHash = [];
/* LoadTitleBarHash loads in passed-in title bar equation */
function loadTitleBarHash()
{
// Get location and search string. I think there is a faster way to do this.
var encodedBar = window.location.href,
equationStart = encodedBar.indexOf("?")+1,
encodedString = encodedBar.substring(equationStart,encodedBar.length),
addressBar = encodedString;
// Demunge
addressBar = addressBar.replace(/'%/g,"+");
// do we have multiple equations?
var multipleEquations = 0;
var equationEnd = addressBar.indexOf("="),
varsStart = equationEnd + 1,
varsStop = addressBar.indexOf("]"),
equationString = "",
equationValid = 0;
var loadRandom = false;
/* ensure we've got an equation to parse*/
if(equationStart < 1)
{
var exNumber;
if(loadRandom)
{
// let's load a random example instead
var exLen = examples.length;
var exRand = Math.floor(Math.random() * exLen);
if (exRand == 0)
{
exRand++;
}
exNumber = exRand;
}
else
{
exNumber = 5;
}
// Assume we have the address we need currently
var URL = window.location.href,
// Pull off any existing URI params
end = URL.indexOf("?");
if(end != -1)
{
URL = URL.substring(0,end);
}
newURL = URL + "?" + examples[exNumber].url;
window.location = newURL;
return;
}
/* assume the equation is the entire bar if no other hash material
* (for people hotlinking or apis to work later) */
if(equationEnd < 1)
{
equationEnd = addressBar.length;
}
/* Pull out our equation and set to be valid*/
var equationArrayString = addressBar.substring(0,equationEnd);
// parse out all the equations with a separator
var equationStringArray = returnArrayOfEquations(equationArrayString);
var esaLength = equationStringArray.length;
// allow each function to have its own name
var functionName = "Unnamed Function";
var equationStringSplit = equationStringArray[0].split("[");
var equationStringZero = equationStringSplit[0];
var equationString = equationStringZero;
if(equationStringSplit.length > 1)
{
functionName = equationStringSplit[1];
}
if (esaLength > 1)
{
multipleEquations = 1;
// the base equation div name
var eqNameBase = "#mainEquation";
var nameNameBase = "#equationName";
for(var i = 0;i<esaLength;i++)
{
var eqName;
var nameName;
if(i == 0)
{
eqName = eqNameBase;
nameName = nameNameBase;
}
else
{
eqName = eqNameBase + (i+1).toString();
nameName = nameNameBase + (i+1).toString();
}
// set each eq val and name to be correct
equationStringSplit = equationStringArray[i].split("[");
equationString = equationStringSplit[0];
if(equationStringSplit.length > 1)
{
functionName = equationStringSplit[1];
functionName = functionName.replace(/%20/g," ");
}
$(eqName).val(equationString);
$(nameName).val(functionName);
}
}
// replace plus signs in equation they are not usually supported
//equationString = equationString.replace(/%2B/g,"+");
equationValid = 1;
/* if we have variable hashes passed in, deal with them */
if(varsStart > 1)
{
var variableString = addressBar.substring(varsStart,varsStop),
minStart = 0,
minStop = variableString.indexOf("{"),
maxStart = minStop + 1,
maxStop = variableString.indexOf("}"),
stepStart = maxStop + 1,
stepStop = variableString.indexOf("["),
lastStart = stepStop + 1,
lastStop = variableString.indexOf(";"),
visStart = lastStop + 1,
visStop = variableString.indexOf("="),
nameStart = visStop + 1,
nameStop = variableString.length;
/* grab the minimum address*/
var parseBlock = variableString.substring(minStart,minStop);
parseAndAddToHash(parseBlock,":",variableMinHash);
/* grab the maximum address*/
parseBlock = variableString.substring(maxStart,maxStop);
parseAndAddToHash(parseBlock,":",variableMaxHash);
/* grab the step address*/
parseBlock = variableString.substring(stepStart,stepStop);
parseAndAddToHash(parseBlock,":",variableStepHash);
/* grab the last address*/
parseBlock = variableString.substring(lastStart,lastStop);
parseAndAddToHash(parseBlock,":",variableLastHash);
/* grab the visibility*/
parseBlock = variableString.substring(visStart,visStop);
parseAndAddToHash(parseBlock,":",variableVisHash);
/* grab the name*/
var tempName = variableString.substring(nameStart,nameStop);
tempName = tempName.replace(/%20/g," ");
}
if(equationValid > 0)
{
$("#mainEquation").val(equationStringZero);
$("#totalName").val(tempName);
if(typeof equationString != "undefined")
{
if(!multipleEquations)
{
// parse the equation
parsedEquation = QGSolver.parse(equationStringZero);
// Create sliders
createSliders(parsedEquation.variables());
// Solve equation
solveEquation();
}
else
{
parseMultipleEquations();
}
}
//$("#graphBtn").click();
}
}
function returnArrayOfEquations(equationArrayString)
{
// local array storage
var localArray = new Array();
// look for a split delimiter
if(equationArrayString.indexOf(";") > 0)
{
localArray = equationArrayString.split(";");
}
else
{
localArray.push(equationArrayString);
}
return localArray;
}
/* function parseAndAddToHash parses a string at delimeter and adds to a hash*/
function parseAndAddToHash(stringToParse,delimiter,hashToGrow)
{
/* should we continue parsing? */
var stillParsing = true;
/* local variable for splitting */
var parseBlock = stringToParse
/* loop through a string and split at indicies */
while(stillParsing)
{
/* break down the string and go to next delimiter*/
var nextDelimiter = parseBlock.indexOf(delimiter);
if(nextDelimiter > -1)
{
var hashValue = parseBlock.substring(0,nextDelimiter);
parseBlock = parseBlock.substring(nextDelimiter+1,parseBlock.length);
hashToGrow.push(hashValue);
}
else
{
stillParsing = false;
}
}
}
/* showValue changes the sibling span text of a slider to be its value and recalculates the equation*/
/* The overall formula based on the
change in this variable */
function showValue(sliderValue, sliderId)
{
var v = sliderId.substring(0,sliderId.indexOf("_")),
sliderLabel = $("#" + v + "_slider_value"),
step = parseFloat($("#" + v + "_step").val()),
dynamicUpdate = $("#dynamic_update");
sliderLabel.empty();
sliderLabel.append(parseInput(sliderValue,step));
var update = dynamicUpdate.is(":checked");
if(update)
{
solveEquation();
}
}
/* clearEqAndScreen clears out equation and all named elements */
function clearEqAndScreen()
{
// clear out equation and equation fxn name
$("#mainEquation").val("");
$("#equationName").val("Function");
// clear out all named elements
clearScreen();
}
/* clearScreen clears out all named elements */
function clearScreen()
{
var graphParent = $("#graph_container"),
sliderParent = $("#variables");
// Clear existing graph
graphParent.empty();
// Clear solved result display
$("#result").hide();
// Hide legend title
//$("#legendTitle").hide();
// Clear sliders
$("tr.variable").empty();
$("tr.variable").remove();
// Clear variables
$("#variable_list").empty();
// clear all global saved hashes
variableMinHash = [];
variableMaxHash = [];
variableStepHash = [];
variableLastHash = [];
variableVisHash = [];
}
function parseInput(input, step)
{
var val = parseFloat(input),
prec = val / step,
str = prec + "",
decimal,
rounded = Math.round(parseFloat(str)),
result = val;
if(step < 1)
{
str = rounded + "";
decimal = str.indexOf(".");
if(decimal != -1)
{
result = parseInt(str.substring(0,decimal)) * step;
}
else
{
result = parseInt(str) * step;
}
// Do final rounding check
str = result + "";
var len = str.length;
decimal = str.indexOf(".");
// We have a possible rounding error
if(decimal != -1 && len > decimal + 3)
{
// As long as we find zeros
var i;
for(i = len - 2; i > -1; i--)
{
if(str.charAt(i) != "0")
{
i++;
break;
}
}
// If we found a 0 chain at the end
if(i != len - 2)
{
result = parseFloat(str.substring(0,i));
}
}
}
return result;
}
function convertToPNG()
{
var parentElement = $("#subgraph_graph")[0];
if(typeof parentElement != "undefined")
{
var pngDataURL = parentElement.toDataURL("image/png");
window.open(pngDataURL);
// the below works in firefox, but you can't name it...
//var pngDataFile = pngDataURL.replace("image/png","image/octet-stream");
//document.location.href = pngDataFile;
}
else
{
alert("Please Graph Something First, Thanks!");
}
}
function updateSolution(name, equation, context, solution)
{
// document.getElementById("formula").innerText = equation.toString(context);
// document.getElementById("solution").innerText = solution;
// document.getElementById("function_name").innerText = $("#equationName").val();
var fxn = $("#fxn_" + name)[0],
inner = equation.toHTML(name,"p", context)
inner += " = " + solution;
fxn.innerHTML = inner;
//$("#" + name + "_solution").text(solution);
// var v, vars = equation.variables(),
// varLen = vars.length,
// varList = "";
// for(var i = 0; i < varLen; i++)
// {
// v = vars[i];
// varList += "<font id='" + v + "_param'>";
// varList += context[v];
// varList += "</font>";
// if(i != varLen - 1)
// {
// varList += ", ";
// }
// }
//document.getElementById("variable_list").innerHTML = varList;
//$("#result").show();
// Clear display property to fix stupid jQuery bug
//$("#result").css({display: ""});
}
function createContext(eq, vars)
{
var context = new Context(vars),
varLen = vars.length,
v, slider, val, step,
data = eq.fxnData.context;
for(var i = 0; i < varLen; i++)
{
v = vars[i];
//step = parseFloat($("#" + v + "_step").val());
//slider = $("#" + v + "_slider_value");//$("#" + v + "_slider");
//val = parseInput(slider.text(),step);
val = data[v];
context.set(v, val);
}
return context;
}
function solveEquation(equationElement, parsedEquation)
{
if(typeof parsedEquation != "undefined")
{
// Create context
var vars = parsedEquation.variables();
var context = createContext(equationElement, vars);
QGSolver.logDebugMessage("Context: " + context.toString());
// Solve
var solution = undefined;
try
{
solution = QGSolver.solve(parsedEquation, context.toObj());
}
catch(exception)
{
alert("Solve failed: " + exception);
}
// If we solved the equation, update page
if(typeof solution != "undefined")
{
// automatically generate a test case for any graph created
if(QGSolver.TESTGENERATION)
{
// add the name to the test case
var testCase = "\nTestExamples.push({name:\"";
testCase += $("#equationName").val() + "\",";
// add the function to the test case
testCase += "fxn : \"";
testCase += parsedEquation.toString() + "\",";
// add the curValContext to the test case
testCase += "curVarContext : [";
for(var j = 0;j<vars.length;j++)
{
testCase += $("#" + vars[j] + "_slider_value").text();
if(j < vars.length-1)
{
testCase += ",";
}
}
testCase += "],";
// add the parse Solution to the test case
testCase += "parseSol : \""
testCase += parsedEquation.toString(context.toObj()) + "\",";
// add the numerical Solution to the test case
testCase += "numSol : \"";
testCase += solution + "\"";
// close out the brackets
testCase += "});\n";
console.log(testCase);
}
// Update solution display
var name = equationElement.fxnData.name;
updateSolution(name, parsedEquation, context.toObj(), solution);
// Update graph
addFunctionToGraph(name, parsedEquation, context);
// Update row color
color = $("#subgraph").color(name);
if(typeof color == "undefined")
{
color = "rgb(255,255,255)";
}
var cs = {};
cs["background-color"] = color;
$("#fxn_" + name).css(cs);
// update all graphs
//updateAllGraphs(parsedEquation, context);
}
// generate a hash
generateHashURL(parsedEquation.variables(),0);
}
}
function solveEqInMult()
{
if(typeof parsedEquation != "undefined")
{
// Create context
var vars = parsedEquation.variables();
var context = createContext(vars);
QGSolver.logDebugMessage("Context: " + context.toString());
// Solve
var solution = undefined;
try
{
solution = QGSolver.solve(context.toObj());
}
catch(exception)
{
alert("Solve failed: " + exception);
}
// If we solved the equation, update page
if(typeof solution != "undefined")
{
// Update solution display
updateSolution(parsedEquation, context.toObj(), solution);
// update all graphs
updateAllGraphs(parsedEquation, context);
}
// generate a hash
generateHashURL(parsedEquation.variables(),1);
}
}
/* clear the screen and parse the equation */
function clearAndParseEquation(equationElement, equation)
{
if(typeof equation != "undefined")
{
// clear the screen
clearScreen();
// parse the equation
parsedEquation = QGSolver.parse(equation);
// Create sliders
createSliders(parsedEquation.variables());
// Solve equation
solveEquation(equationElement, parsedEquation);
}
else
{
alert("Please enter a formula");
}
}
function clearAndParseMultipleEquations()
{
clearScreen();
parseMultipleEquations();
}
/* clear the screen then parse later */
function parseMultipleEquations()
{
// put all variables into single array
var allVariables = [];
// the base equation div name
var eqNameBase = "mainEquation";
// loop once over equations and grab all variables
for(var i = 1;i<6;i++)
{
var eqName;
if(i == 1)
{
eqName = eqNameBase;
}
else
{
eqName = eqNameBase + i.toString();
}
var singleEq = document.getElementById(eqName).value;
if(typeof singleEq != "undefined")
{
// parse the equation
parsedEquation = QGSolver.parse(singleEq);
// concat the variables
allVariables += parsedEquation.variables();
}
else
{
alert("Please enter a formula for " + eqName);
return;
}
}
// now that we've concatenated all variables...
// remove duplicates
var cleanVarArray = removeDuplicateVariables(allVariables);
// Create slidersFunction
createSliders(cleanVarArray);
// loop second time over equations and solve top down
for(var i = 1;i<6;i++)
{
var eqName;
if(i > 1)
{
eqName = eqNameBase + i.toString();
}
else
{
eqName = eqNameBase;
}
var singleEq = document.getElementById(eqName).value;
if(typeof singleEq != "undefined")
{
// parse the equation
parsedEquation = QGSolver.parse(singleEq);
// Solve equation
solveEqInMult();
}
}
}
function removeDuplicateVariables(dupArray)
{
var a = [];
var l = dupArray.length;
for(var i=0; i<l; i++) {
var found = 0;
for(var j=i+1; j<l; j++) {
// If this[i] is found later in the array
if (dupArray[i] == dupArray[j])
{
found = 1;
}
if(dupArray[i] == ",")
{
found = 1;
}
}
if(found == 0)
{
a.push(dupArray[i]);
}
}
return a;
}
function toggleDraw(toggleID)
{
solveEquation(this);
}
function updateMinimum(inputID)
{
// Retrieve variable name
var v = inputID.substring(0,inputID.indexOf("_")),
minField = $("#" + v + "_min"),
min = parseFloat(minField.val()),
maxField = $("#" + v + "_max"),
max = parseFloat(maxField.val()),
step = parseFloat($("#" + v + "_step").val()),
slider = $("#" + v + "_slider"),
curr = parseInput(slider.val(), step);
// Make sure the value is less than the maximum
if(min >= max)
{
min = max - 1;
minField.val(min);
}
// Make sure slider value is within new range
if(curr < min)
{
slider.val(min);
}
// Update slider values
slider[0].setAttribute("min", min);
// Resolve with new parameters
solve();
// if we changed the value we need to change the display
if(curr < min)
{
// update visually
showValue(min, inputID);
}
}
function updateMaximum(inputID)
{
// Retrieve variable name
var v = inputID.substring(0,inputID.indexOf("_")),
minField = $("#" + v + "_min"),
min = parseFloat(minField.val()),
maxField = $("#" + v + "_max"),
max = parseFloat(maxField.val()),
step = parseFloat($("#" + v + "_step").val()),
slider = $("#" + v + "_slider"),
curr = parseInput(slider.val(), step);
// Make sure the value is grater than the minimum
if(max <= min)
{
max = min + 1;
maxField.val(max);
}
// Make sure slider value is within new range
if(curr > max)
{
slider.val(max);
}
// Update slider values
slider[0].setAttribute("max", max);
// Resolve with new parameters
solve();
// if we changed the value we need to change the display
if(curr > max)
{
// update visually
showValue(max, inputID);
}
}
function updateStep(inputID)
{
// Retrieve variable name
var v = inputID.substring(0,inputID.indexOf("_")),
stepField = $("#" + v + "_step"),
slider = $("#" + v + "_slider");
// Update slider values
slider[0].setAttribute("step", parseFloat(stepField.val()));
// Resolve with new parameters
solve();
}
/* function generateHashURL generates a save hash url for the current equation, receives variables as argument*/
function generateHashURL(vars,multi)
{
// do NOT use window.location.href
// it FAILS to on redirection sites
//var URL = window.location.href,
var URL = "www.quickgrapher.com/index.html?";
// Pull off any existing URI params
end = URL.indexOf("?");
if(end != -1)
{
URL = URL.substring(0,end+1);
}
else
{
URL = URL + "?";
}
// add equation(s) to url
if(multi == 1)
{
// the base equation div name
var eqNameBase = "#mainEquation";
// the base name div name
var nameNameBase = "#equationName";
// loop once over equations and grab all variables
for(var i = 1;i<6;i++)
{
var eqName;
var nameName;
if(i == 1)
{
eqName = eqNameBase;
nameName = nameNameBase;
}
else
{
eqName = eqNameBase + i.toString();
nameName = nameNameBase + i.toString();
}
var localEquation = $(eqName).val();
if(typeof localEquation != "undefined")
{
URL += compressName(localEquation);
var localName = $(nameName).val();
localName = localName.replace(/\s/g,"%20");
if(typeof localName != "undefined")
{
URL += "[";
URL += localName;
}
URL += ";"
}
}
URL += "=";
}
else
{
var localEquation = $("#mainEquation").val();
if(typeof localEquation != "undefined")
{
URL += compressName(localEquation) + "=";
}
}
// variables to store hash values
var delimiter = ":",
minString = "",
maxString = "",
stepString = "",
lastString = "",
visString = "";
// Loop over variables
var name = "",
v, varLen = vars.length,
step, minVal, maxVal, last;
for(var i = 0; i < varLen; i++)
{
// Current variable
v = vars[i];
// get current variable's values
lastVal = parseFloat($("#" + v + "_slider").val()),
minVal = parseFloat($("#" + v + "_min").val()),
stepVal = parseFloat($("#" + v + "_step").val()),
maxVal = parseFloat($("#" + v + "_max").val());
var visVal;
if($("#" + v + "_graph_checkbox").is(":checked"))
{
visVal = 1;
}
else
{
visVal = 0;
}
// add current values to correct hash strings
minString = minString + minVal + delimiter;
maxString = maxString + maxVal + delimiter;
stepString = stepString + stepVal + delimiter;
lastString = lastString + lastVal + delimiter;
visString = visString + visVal + delimiter;
}
// replace spaces with %20 for web addresses
//var graphName = $("#totalName").val(),
//cleanGraphName = graphName.replace(/\s/g,"%20");
var cleanGraphName = "";
// clean up the plusses in URL for email clients
URL = URL.replace(/\+/g,"'%");
// add the fully constituted strings to URL
URL += minString + "{" + maxString + "}" + stepString + "[" + lastString + ";" + visString + "=" + cleanGraphName + "]";
// sneak the url into the instructions block
$("#instruct").attr("href", URL);
//updateShare(URL,graphName);
// sneak the url into social sharing services
$("#twitter_share").attr("st_url",URL);
$("#facebook_share").attr("st_url",URL);
$("#linkedin_share").attr("st_url",URL);
$("#gbuzz_share").attr("st_url",URL);
$("#email_share").attr("st_url",URL);
$("#sharethis_share").attr("st_url",URL);
$("#reddit_share").attr("st_url",URL);
$("#slashdot_share").attr("st_url",URL);
}
// update our share icon dynamically
function updateShare(url, title)
{
if(typeof SHARETHIS != "undefined")
{
var object = SHARETHIS.addEntry({
title: title,
url: url
});
object.attachButton(document.getElementById('blank_share'));
}
}
function createFunctionRow(name, fxn, parsed)
{
var v, vars = parsed.variables(),
varsLen = vars.length, ctx,
el, elParent = $("#function_list"),
row,
style;
// Create context
ctx = {};
for(var i = 0; i < varsLen; i++)
{
v = vars[i];
// Default value is 1
ctx[v] = 1;
}
// Row container
el = document.createElement("div");
el.id = "row_" + name;
el.className = "fxn_row";
el.fxnData = {
name: name,
fxn: fxn,
eq: parsed,
context: ctx
};
row = el;
el = $(el);
elParent.append(el);
elParent = el;
// Row table
el = document.createElement("table");
elParent.append(el);
elParent = $(el);
// Table row
el = document.createElement("tr");
elParent.append(el);
elParent = $(el);
// Icon column
el = document.createElement("td");
el.id = "icons_" + name;
el.className = "fxn_icons";
el = $(el);
elParent.append(el);
// Function column
el = document.createElement("td");
el.id = "fxn_" + name;
el.className = "fxn_highlight";
// Function HTML string (id prefix, element open tag, element close tag, context(optional) )
var inner = parsed.toHTML(name,"p")
inner += " = ";
el.innerHTML = inner;
el = $(el);
// modified later by graph
style = {
background: "rgb(255,255,255)"
};
el.css(style);
elParent.append(el);
// Remove column
el = document.createElement("td");
el.id = "remove_" + name;
el.className = "fxn_remove";
elParent.append(el);
el.innerHTML = "-";
return row;
}
function createSliders(vars)
{
var v, varsLen = vars.length,
sliderParent = $("#variables"),
el, inp, first,
sliderLabel, sliderValue,
graphCheck, graphCheckLabel;
for(var i = 0; i < varsLen; i++)
{
// each variable may have a stored min, max, step, last
var minValue = "";
var maxValue = "";
var stepValue = "";
var lastValue = "";
var visValue = 1;
// if not, use the default values
// default min value
if(!variableMinHash[i]) {
minValue = 0;
}
else
{
minValue = variableMinHash[i];
}
// default max value
if(typeof variableMaxHash[i] == "undefined") {
maxValue = 100;
}
else
{
maxValue = variableMaxHash[i];
}
// default step value
if(typeof variableStepHash[i] == "undefined") {
stepValue = 1;
}
else
{
stepValue = variableStepHash[i];
}
// default last value
if(typeof variableLastHash[i] == "undefined") {
lastValue = 1;
}
else
{
lastValue = variableLastHash[i];
}
if(typeof variableVisHash[i] == "undefined") {
visValue = 1;
}
else
{
visValue = variableVisHash[i];
}
v = vars[i];
// Create slider list item
first = document.createElement("tr");
first.setAttribute("class","variable");
sliderParent.append(first);
first = $(first);
// Create show checkbox
inp = document.createElement("input");
inp.setAttribute("class","show_select");
inp.id = v + "_graph_checkbox";
inp.setAttribute("type", "checkbox");
inp.setAttribute("onclick", "toggleInclude(this.id)");
inp.setAttribute("alt", "Draw " + v);
inp.setAttribute("title", "Draw " + v);
if(visValue == 1)
{
inp.setAttribute("checked", "checked");
}
// Variable name and value (added checkbox here)
el = document.createElement("td");
el.setAttribute("rowspan","2");
el = $(el);
el.append(inp);
inp = document.createElement("div");
inp.innerHTML = v + "<font style='font-size: 7pt; margin-left:2px;'> = </font>";
inp.id = v + "_variable_name";
el.append(inp);
inp = $(inp);
var cs = {
width:"100%",
// Need to load this from graph
color:"rgb" + "(0,0,0)",
display: "inline"
};
cs["font-size"] = "13pt";
inp.css(cs);
inp = document.createElement("div");
inp.setAttribute("class","variable_value");
inp.innerHTML = lastValue;
inp.id = v + "_slider_value";
el.append(inp);
inp = $(inp);
first.append(el);
el = document.createElement("td");
el.setAttribute("class","minimum");
el = $(el);
inp = document.createElement("input");
inp.setAttribute("id", v + "_min");
inp.setAttribute("type", "text");
inp.setAttribute("class", "range_input");
inp.setAttribute("size", "10");
inp.setAttribute("value", minValue);
inp.setAttribute("onchange", "updateMinimum(this.id)");
inp.setAttribute("alt", "Set minimum value for " + v);
inp.setAttribute("title", "Set minimum value for " + v);
el.append(inp);
first.append(el);
el = document.createElement("td");
el.setAttribute("class","step");
el = $(el);
inp = document.createElement("input");
inp.setAttribute("id", v + "_step");
inp.setAttribute("type", "text");
inp.setAttribute("class", "range_input");
inp.setAttribute("size", "10");
inp.setAttribute("value", stepValue);
inp.setAttribute("onchange", "updateStep(this.id)");
inp.setAttribute("alt", "Set step value for " + v);
inp.setAttribute("title", "Set step value for " + v);
el.append(inp);
first.append(el);
el = document.createElement("td");
el.setAttribute("class","maximum");
el = $(el);
inp = document.createElement("input");
inp.setAttribute("id", v + "_max");
inp.setAttribute("type", "text");
inp.setAttribute("class", "range_input");
inp.setAttribute("size", "10");
inp.setAttribute("value", maxValue);
inp.setAttribute("onchange", "updateMaximum(this.id)");
inp.setAttribute("alt", "Set maximum value for " + v);
inp.setAttribute("title", "Set maximum value for " + v);
el.append(inp);
first.append(el);
first = document.createElement("tr");
first.setAttribute("class","variable");
sliderParent.append(first);
first = $(first);
el = document.createElement("td");
el.setAttribute("class","range");
el.setAttribute("colspan","3");
el = $(el);
inp = document.createElement("input");
inp.id = v + "_slider";
inp.setAttribute("type", "range");
inp.setAttribute("min", minValue); //variableMinHash[i]);
inp.setAttribute("max", maxValue); //variableMaxHash[i]);
inp.setAttribute("step", stepValue); //variableStepHash[i]);
inp.setAttribute("value", lastValue);
inp.setAttribute("alt", "Adjust " + v);
inp.setAttribute("title", "Adjust " + v);
el.append(inp);
first.append(el);
inp = $(inp);
// Set initial value
inp.val(lastValue);
// Add change listener
inp[0].setAttribute("onchange", "showValue(this.value, this.id)");
}
// Verify slider compatibility with browser
//If range isnt supported
if(!Modernizr.inputtypes.range)
{
$('input[type=range]').each(function() {
var $input = $(this);
var $slider = $('<div id="' + $input.attr('id') + '" class="' + $input.attr('class') + '"></div>');
var step = $input.attr('step');
$input.after($slider).hide();
$slider.slider({
min: parseFloat($input.attr('min')),
max: parseFloat($input.attr('max')),
step: parseFloat($input.attr('step')),
value: parseFloat($input.attr('value')),
change: function(e, ui) {
showValue(ui.value, this.id);
}
});
});
}
}
function verifyGraph()
{
var graphID = "subgraph";
// Check if we already have a graph element
graph = $("#" + graphID);
if(graph.length == 0)
{
// Create graph element
var parentElement = $("#graph_container");
graph = document.createElement("div");
graph.id = graphID;
graph.style.position = "relative";
graph.style.width = "100%";
graph.style.height = "100%";
// Add to canvas
parentElement.append(graph);
// Register with Graph
var graphName = $("#equationName").val();
graph = $(graph);
var opts = {name: graphName};
opts['hue-increment'] = 45;
opts['hue-base'] = 22;
opts['value-base'] = 95;
opts['title'] = "What to put for title?"; //$("#equationName").val() + " ( " + vars.join(", ") +" )";
graph.graphify(opts).realHover({
hover: Graph.highlightNearest,
out: Graph.removeHighlight
});
// Set variable colors from plot
// var color;
// for(var i = 0; i < varLen; i++)
// {
// v = vars[i];
// color = $("#subgraph").color(v);
// if(typeof color == "undefined")
// {
// color = "rgb(0,0,0)";
// }
//
// $("#" + v + "_slider_value").css({color: color});
// }
}
}
function addFunctionToGraph(name, equation, context)
{
verifyGraph();
}
// updates graphs for all variables
function updateAllGraphs(equation, context)
{
var unifiedGraph = true,
graph,
// Retrieve variables
v, vars = equation.variables(),
varLen = vars.length;
if(unifiedGraph)
{
var graphID = "subgraph";
// Check if we already have a graph element
graph = $("#" + graphID);
if(graph.length == 0)
{
// Create graph element
var parentElement = $("#graph_container");
graph = document.createElement("div");
graph.id = graphID;
graph.style.position = "relative";
graph.style.width = "100%";
graph.style.height = "100%";
// Add to canvas
parentElement.append(graph);
// Register with Graph
var graphName = $("#equationName").val();
graph = $(graph);
var opts = {name: graphName};
opts['hue-increment'] = 45;
opts['hue-base'] = 22;
opts['value-base'] = 95;
opts['title'] = $("#equationName").val() + " ( " + vars.join(", ") +" )";
graph.graphify(opts)/*.attach_legend({
'legend-mode': false,
'legend-container': $("#legend"),
})*/.realHover({
hover: Graph.highlightNearest,
out: Graph.removeHighlight
});
// Set variable colors from plot
var color;
for(var i = 0; i < varLen; i++)
{
v = vars[i];
color = $("#subgraph").color(v);
if(typeof color == "undefined")
{
color = "rgb(0,0,0)";
}
$("#" + v + "_slider_value").css({color: color});
}
}
else
{
// Update graph title
graph.graph_option("title",$("#equationName").val() + " ( " + vars.join(", ") +" )");
}
}
/// Loop over variable
var name = "",
localContext = context.toObj(),
step, min, max;
for(var i = 0; i < varLen; i++)
{
// Current variable
v = vars[i];
// If we are supposed to draw this variable
if($("#" + v + "_graph_checkbox").is(":checked")
|| (typeof graph.color(v) == "undefined"))
{
// Adjust context
var fixedPt = localContext[v],
min = parseFloat($("#" + v + "_min").val()),
step = parseFloat($("#" + v + "_step").val()),
max = parseFloat($("#" + v + "_max").val()),
steps = ((max - min)/step) + 1;
// Substitute iterator
localContext[v] = new VariableIterator(min,step);
// Create graph
updateGraph(graphID, v, equation, localContext, steps);
// Replace values into local context for next loop step
localContext[v] = fixedPt;
}
if(!$("#" + v + "_graph_checkbox").is(":checked"))
{
// Make sure we have cleared the data for this variable
graph.hide_data(v);
}
}
}
// updates a single graph
function updateGraph(graphID, graphVariable, equation, context, steps)
{
// Retrieve reference to graph object
var graph = $("#" + graphID),
currVarValue, solution, data = [];
// Solve for the specified points
for(var i = 0; i < steps; i++)
{
currVarValue = context[graphVariable].value;
try
{
solution = equation.solve(context);
} catch(error)
{
solution = undefined;
QGSolver.logDebugMessage("Solve Error: [var: "+graphVariable+", value: "+currVarValue+"] " + error);
}
// Only add the point if it is a valid solution
if((typeof solution != "undefined") && isFinite(solution))
{
data.push([currVarValue, solution]);
}
// Step variable
context[graphVariable].step();
}
var lbl = "",
v, vars = equation.variables(),
varLen = vars.length;
lbl += graphVariable;
// Add plot for this variable (will overwrite existing ones)
var cs = {label : lbl};
cs['plot-type'] = 'line';
graph.plot(
graphVariable,
data,
cs
);
// Set variable colors from plot
var color = $("#subgraph").color(lbl);
if(typeof color == "undefined")
{
color = "rgb(0,0,0)";
}
//$("#" + lbl + "_variable_name").css({"color": color});
$("#" + lbl + "_slider_value").css({color: color});
cs = {color: color};
cs["font-weight"] = "bold";
$("#" + lbl + "_param").css(cs);
}
function toggle(exampleID)
{
var ex = $("#" + exampleID);
if(ex.is(":visible"))
{
ex.hide();
}
else
{
// Hide all others
$(".menu_item").hide();
// Show this one
ex.show();
}
return false;
}
function showExamples(exampleID)
{
var ex = $("#" + exampleID);
ex.show();
return false;
}
function hideExamples(exampleID)
{
var ex = $("#" + exampleID);
ex.hide();
return false;
}
function nextExamples()
{
var exLen = examples.length;
if((curr_page + 1) * 5 < exLen)
{
curr_page = curr_page + 1;
// Clear display
var list = $("#examplelist").empty();
var ex, example;
for(var i = (curr_page * 5); i < exLen && i < (curr_page + 1)*5; i++)
{
ex = examples[i];
createExampleLink(ex, list);
}
if( curr_page > 0 )
{
$("#prevExamples").show();
}
if( ((curr_page+1)*5) > exLen )
{
$("#nextExamples").hide();
}
}
return false;
}
function prevExamples()
{
var exLen = examples.length;
if(curr_page > 0)
{
curr_page = curr_page - 1;
// Clear display
var list = $("#examplelist").empty();
var ex, example;
for(var i = (curr_page * 5); i < exLen && i < (curr_page + 1)*5; i++)
{
ex = examples[i];
createExampleLink(ex, list);
}
$("#nextExamples").show();
if( curr_page == 0 )
{
$("#prevExamples").hide();
}
}
return false;
}
var examples,
functions,
curr_page;
function loadExamples()
{
// Load examples
examples = Examples;
// If there was nothing to load, just create empty array
if(typeof examples == "undefined")
{
examples = [];
}
if(examples.length > 0)
{
resetExamples();
}
}
function loadFunctions()
{
// Load functions
functions = Functions;
// If there was nothing to load, just create empty array
if(typeof functions == "undefined")
{
functions = {};
}
var list = $("#functionlist"), fxn,
col, row = 0, cols = 5,
fxnCount = 0, colSize = 1, colWidth,
emptied = false, margins;
// Count functions
for(var f in functions)
{
fxnCount++;
}
colSize = Math.ceil(fxnCount / cols);
var item = list,
w = item.width();
while(w == 0 || item.css("width").indexOf("%") != -1)
{
if(typeof item.parent() != "undefined")
{
item = item.parent();
w = item.width();
}
else
{
break;
}
}
colWidth = Math.floor(item.width() / cols);
if(colSize < 1)
{
colSize = 1;
}
// Create links
for(var fxnName in functions)
{
if(!emptied)
{
list.empty();
emptied = true;
}
margins = "margin-top: ";
col = Math.floor(row/colSize);
var top = 0;
if(row > 0 && row % colSize == 0)
{
top = -14 * colSize;
}
margins += top + "px;";
margins += " margin-left: " + (col * colWidth + 5) + "px;";
// If last row
var next = row + 1;
if(next == fxnCount && next % colSize != 0)
{
margins += " margin-bottom: " + (14 * (colSize - (next%colSize))) + "px;";
}
createFunctionLink(fxnName, margins, list);
row++;
}
}
function insertFunction(linkID)
{
var fxnName = linkID.substring(linkID.indexOf("_")+1,linkID.length),
fxn = functions[fxnName];
if(typeof fxn != "undefined")
{
var append = "",
eq = $("#mainEquation"),
// Add a space if none there
curr = eq.val(),
cursorOffset = 0;
if(curr.length > 0 && curr.charAt(curr.length - 1) != " ")
{
append += " ";
}
append += fxnName;
if(fxn.prefix)
{
append += "()";
cursorOffset = -2;
}
append += " ";
curr += append;
eq.val(curr);
// Focus
eq.focus();
// Set cursor
eq[0].selectionStart = curr.length + cursorOffset;
eq[0].selectionEnd = curr.length + cursorOffset;
}
}
function compressName(name)
{
// Remove spaces
var compressed = name.replace(/\s/g,"");
return compressed;
}
function createFunctionLink(fxnStr, style, parent)
{
var ex = document.createElement("li");
ex.setAttribute("id","fxn_" + fxnStr);
ex.setAttribute("onclick","insertFunction(this.id)");
ex.setAttribute("style",style);
// Text to add
ex.innerHTML = fxnStr;
parent.append(ex);
}
function createExampleLink(example, parent)
{
var ex = document.createElement("li"),
inner = "<a href='http://www.quickgrapher.com/index.html?";
inner += compressName(example.url);
inner += "'>"
inner += example.name;
inner += "</a>";
ex.innerHTML = inner;
ex.setAttribute("id","example_" + compressName(example.name));
parent.append(ex);
}
function resetExamples()
{
curr_page = 0;
// Clear display
var list = $("#examplelist");
list.empty();
// Display
var exLen = examples.length,
ex, example;
for(var i = (curr_page * 5); i < exLen && i < (curr_page + 1)*5; i++)
{
ex = examples[i];
createExampleLink(ex, list);
}
if( exLen > 5 )
{
$("#nextExamples").show();
}
}
function loadExample(exampleID)
{
var exampleName = exampleID.substring(8,exampleID.length),
ex, exLen = examples.length;
// Close examples list
var p = $("#" + exampleID).parent();
hideExamples(p.id());
// Load display
for(var i = 0; i < exLen; i++)
{
ex = examples[i];
if(compressName(ex.name) == exampleName)
{
$("#mainEquation").val(ex.fxn);
$("#graphBtn").click();
break;
}
}
return false;
}
function getViewportDimensions()
{
var dims = {};
// Compliant browsers use innerWidth
if (typeof window.innerWidth != 'undefined')
{
dims.width = window.innerWidth,
dims.height = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0)
{
dims.width = document.documentElement.clientWidth,
dims.height = document.documentElement.clientHeight
}
// For older versions of IE
else
{
dims.width = document.getElementsByTagName('body')[0].clientWidth,
dims.height = document.getElementsByTagName('body')[0].clientHeight
}
return dims;
}
var fullscreen_active = false,
// To prevent re-entrance issues if the person clicks link rapidly
toggling = false;
function resizeFullscreen()
{
// Calculate available width
var dims = getViewportDimensions(),
w = dims.width,
h = dims.height,
// Graph & equation get 75%
graphW = Math.floor(0.75 * w),
// Solution and variables get other 25%
resultsW = w - graphW - 5;
// Adjust for vertical screens
var vertical = false;
// Start adjusting graph compression
// Minimum width the variable bar can manage is 240px
if(resultsW < 250)
{
resultsW = 250;
graphW = w - resultsW - 5;
}
if(h > 1.05*w)
{
vertical = true;
}
// Fix styles
var style;
if(vertical)
{
$("#result").removeClass("result_fullscreen");
$("#solution_column").addClass("solution_column");
$("#solution_column").removeClass("solution_column_fullscreen");
$("#variables_column").addClass("variables_column_fullscreen_vert");
$("#variables_column").removeClass("variables_column");
$("#variables_column").removeClass("variables_column_fullscreen");
style = {
width : Math.floor(w - 300)
};
$("#variables_column").css(style);
style = {
width : Math.floor(w - 10),
height : Math.floor(0.65 * h)
};
$("#graph_container").css(style);
style = {width : w - 260};
$("#mainEquation").css(style);
// Remove background logo
style = {};
style["background-image"] = "";
$("#fullscreen_container").css(style);
}
else
{
$("#result").addClass("result_fullscreen");
$("#solution_column").removeClass("solution_column");
$("#solution_column").addClass("solution_column_fullscreen");
$("#variables_column").removeClass("variables_column");
$("#variables_column").removeClass("variables_column_fullscreen_vert");
$("#variables_column").addClass("variables_column_fullscreen");
style = {width : ""};
$("#mainEquation").css(style);
style = {width : graphW - 30};
$("#equation").css(style);
style = {
width : graphW,
height : h - 40
};
$("#graph_container").css(style);
style = {width : resultsW};
$("#result").css(style);
$("#solution_column").css(style);
$("#variables_column").css(style);
// Add background logo
style = {};
style["background-image"] = "url('images/logo_1.png')";
$("#fullscreen_container").css(style);
}
}
function toggleFullscreen()
{
if(!toggling)
{
toggling = true;
if(!fullscreen_active)
{
// Update toggle
fullscreen_active = true;
$("#fullscreen_toggle").text("X");
var style = {};
style["background-color"] = "rgb(255,0,0)";
style["color"] = "rgb(255,255,255)";
style["border"] = "0px";
$("#fullscreen_toggle").css(style);
// Hide normal elements
$("#container").hide();
$("#footer").hide();
$("#beta_box").hide();
// Move necessary elements to fullscreen block
var fsc = $("#fullscreen_container");
// -- Equation
fsc.append($("#equation"));
// -- Graph
fsc.append($("#graph_container"));
// -- Solutions & Variables
fsc.append($("#result"));
// -- Variables
// Calculate available width
var dims = getViewportDimensions(),
w = dims.width,
h = dims.height,
vertical = false,
// Graph & equation get 75%
graphW = Math.floor(0.75 * w),
// Solution and variables get other 25%
resultsW = w - graphW - 5;
if(h > 1.05*w)
{
vertical = true;
}
// Fix styles
style = {};
// Background style
if(vertical)
{
// Remove background logo
style["background-image"] = "";
$("#fullscreen_container").css(style);
}
else
{
// Add background logo
style["background-image"] = "url('images/logo_1.png')";
$("#fullscreen_container").css(style);
}
// Input style
style = {};
style["margin"] = "2px 0px 0px 30px";
$("#equation").css(style);
// Graph style
style = {};
style["margin"] = "5px 5px 5px 5px";
style["display"] = "inline";
$("#graph_container").css(style);
// Results and variables display
if(!vertical)
{
$("#result").addClass("result_fullscreen");
}
$("#mainEquation").removeClass("equation_input");
$("#mainEquation").addClass("equation_input_fullscreen");
if(!vertical)
{
$("#solution_column").removeClass("solution_column");
$("#solution_column").addClass("solution_column_fullscreen");
$("#variables_column").removeClass("variables_column");
$("#variables_column").addClass("variables_column_fullscreen");
}
resizeFullscreen();
// Show fullscreen block
$("#fullscreen_container").show();
// Fire resize handler
$("#subgraph").trigger("resize");
}
else
{
// Update toggle
fullscreen_active = false;
$("#fullscreen_toggle").text("Fullscreen");
var style = {};
style["background-color"] = "";
style["color"] = "";
style["border"] = "";
$("#fullscreen_toggle").css(style);
// Hide fullscreen block
$("#fullscreen_container").hide();
// Move elements to normal location
// -- Equation
$("#equation").insertAfter("#functions");
// -- Graph
$("#graph_container").insertAfter("#equation");
// -- Solution & variables
$("#result").insertAfter("#graph_break");
// // -- Variables
// Fix styles
style = {};
style["margin"] = "";
style["width"] = "";
$("#equation").css(style);
style = {};
style["margin"] = "";
style["width"] = "";
style["height"] = "";
style["display"] = "";
$("#graph_container").css(style);
// Fire resize handler
$("#subgraph").trigger("resize");
style = {};
style["width"] = "";
$("#result").removeClass("result_fullscreen");
$("#mainEquation").addClass("equation_input");
$("#mainEquation").removeClass("equation_input_fullscreen");
$("#result").css(style);
$("#solution_column").addClass("solution_column");
$("#solution_column").removeClass("solution_column_fullscreen");
$("#solution_column").css(style);
$("#variables_column").addClass("variables_column");
$("#variables_column").removeClass("variables_column_fullscreen");
$("#variables_column").removeClass("variables_column_fullscreen_vert");
$("#variables_column").css(style);
// Show normal elements
$("#container").show();
$("#footer").show();
$("#beta_box").show();
// Fire resize handler
$("#subgraph").trigger("resize");
}
toggling = false;
}
}
$(window).resize(function() {
if(fullscreen_active && !toggling)
{
toggling = true;
resizeFullscreen();
toggling = false;
}
});
/* From page */
function clearAndParse()
{
clearAndParseEquation(this, document.getElementById('mainEquation').value);
}
function clearAndParseMultiple()
{
clearAndParseMultipleEquations();
}
function solve()
{
solveEquation(this);
}
function solveMult()
{
solveEqInMult();
}
function toggleInclude(toggleID)
{
toggleDraw(toggleID);
}
function addFunction() {
var fxn = $('#mainEquation').val(),
name = $('#equationName').val();
// parse the equation
var parsed = QGSolver.parse(fxn);
// Create sliders
var row = createFunctionRow(name, fxn, parsed);
// Solve equation
solveEquation(row, parsed);
}
$(document).ready(function() {
// Turn on debug
//QGSolver.DEBUG = true;
QGSolver.DEBUG = false;
// enable random load
// Turn on Test Generation
QGSolver.TESTGENERATION = false;
// Load examples
loadExamples();
// Load functions
loadFunctions();
// Load From TitleBar
loadTitleBarHash();
// Add key listeners
$("#equationName").keyup(function(event){
if(event.keyCode == 13){
var eq = $("#mainEquation");
if(eq.val().length == 0)
{
eq.focus();
}
else
{
$("#graphBtn").click();
}
}
});
$("#mainEquation").keyup(function(event){
if(event.keyCode == 13){
var name = $("#equationName");
if(name.val().length == 0)
{
name.focus();
}
else
{
$("#graphBtn").click();
}
}
});
});
| Changing var scope
| js/plain/quick_graph.js | Changing var scope | <ide><path>s/plain/quick_graph.js
<ide> addFunctionToGraph(name, parsedEquation, context);
<ide>
<ide> // Update row color
<del> color = $("#subgraph").color(name);
<add> var color = $("#subgraph").color(name);
<ide> if(typeof color == "undefined")
<ide> {
<ide> color = "rgb(255,255,255)"; |
|
Java | apache-2.0 | 42c52e4fe6ddd86381625aaad2884591f6da1d0b | 0 | hierynomus/sshj,hierynomus/sshj | /*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.transport;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.transport.cipher.Cipher;
import net.schmizz.sshj.transport.compression.Compression;
import net.schmizz.sshj.transport.mac.MAC;
import net.schmizz.sshj.transport.random.Random;
import org.slf4j.Logger;
import java.util.concurrent.locks.Lock;
/** Encodes packets into the SSH binary protocol per the current algorithms. */
final class Encoder
extends Converter {
private final Logger log;
private final Random prng;
private final Lock encodeLock;
Encoder(Random prng, Lock encodeLock, LoggerFactory loggerFactory) {
this.prng = prng;
this.encodeLock = encodeLock;
log = loggerFactory.getLogger(getClass());
}
private void compress(SSHPacket buffer) {
compression.compress(buffer);
}
private void putMAC(SSHPacket buffer, int startOfPacket, int endOfPadding) {
buffer.wpos(endOfPadding + mac.getBlockSize());
mac.update(seq);
mac.update(buffer.array(), startOfPacket, endOfPadding);
mac.doFinal(buffer.array(), endOfPadding);
}
/**
* Encode a buffer into the SSH binary protocol per the current algorithms.
*
* @param buffer the buffer to encode
*
* @return the sequence no. of encoded packet
*
* @throws TransportException
*/
long encode(SSHPacket buffer) {
encodeLock.lock();
try {
if (log.isTraceEnabled()) {
// Add +1 to seq as we log before actually incrementing the sequence.
log.trace("Encoding packet #{}: {}", seq + 1, buffer.printHex());
}
if (usingCompression())
compress(buffer);
final int payloadSize = buffer.available();
// Compute padding length
int padLen = -(payloadSize + 5) & cipherSize - 1;
if (padLen < cipherSize)
padLen += cipherSize;
final int startOfPacket = buffer.rpos() - 5;
final int packetLen = payloadSize + 1 + padLen;
// Put packet header
buffer.wpos(startOfPacket);
buffer.putUInt32(packetLen);
buffer.putByte((byte) padLen);
// Now wpos will mark end of padding
buffer.wpos(startOfPacket + 5 + payloadSize + padLen);
// Fill padding
prng.fill(buffer.array(), buffer.wpos() - padLen, padLen);
seq = seq + 1 & 0xffffffffL;
if (mac != null)
putMAC(buffer, startOfPacket, buffer.wpos());
cipher.update(buffer.array(), startOfPacket, 4 + packetLen);
buffer.rpos(startOfPacket); // Make ready-to-read
return seq;
} finally {
encodeLock.unlock();
}
}
@Override
void setAlgorithms(Cipher cipher, MAC mac, Compression compression) {
encodeLock.lock();
try {
super.setAlgorithms(cipher, mac, compression);
} finally {
encodeLock.unlock();
}
}
@Override
void setAuthenticated() {
encodeLock.lock();
try {
super.setAuthenticated();
} finally {
encodeLock.unlock();
}
}
@Override
Compression.Mode getCompressionType() {
return Compression.Mode.DEFLATE;
}
}
| src/main/java/net/schmizz/sshj/transport/Encoder.java | /*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.transport;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.transport.cipher.Cipher;
import net.schmizz.sshj.transport.compression.Compression;
import net.schmizz.sshj.transport.mac.MAC;
import net.schmizz.sshj.transport.random.Random;
import org.slf4j.Logger;
import java.util.concurrent.locks.Lock;
/** Encodes packets into the SSH binary protocol per the current algorithms. */
final class Encoder
extends Converter {
private final Logger log;
private final Random prng;
private final Lock encodeLock;
Encoder(Random prng, Lock encodeLock, LoggerFactory loggerFactory) {
this.prng = prng;
this.encodeLock = encodeLock;
log = loggerFactory.getLogger(getClass());
}
private void compress(SSHPacket buffer) {
compression.compress(buffer);
}
private void putMAC(SSHPacket buffer, int startOfPacket, int endOfPadding) {
buffer.wpos(endOfPadding + mac.getBlockSize());
mac.update(seq);
mac.update(buffer.array(), startOfPacket, endOfPadding);
mac.doFinal(buffer.array(), endOfPadding);
}
/**
* Encode a buffer into the SSH binary protocol per the current algorithms.
*
* @param buffer the buffer to encode
*
* @return the sequence no. of encoded packet
*
* @throws TransportException
*/
long encode(SSHPacket buffer) {
encodeLock.lock();
try {
if (log.isTraceEnabled())
log.trace("Encoding packet #{}: {}", seq, buffer.printHex());
if (usingCompression())
compress(buffer);
final int payloadSize = buffer.available();
// Compute padding length
int padLen = -(payloadSize + 5) & cipherSize - 1;
if (padLen < cipherSize)
padLen += cipherSize;
final int startOfPacket = buffer.rpos() - 5;
final int packetLen = payloadSize + 1 + padLen;
// Put packet header
buffer.wpos(startOfPacket);
buffer.putUInt32(packetLen);
buffer.putByte((byte) padLen);
// Now wpos will mark end of padding
buffer.wpos(startOfPacket + 5 + payloadSize + padLen);
// Fill padding
prng.fill(buffer.array(), buffer.wpos() - padLen, padLen);
seq = seq + 1 & 0xffffffffL;
if (mac != null)
putMAC(buffer, startOfPacket, buffer.wpos());
cipher.update(buffer.array(), startOfPacket, 4 + packetLen);
buffer.rpos(startOfPacket); // Make ready-to-read
return seq;
} finally {
encodeLock.unlock();
}
}
@Override
void setAlgorithms(Cipher cipher, MAC mac, Compression compression) {
encodeLock.lock();
try {
super.setAlgorithms(cipher, mac, compression);
} finally {
encodeLock.unlock();
}
}
@Override
void setAuthenticated() {
encodeLock.lock();
try {
super.setAuthenticated();
} finally {
encodeLock.unlock();
}
}
@Override
Compression.Mode getCompressionType() {
return Compression.Mode.DEFLATE;
}
}
| Fixed logging of Encoder to log correct sequence number
| src/main/java/net/schmizz/sshj/transport/Encoder.java | Fixed logging of Encoder to log correct sequence number | <ide><path>rc/main/java/net/schmizz/sshj/transport/Encoder.java
<ide> long encode(SSHPacket buffer) {
<ide> encodeLock.lock();
<ide> try {
<del> if (log.isTraceEnabled())
<del> log.trace("Encoding packet #{}: {}", seq, buffer.printHex());
<add> if (log.isTraceEnabled()) {
<add> // Add +1 to seq as we log before actually incrementing the sequence.
<add> log.trace("Encoding packet #{}: {}", seq + 1, buffer.printHex());
<add> }
<ide>
<ide> if (usingCompression())
<ide> compress(buffer); |
|
Java | mit | 41931b5852dd1b6dfad69c41b34d20ac7e5be25d | 0 | kmdouglass/Micro-Manager,kmdouglass/Micro-Manager | ///////////////////////////////////////////////////////////////////////////////
//FILE: MMStudioMainFrame.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//AUTHOR: Nenad Amodaj, [email protected], Jul 18, 2005
// Modifications by Arthur Edelstein, Nico Stuurman
//COPYRIGHT: University of California, San Francisco, 2006-2010
// 100X Imaging Inc, www.100ximaging.com, 2008
//LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//CVS: $Id$
//
package org.micromanager;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.Line;
import ij.gui.Roi;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import java.util.Timer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.event.AncestorEvent;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.MMEventCallback;
import mmcorej.Metadata;
import mmcorej.StrVector;
import org.json.JSONObject;
import org.micromanager.acquisition.AcquisitionManager;
import org.micromanager.api.ImageCache;
import org.micromanager.api.ImageCacheListener;
import org.micromanager.acquisition.MMImageCache;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.Autofocus;
import org.micromanager.api.DeviceControlGUI;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.MMListenerInterface;
import org.micromanager.conf2.ConfiguratorDlg2;
import org.micromanager.conf.ConfiguratorDlg;
import org.micromanager.conf.MMConfigFileException;
import org.micromanager.conf.MicroscopeModel;
import org.micromanager.graph.ContrastPanel;
import org.micromanager.graph.GraphData;
import org.micromanager.graph.GraphFrame;
import org.micromanager.navigation.CenterAndDragListener;
import org.micromanager.navigation.PositionList;
import org.micromanager.navigation.XYZKeyListener;
import org.micromanager.navigation.ZWheelListener;
import org.micromanager.utils.AutofocusManager;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMImageWindow;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.TextUtils;
import org.micromanager.utils.TooltipTextMaker;
import org.micromanager.utils.WaitDialog;
import bsh.EvalError;
import bsh.Interpreter;
import com.swtdesigner.SwingResourceManager;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.process.FloatProcessor;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.KeyboardFocusManager;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.HashMap;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.event.AncestorListener;
import mmcorej.TaggedImage;
import org.json.JSONException;
import org.micromanager.acquisition.AcquisitionVirtualStack;
import org.micromanager.acquisition.AcquisitionWrapperEngine;
import org.micromanager.acquisition.LiveModeTimer;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.acquisition.MetadataPanel;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.acquisition.VirtualAcquisitionDisplay;
import org.micromanager.utils.ImageFocusListener;
import org.micromanager.api.Pipeline;
import org.micromanager.api.TaggedImageStorage;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.HotKeysDialog;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMKeyDispatcher;
import org.micromanager.utils.ReportingUtils;
/*
* Main panel and application class for the MMStudio.
*/
public class MMStudioMainFrame extends JFrame implements DeviceControlGUI, ScriptInterface {
private static final String MICRO_MANAGER_TITLE = "Micro-Manager 1.4";
private static final String VERSION = "1.4.7 20111110";
private static final long serialVersionUID = 3556500289598574541L;
private static final String MAIN_FRAME_X = "x";
private static final String MAIN_FRAME_Y = "y";
private static final String MAIN_FRAME_WIDTH = "width";
private static final String MAIN_FRAME_HEIGHT = "height";
private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos";
private static final String MAIN_EXPOSURE = "exposure";
private static final String SYSTEM_CONFIG_FILE = "sysconfig_file";
private static final String MAIN_STRETCH_CONTRAST = "stretch_contrast";
private static final String MAIN_REJECT_OUTLIERS = "reject_outliers";
private static final String MAIN_REJECT_FRACTION = "reject_fraction";
private static final String CONTRAST_SETTINGS_8_MIN = "contrast8_MIN";
private static final String CONTRAST_SETTINGS_8_MAX = "contrast8_MAX";
private static final String CONTRAST_SETTINGS_16_MIN = "contrast16_MIN";
private static final String CONTRAST_SETTINGS_16_MAX = "contrast16_MAX";
private static final String OPEN_ACQ_DIR = "openDataDir";
private static final String SCRIPT_CORE_OBJECT = "mmc";
private static final String SCRIPT_ACQENG_OBJECT = "acq";
private static final String SCRIPT_GUI_OBJECT = "gui";
private static final String AUTOFOCUS_DEVICE = "autofocus_device";
private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage";
private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000;
private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000;
// cfg file saving
private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4}
// GUI components
private JComboBox comboBinning_;
private JComboBox shutterComboBox_;
private JTextField textFieldExp_;
private JLabel labelImageDimensions_;
private JToggleButton toggleButtonLive_;
private JCheckBox autoShutterCheckBox_;
private boolean shutterOriginalState_;
private MMOptions options_;
private boolean runsAsPlugin_;
private JCheckBoxMenuItem centerAndDragMenuItem_;
private JButton buttonSnap_;
private JButton buttonAutofocus_;
private JButton buttonAutofocusTools_;
private JToggleButton toggleButtonShutter_;
private GUIColors guiColors_;
private GraphFrame profileWin_;
private PropertyEditor propertyBrowser_;
private CalibrationListDlg calibrationListDlg_;
private AcqControlDlg acqControlWin_;
private ReportProblemDialog reportProblemDialog_;
private JMenu pluginMenu_;
private ArrayList<PluginItem> plugins_;
private List<MMListenerInterface> MMListeners_
= (List<MMListenerInterface>)
Collections.synchronizedList(new ArrayList<MMListenerInterface>());
private List<Component> MMFrames_
= (List<Component>)
Collections.synchronizedList(new ArrayList<Component>());
private AutofocusManager afMgr_;
private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg";
private ArrayList<String> MRUConfigFiles_;
private static final int maxMRUCfgs_ = 5;
private String sysConfigFile_;
private String startupScriptFile_;
private String sysStateFile_ = "MMSystemState.cfg";
private ConfigGroupPad configPad_;
private ContrastPanel contrastPanel_;
// Timer interval - image display interval
private double liveModeInterval_ = 40;
private LiveModeTimer liveModeTimer_;
private GraphData lineProfileData_;
// labels for standard devices
private String cameraLabel_;
private String zStageLabel_;
private String shutterLabel_;
private String xyStageLabel_;
// applications settings
private Preferences mainPrefs_;
private Preferences systemPrefs_;
private Preferences colorPrefs_;
// MMcore
private CMMCore core_;
private AcquisitionEngine engine_;
private PositionList posList_;
private PositionListDlg posListDlg_;
private String openAcqDirectory_ = "";
private boolean running_;
private boolean configChanged_ = false;
private StrVector shutters_ = null;
private JButton saveConfigButton_;
private ScriptPanel scriptPanel_;
private org.micromanager.utils.HotKeys hotKeys_;
private CenterAndDragListener centerAndDragListener_;
private ZWheelListener zWheelListener_;
private XYZKeyListener xyzKeyListener_;
private AcquisitionManager acqMgr_;
private static MMImageWindow imageWin_;
private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN};
private boolean multiChannelCamera_ = false;
private long multiChannelCameraNrCh_ = 0;
private int snapCount_ = -1;
private boolean liveModeSuspended_;
public Font defaultScriptFont_ = null;
public static final String MULTI_CAMERA_ACQ = "Multi-Camera Snap";
public static final String RGB_ACQ = "RGB-Camera Acquisition";
public static FileType MM_CONFIG_FILE
= new FileType("MM_CONFIG_FILE",
"Micro-Manager Config File",
"./MyScope.cfg",
true, "cfg");
// Our instance
private static MMStudioMainFrame gui_;
// Callback
private CoreEventCallback cb_;
// Lock invoked while shutting down
private final Object shutdownLock_ = new Object();
private JMenuBar menuBar_;
private ConfigPadButtonPanel configPadButtonPanel_;
private final JMenu switchConfigurationMenu_;
private final MetadataPanel metadataPanel_;
public static FileType MM_DATA_SET
= new FileType("MM_DATA_SET",
"Micro-Manager Image Location",
System.getProperty("user.home") + "/Untitled",
false, (String[]) null);
private Thread pipelineClassLoadingThread_ = null;
private Class pipelineClass_ = null;
private Pipeline acquirePipeline_ = null;
private final JSplitPane splitPane_;
private volatile boolean ignorePropertyChanges_;
public ImageWindow getImageWin() {
return imageWin_;
}
public static MMImageWindow getLiveWin() {
return imageWin_;
}
private void doSnapColor() {
checkRGBAcquisition();
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
core_.snapImage();
getAcquisition(RGB_ACQ).toFront();
TaggedImage ti = ImageUtils.makeTaggedImage(core_.getImage(),
0,
0,
0,
0,
getAcquisitionImageWidth(RGB_ACQ),
getAcquisitionImageHeight(RGB_ACQ),
getAcquisitionImageByteDepth(RGB_ACQ) );
addImage(RGB_ACQ,ti, true, true, false);
getAcquisition(RGB_ACQ).getAcquisitionWindow().setWindowTitle("RGB Snap");
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
private void doSnapFloat() {
try {
// just a test harness
core_.snapImage();
byte[] byteImage = (byte[]) core_.getImage();
int ii = (int)core_.getImageWidth();
int jj = (int)core_.getImageHeight();
int npoints = ii*jj;
float[] floatImage = new float[npoints];
ImagePlus implus = new ImagePlus();
int iiterator = 0;
int oiterator = 0;
for (; oiterator < npoints; ++oiterator) {
floatImage[oiterator] = Float.intBitsToFloat(((int) byteImage[iiterator+3 ] << 24) + ((int) byteImage[iiterator + 2] << 16) + ((int) byteImage[iiterator + 1] << 8) + (int) byteImage[iiterator]);
iiterator += 4;
}
FloatProcessor fp = new FloatProcessor(ii, jj, floatImage, null);
implus.setProcessor(fp);
ImageWindow iwindow = new ImageWindow(implus);
WindowManager.setCurrentWindow(iwindow);
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
private void doSnapMonochrome() {
try {
Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitCursor);
if (!isImageWindowOpen()) {
imageWin_ = createImageWindow();
}
if (imageWin_ == null) {
return;
}
imageWin_.toFront();
setIJCal(imageWin_);
// this is needed to clear the subtite, should be folded into
// drawInfo
imageWin_.getGraphics().clearRect(0, 0, imageWin_.getWidth(), 40);
imageWin_.drawInfo(imageWin_.getGraphics());
imageWin_.setSubTitle("Snap");
String expStr = textFieldExp_.getText();
if (expStr.length() > 0) {
core_.setExposure(NumberUtils.displayStringToDouble(expStr));
updateImage();
} else {
handleError("Exposure field is empty!");
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
private void checkMultiChannelWindow()
{
int w = (int) core_.getImageWidth();
int h = (int) core_.getImageHeight();
int d = (int) core_.getBytesPerPixel();
long c = core_.getNumberOfCameraChannels();
if (c > 1)
{
try {
ArrayList<String> chNames = new ArrayList<String>();
for (long i = 0; i < c; i++) {
chNames.add(core_.getCameraChannelName(i));
}
if (acquisitionExists(MULTI_CAMERA_ACQ)) {
if (c != (getAcquisition(MULTI_CAMERA_ACQ)).getChannels()) {
closeAcquisitionImage5D(MULTI_CAMERA_ACQ);
closeAcquisition(MULTI_CAMERA_ACQ);
}
if ( (getAcquisitionImageWidth(MULTI_CAMERA_ACQ) != w) ||
(getAcquisitionImageHeight(MULTI_CAMERA_ACQ) != h) ||
(getAcquisitionImageByteDepth(MULTI_CAMERA_ACQ) != d) ) {
closeAcquisitionImage5D(MULTI_CAMERA_ACQ);
closeAcquisition(MULTI_CAMERA_ACQ);
}
}
if (!acquisitionExists(MULTI_CAMERA_ACQ)) {
openAcquisition(MULTI_CAMERA_ACQ, "", 1, (int) c, 1, true);
for (long i = 0; i < c; i++) {
String chName = core_.getCameraChannelName(i);
int defaultColor = multiCameraColors_[(int)i % multiCameraColors_.length].getRGB();
setChannelColor(MULTI_CAMERA_ACQ, (int) i,
getChannelColor(chName, defaultColor) );
setChannelName(MULTI_CAMERA_ACQ, (int) i, chName);
}
initializeAcquisition(MULTI_CAMERA_ACQ, w, h, d);
getAcquisition(MULTI_CAMERA_ACQ).promptToSave(false);
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
}
private void checkRGBAcquisition()
{
int w = (int) core_.getImageWidth();
int h = (int) core_.getImageHeight();
int d = (int) core_.getBytesPerPixel();
try {
if (acquisitionExists(RGB_ACQ)) {
if ( (getAcquisitionImageWidth(RGB_ACQ) != w) ||
(getAcquisitionImageHeight(RGB_ACQ) != h) ||
(getAcquisitionImageByteDepth(RGB_ACQ) != d) )
{
closeAcquisitionImage5D(RGB_ACQ);
closeAcquisition(RGB_ACQ);
openAcquisition(RGB_ACQ, "", 1, 1, 1, true);
initializeAcquisition(RGB_ACQ, w, h, d);
getAcquisition(RGB_ACQ).promptToSave(false);
}
} else {
openAcquisition(RGB_ACQ, "", 1, 1, 1, true); //creates new acquisition
initializeAcquisition(RGB_ACQ, w, h, d);
getAcquisition(RGB_ACQ).promptToSave(false);
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
public void saveChannelColor(String chName, int rgb)
{
if (colorPrefs_ != null) {
colorPrefs_.putInt("Color_" + chName, rgb);
}
}
public Color getChannelColor(String chName, int defaultColor)
{
if (colorPrefs_ != null) {
defaultColor = colorPrefs_.getInt("Color_" + chName, defaultColor);
}
return new Color(defaultColor);
}
/**
* Snaps an image for a multi-Channel camera
* This version does not (yet) support attachment of mouse listeners
* for stage movement.
*/
private void doSnapMultiCamera()
{
checkMultiChannelWindow();
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
core_.snapImage();
getAcquisition(MULTI_CAMERA_ACQ).toFront();
long c = core_.getNumberOfCameraChannels();
for (int i = 0; i < c; i++) {
TaggedImage ti = ImageUtils.makeTaggedImage(core_.getImage(i),
i,
0,
0,
0,
getAcquisitionImageWidth(MULTI_CAMERA_ACQ),
getAcquisitionImageHeight(MULTI_CAMERA_ACQ),
getAcquisitionImageByteDepth(MULTI_CAMERA_ACQ) );
boolean update = false;
if (i == c -1)
update = true;
addImage(MULTI_CAMERA_ACQ,ti, update, true, false);
getAcquisition(MULTI_CAMERA_ACQ).getAcquisitionWindow().setWindowTitle("Multi Camera Snap");
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
private void initializeHelpMenu() {
// add help menu item
final JMenu helpMenu = new JMenu();
helpMenu.setText("Help");
menuBar_.add(helpMenu);
final JMenuItem usersGuideMenuItem = new JMenuItem();
usersGuideMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_User%27s_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
usersGuideMenuItem.setText("User's Guide...");
helpMenu.add(usersGuideMenuItem);
final JMenuItem configGuideMenuItem = new JMenuItem();
configGuideMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_Configuration_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
configGuideMenuItem.setText("Configuration Guide...");
helpMenu.add(configGuideMenuItem);
if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) {
final JMenuItem registerMenuItem = new JMenuItem();
registerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_);
regDlg.setVisible(true);
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
});
registerMenuItem.setText("Register your copy of Micro-Manager...");
helpMenu.add(registerMenuItem);
}
final MMStudioMainFrame thisFrame = this;
final JMenuItem reportProblemMenuItem = new JMenuItem();
reportProblemMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (null == reportProblemDialog_) {
reportProblemDialog_ = new ReportProblemDialog(core_, thisFrame, sysConfigFile_, options_);
thisFrame.addMMBackgroundListener(reportProblemDialog_);
reportProblemDialog_.setBackground(guiColors_.background.get(options_.displayBackground_));
}
reportProblemDialog_.setVisible(true);
}
});
reportProblemMenuItem.setText("Report Problem");
helpMenu.add(reportProblemMenuItem);
final JMenuItem aboutMenuItem = new JMenuItem();
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MMAboutDlg dlg = new MMAboutDlg();
String versionInfo = "MM Studio version: " + VERSION;
versionInfo += "\n" + core_.getVersionInfo();
versionInfo += "\n" + core_.getAPIVersionInfo();
versionInfo += "\nUser: " + core_.getUserId();
versionInfo += "\nHost: " + core_.getHostName();
dlg.setVersionInfo(versionInfo);
dlg.setVisible(true);
}
});
aboutMenuItem.setText("About Micromanager...");
helpMenu.add(aboutMenuItem);
menuBar_.validate();
}
private void updateSwitchConfigurationMenu() {
switchConfigurationMenu_.removeAll();
for (final String configFile : MRUConfigFiles_) {
if (! configFile.equals(sysConfigFile_)) {
JMenuItem configMenuItem = new JMenuItem();
configMenuItem.setText(configFile);
configMenuItem.addActionListener(new ActionListener() {
String theConfigFile = configFile;
public void actionPerformed(ActionEvent e) {
sysConfigFile_ = theConfigFile;
loadSystemConfiguration();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
}
});
switchConfigurationMenu_.add(configMenuItem);
}
}
}
/**
* Allows MMListeners to register themselves
*/
public void addMMListener(MMListenerInterface newL) {
if (MMListeners_.contains(newL))
return;
MMListeners_.add(newL);
}
/**
* Allows MMListeners to remove themselves
*/
public void removeMMListener(MMListenerInterface oldL) {
if (!MMListeners_.contains(oldL))
return;
MMListeners_.remove(oldL);
}
/**
* Lets JComponents register themselves so that their background can be
* manipulated
*/
public void addMMBackgroundListener(Component comp) {
if (MMFrames_.contains(comp))
return;
MMFrames_.add(comp);
}
/**
* Lets JComponents remove themselves from the list whose background gets
* changes
*/
public void removeMMBackgroundListener(Component comp) {
if (!MMFrames_.contains(comp))
return;
MMFrames_.remove(comp);
}
public void updateContrast(ImagePlus iplus) {
contrastPanel_.updateContrast(iplus);
}
/**
* Part of ScriptInterface
* Manipulate acquisition so that it looks like a burst
*/
public void runBurstAcquisition() throws MMScriptException {
double interval = engine_.getFrameIntervalMs();
int nr = engine_.getNumFrames();
boolean doZStack = engine_.isZSliceSettingEnabled();
boolean doChannels = engine_.isChannelsSettingEnabled();
engine_.enableZSliceSetting(false);
engine_.setFrames(nr, 0);
engine_.enableChannelsSetting(false);
try {
engine_.acquire();
} catch (MMException e) {
throw new MMScriptException(e);
}
engine_.setFrames(nr, interval);
engine_.enableZSliceSetting(doZStack);
engine_.enableChannelsSetting(doChannels);
}
public void runBurstAcquisition(int nr) throws MMScriptException {
int originalNr = engine_.getNumFrames();
double interval = engine_.getFrameIntervalMs();
engine_.setFrames(nr, 0);
this.runBurstAcquisition();
engine_.setFrames(originalNr, interval);
}
public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException {
//String originalName = engine_.getDirName();
String originalRoot = engine_.getRootName();
engine_.setDirName(name);
engine_.setRootName(root);
this.runBurstAcquisition(nr);
engine_.setRootName(originalRoot);
//engine_.setDirName(originalDirName);
}
/**
* @deprecated
* @throws MMScriptException
*/
public void startBurstAcquisition() throws MMScriptException {
runAcquisition();
}
public boolean isBurstAcquisitionRunning() throws MMScriptException {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
private void startLoadingPipelineClass() {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
pipelineClassLoadingThread_ = new Thread("Pipeline Class loading thread") {
@Override
public void run() {
try {
pipelineClass_ = Class.forName("org.micromanager.AcqEngine");
} catch (Exception ex) {
ReportingUtils.logError(ex);
pipelineClass_ = null;
}
}
};
pipelineClassLoadingThread_.start();
}
public void addImageStorageListener(ImageCacheListener listener) {
throw new UnsupportedOperationException("Not supported yet.");
}
public ImageCache getAcquisitionImageCache(String acquisitionName) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Callback to update GUI when a change happens in the MMCore.
*/
public class CoreEventCallback extends MMEventCallback {
public CoreEventCallback() {
super();
}
@Override
public void onPropertiesChanged() {
// TODO: remove test once acquisition engine is fully multithreaded
if (engine_ != null && engine_.isAcquisitionRunning()) {
core_.logMessage("Notification from MMCore ignored because acquistion is running!");
} else {
if (ignorePropertyChanges_) {
core_.logMessage("Notification from MMCore ignored since the system is still loading");
} else {
core_.updateSystemStateCache();
updateGUI(true);
// update all registered listeners
for (MMListenerInterface mmIntf : MMListeners_) {
mmIntf.propertiesChangedAlert();
}
core_.logMessage("Notification from MMCore!");
}
}
}
@Override
public void onPropertyChanged(String deviceName, String propName, String propValue) {
core_.logMessage("Notification for Device: " + deviceName + " Property: " +
propName + " changed to value: " + propValue);
// update all registered listeners
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.propertyChangedAlert(deviceName, propName, propValue);
}
}
@Override
public void onConfigGroupChanged(String groupName, String newConfig) {
try {
configPad_.refreshGroup(groupName, newConfig);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.configGroupChangedAlert(groupName, newConfig);
}
} catch (Exception e) {
}
}
@Override
public void onPixelSizeChanged(double newPixelSizeUm) {
updatePixSizeUm (newPixelSizeUm);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.pixelSizeChangedAlert(newPixelSizeUm);
}
}
@Override
public void onStagePositionChanged(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_)) {
updateZPos(pos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.stagePositionChangedAlert(deviceName, pos);
}
}
}
@Override
public void onStagePositionChangedRelative(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_))
updateZPosRelative(pos);
}
@Override
public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_)) {
updateXYPos(xPos, yPos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.xyStagePositionChanged(deviceName, xPos, yPos);
}
}
}
@Override
public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_))
updateXYPosRelative(xPos, yPos);
}
}
private class PluginItem {
public Class<?> pluginClass = null;
public String menuItem = "undefined";
public MMPlugin plugin = null;
public String className = "";
public void instantiate() {
try {
if (plugin == null) {
plugin = (MMPlugin) pluginClass.newInstance();
}
} catch (InstantiationException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
plugin.setApp(MMStudioMainFrame.this);
}
}
/*
* Simple class used to cache static info
*/
private class StaticInfo {
public long width_;
public long height_;
public long bytesPerPixel_;
public long imageBitDepth_;
public double pixSizeUm_;
public double zPos_;
public double x_;
public double y_;
}
private StaticInfo staticInfo_ = new StaticInfo();
/**
* Main procedure for stand alone operation.
*/
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MMStudioMainFrame frame = new MMStudioMainFrame(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
} catch (Throwable e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
}
}
public MMStudioMainFrame(boolean pluginStatus) {
super();
startLoadingPipelineClass();
options_ = new MMOptions();
try {
options_.loadSettings();
} catch (NullPointerException ex) {
ReportingUtils.logError(ex);
}
guiColors_ = new GUIColors();
plugins_ = new ArrayList<PluginItem>();
gui_ = this;
runsAsPlugin_ = pluginStatus;
setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class,
"icons/microscope.gif"));
running_ = true;
acqMgr_ = new AcquisitionManager();
sysConfigFile_ = System.getProperty("user.dir") + "/"
+ DEFAULT_CONFIG_FILE_NAME;
if (options_.startupScript_.length() > 0) {
startupScriptFile_ = System.getProperty("user.dir") + "/"
+ options_.startupScript_;
} else {
startupScriptFile_ = "";
}
ReportingUtils.SetContainingFrame(gui_);
// set the location for app preferences
try {
mainPrefs_ = Preferences.userNodeForPackage(this.getClass());
} catch (Exception e) {
ReportingUtils.logError(e);
}
systemPrefs_ = mainPrefs_;
colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
AcqControlDlg.COLOR_SETTINGS_NODE);
// check system preferences
try {
Preferences p = Preferences.systemNodeForPackage(this.getClass());
if (null != p) {
// if we can not write to the systemPrefs, use AppPrefs instead
if (JavaUtils.backingStoreAvailable(p)) {
systemPrefs_ = p;
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
// show registration dialog if not already registered
// first check user preferences (for legacy compatibility reasons)
boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,
false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!userReg) {
boolean systemReg = systemPrefs_.getBoolean(
RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!systemReg) {
// prompt for registration info
RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);
dlg.setVisible(true);
}
}
// load application preferences
// NOTE: only window size and position preferences are loaded,
// not the settings for the camera and live imaging -
// attempting to set those automatically on startup may cause problems
// with the hardware
int x = mainPrefs_.getInt(MAIN_FRAME_X, 100);
int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100);
int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 580);
int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 482);
boolean stretch = mainPrefs_.getBoolean(MAIN_STRETCH_CONTRAST, true);
boolean reject = mainPrefs_.getBoolean(MAIN_REJECT_OUTLIERS, false);
double rejectFract = mainPrefs_.getDouble(MAIN_REJECT_FRACTION, 0.027);
int dividerPos = mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 178);
openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, "");
ToolTipManager ttManager = ToolTipManager.sharedInstance();
ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS);
ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS);
setBounds(x, y, width, height);
setExitStrategy(options_.closeOnExit_);
setTitle(MICRO_MANAGER_TITLE);
setBackground(guiColors_.background.get((options_.displayBackground_)));
SpringLayout topLayout = new SpringLayout();
this.setMinimumSize(new Dimension(580,480));
JPanel topPanel = new JPanel();
topPanel.setLayout(topLayout);
topPanel.setMinimumSize(new Dimension(580, 175));
class ListeningJPanel extends JPanel implements AncestorListener {
public void ancestorMoved(AncestorEvent event) {
//System.out.println("moved!");
}
public void ancestorRemoved(AncestorEvent event) {}
public void ancestorAdded(AncestorEvent event) {}
}
ListeningJPanel bottomPanel = new ListeningJPanel();
bottomPanel.setLayout(topLayout);
splitPane_ = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
topPanel, bottomPanel);
splitPane_.setBorder(BorderFactory.createEmptyBorder());
splitPane_.setDividerLocation(dividerPos);
splitPane_.setResizeWeight(0.0);
splitPane_.addAncestorListener(bottomPanel);
getContentPane().add(splitPane_);
// Snap button
// -----------
buttonSnap_ = new JButton();
buttonSnap_.setIconTextGap(6);
buttonSnap_.setText("Snap");
buttonSnap_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/camera.png"));
buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonSnap_.setToolTipText("Snap single image");
buttonSnap_.setMaximumSize(new Dimension(0, 0));
buttonSnap_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSnap();
}
});
topPanel.add(buttonSnap_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonSnap_, 4,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonSnap_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonSnap_, 7,
SpringLayout.WEST, topPanel);
// Initialize
// ----------
// Exposure field
// ---------------
final JLabel label_1 = new JLabel();
label_1.setFont(new Font("Arial", Font.PLAIN, 10));
label_1.setText("Exposure [ms]");
topPanel.add(label_1);
topLayout.putConstraint(SpringLayout.EAST, label_1, 198,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, label_1, 111,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, label_1, 39,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, label_1, 23,
SpringLayout.NORTH, topPanel);
textFieldExp_ = new JTextField();
textFieldExp_.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent fe) {
synchronized(shutdownLock_) {
if (core_ != null)
setExposure();
}
}
});
textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10));
textFieldExp_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setExposure();
}
});
topPanel.add(textFieldExp_);
topLayout.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, textFieldExp_, 21,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, textFieldExp_, 276,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, textFieldExp_, 203,
SpringLayout.WEST, topPanel);
// Live button
// -----------
toggleButtonLive_ = new JToggleButton();
toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2));
toggleButtonLive_.setIconTextGap(1);
toggleButtonLive_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setIconTextGap(6);
toggleButtonLive_.setToolTipText("Continuous live view");
toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10));
toggleButtonLive_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!isLiveModeOn()) {
// Display interval for Live Mode changes as well
setLiveModeInterval();
}
enableLiveMode(!isLiveModeOn());
}
});
toggleButtonLive_.setText("Live");
topPanel.add(toggleButtonLive_);
topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7,
SpringLayout.WEST, topPanel);
// Acquire button
// -----------
JButton acquireButton = new JButton();
acquireButton.setMargin(new Insets(2, 2, 2, 2));
acquireButton.setIconTextGap(1);
acquireButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/snapAppend.png"));
acquireButton.setIconTextGap(6);
acquireButton.setToolTipText("Acquire single frame and add to an album");
acquireButton.setFont(new Font("Arial", Font.PLAIN, 10));
acquireButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snapAndAddToImage5D();
}
});
acquireButton.setText("Acquire");
topPanel.add(acquireButton);
topLayout.putConstraint(SpringLayout.SOUTH, acquireButton, 69,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, acquireButton, 48,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, acquireButton, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, acquireButton, 7,
SpringLayout.WEST, topPanel);
// Shutter button
// --------------
toggleButtonShutter_ = new JToggleButton();
toggleButtonShutter_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
toggleShutter();
}
});
toggleButtonShutter_.setToolTipText("Open/close the shutter");
toggleButtonShutter_.setIconTextGap(6);
toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10));
toggleButtonShutter_.setText("Open");
topPanel.add(toggleButtonShutter_);
topLayout.putConstraint(SpringLayout.EAST, toggleButtonShutter_,
275, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toggleButtonShutter_,
203, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_,
138 - 21, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toggleButtonShutter_,
117 - 21, SpringLayout.NORTH, topPanel);
// Active shutter label
final JLabel activeShutterLabel = new JLabel();
activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10));
activeShutterLabel.setText("Shutter");
topPanel.add(activeShutterLabel);
topLayout.putConstraint(SpringLayout.SOUTH, activeShutterLabel,
108 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, activeShutterLabel,
95 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, activeShutterLabel,
160 - 2, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, activeShutterLabel,
113 - 2, SpringLayout.WEST, topPanel);
// Active shutter Combo Box
shutterComboBox_ = new JComboBox();
shutterComboBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
if (shutterComboBox_.getSelectedItem() != null) {
core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
return;
}
});
topPanel.add(shutterComboBox_);
topLayout.putConstraint(SpringLayout.SOUTH, shutterComboBox_,
114 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, shutterComboBox_,
92 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, shutterComboBox_, 275,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, shutterComboBox_, 170,
SpringLayout.WEST, topPanel);
menuBar_ = new JMenuBar();
setJMenuBar(menuBar_);
final JMenu fileMenu = new JMenu();
fileMenu.setText("File");
menuBar_.add(fileMenu);
final JMenuItem openMenuItem = new JMenuItem();
openMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
openAcquisitionData();
}
}.start();
}
});
openMenuItem.setText("Open Acquisition Data...");
fileMenu.add(openMenuItem);
fileMenu.addSeparator();
final JMenuItem loadState = new JMenuItem();
loadState.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemState();
}
});
loadState.setText("Load System State...");
fileMenu.add(loadState);
final JMenuItem saveStateAs = new JMenuItem();
fileMenu.add(saveStateAs);
saveStateAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveSystemState();
}
});
saveStateAs.setText("Save System State As...");
fileMenu.addSeparator();
final JMenuItem exitMenuItem = new JMenuItem();
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeSequence();
}
});
fileMenu.add(exitMenuItem);
exitMenuItem.setText("Exit");
/*
final JMenu image5dMenu = new JMenu();
image5dMenu.setText("Image5D");
menuBar_.add(image5dMenu);
final JMenuItem closeAllMenuItem = new JMenuItem();
closeAllMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
WindowManager.closeAllWindows();
}
});
closeAllMenuItem.setText("Close All");
image5dMenu.add(closeAllMenuItem);
final JMenuItem duplicateMenuItem = new JMenuItem();
duplicateMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Duplicate_Image5D duplicate = new Duplicate_Image5D();
duplicate.run("");
}
});
duplicateMenuItem.setText("Duplicate");
image5dMenu.add(duplicateMenuItem);
final JMenuItem cropMenuItem = new JMenuItem();
cropMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Crop_Image5D crop = new Crop_Image5D();
crop.run("");
}
});
cropMenuItem.setText("Crop");
image5dMenu.add(cropMenuItem);
final JMenuItem makeMontageMenuItem = new JMenuItem();
makeMontageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Make_Montage makeMontage = new Make_Montage();
makeMontage.run("");
}
});
makeMontageMenuItem.setText("Make Montage");
image5dMenu.add(makeMontageMenuItem);
final JMenuItem zProjectMenuItem = new JMenuItem();
zProjectMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Z_Project projection = new Z_Project();
projection.run("");
}
});
zProjectMenuItem.setText("Z Project");
image5dMenu.add(zProjectMenuItem);
final JMenuItem convertToRgbMenuItem = new JMenuItem();
convertToRgbMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB();
stackToRGB.run("");
}
});
convertToRgbMenuItem.setText("Copy to RGB Stack(z)");
image5dMenu.add(convertToRgbMenuItem);
final JMenuItem convertToRgbtMenuItem = new JMenuItem();
convertToRgbtMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t();
stackToRGB_t.run("");
}
});
convertToRgbtMenuItem.setText("Copy to RGB Stack(t)");
image5dMenu.add(convertToRgbtMenuItem);
final JMenuItem convertToStackMenuItem = new JMenuItem();
convertToStackMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_Stack image5DToStack = new Image5D_to_Stack();
image5DToStack.run("");
}
});
convertToStackMenuItem.setText("Copy to Stack");
image5dMenu.add(convertToStackMenuItem);
final JMenuItem convertToStacksMenuItem = new JMenuItem();
convertToStacksMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks();
image5DToStacks.run("");
}
});
convertToStacksMenuItem.setText("Copy to Stacks (channels)");
image5dMenu.add(convertToStacksMenuItem);
final JMenuItem volumeViewerMenuItem = new JMenuItem();
volumeViewerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer();
volumeViewer.run("");
}
});
volumeViewerMenuItem.setText("VolumeViewer");
image5dMenu.add(volumeViewerMenuItem);
final JMenuItem splitImageMenuItem = new JMenuItem();
splitImageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Split_Image5D splitImage = new Split_Image5D();
splitImage.run("");
}
});
splitImageMenuItem.setText("SplitView");
image5dMenu.add(splitImageMenuItem);
*/
final JMenu toolsMenu = new JMenu();
toolsMenu.setText("Tools");
menuBar_.add(toolsMenu);
final JMenuItem refreshMenuItem = new JMenuItem();
refreshMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/arrow_refresh.png"));
refreshMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.updateSystemStateCache();
updateGUI(true);
}
});
refreshMenuItem.setText("Refresh GUI");
refreshMenuItem.setToolTipText("Refresh all GUI controls directly from the hardware");
toolsMenu.add(refreshMenuItem);
final JMenuItem rebuildGuiMenuItem = new JMenuItem();
rebuildGuiMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
initializeGUI();
core_.updateSystemStateCache();
}
});
rebuildGuiMenuItem.setText("Rebuild GUI");
rebuildGuiMenuItem.setToolTipText("Regenerate micromanager user interface");
toolsMenu.add(rebuildGuiMenuItem);
toolsMenu.addSeparator();
final JMenuItem scriptPanelMenuItem = new JMenuItem();
toolsMenu.add(scriptPanelMenuItem);
scriptPanelMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scriptPanel_.setVisible(true);
}
});
scriptPanelMenuItem.setText("Script Panel...");
scriptPanelMenuItem.setToolTipText("Open micromanager script editor window");
final JMenuItem hotKeysMenuItem = new JMenuItem();
toolsMenu.add(hotKeysMenuItem);
hotKeysMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
HotKeysDialog hk = new HotKeysDialog
(guiColors_.background.get((options_.displayBackground_)));
//hk.setBackground(guiColors_.background.get((options_.displayBackground_)));
}
});
hotKeysMenuItem.setText("Shortcuts...");
hotKeysMenuItem.setToolTipText("Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts");
final JMenuItem propertyEditorMenuItem = new JMenuItem();
toolsMenu.add(propertyEditorMenuItem);
propertyEditorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createPropertyEditor();
}
});
propertyEditorMenuItem.setText("Device/Property Browser...");
propertyEditorMenuItem.setToolTipText("Open new window to view and edit property values in current configuration");
toolsMenu.addSeparator();
final JMenuItem xyListMenuItem = new JMenuItem();
xyListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showXYPositionList();
}
});
xyListMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/application_view_list.png"));
xyListMenuItem.setText("XY List...");
toolsMenu.add(xyListMenuItem);
xyListMenuItem.setToolTipText("Open position list manager window");
final JMenuItem acquisitionMenuItem = new JMenuItem();
acquisitionMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
acquisitionMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/film.png"));
acquisitionMenuItem.setText("Multi-Dimensional Acquisition...");
toolsMenu.add(acquisitionMenuItem);
acquisitionMenuItem.setToolTipText("Open multi-dimensional acquisition window");
/*
final JMenuItem splitViewMenuItem = new JMenuItem();
splitViewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
splitViewDialog();
}
});
splitViewMenuItem.setText("Split View...");
toolsMenu.add(splitViewMenuItem);
*/
centerAndDragMenuItem_ = new JCheckBoxMenuItem();
centerAndDragMenuItem_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (centerAndDragListener_ == null) {
centerAndDragListener_ = new CenterAndDragListener(core_, gui_);
}
if (!centerAndDragListener_.isRunning()) {
centerAndDragListener_.start();
centerAndDragMenuItem_.setSelected(true);
} else {
centerAndDragListener_.stop();
centerAndDragMenuItem_.setSelected(false);
}
mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected());
}
});
centerAndDragMenuItem_.setText("Mouse Moves Stage");
centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false));
centerAndDragMenuItem_.setToolTipText("When enabled, double clicking in live window moves stage");
toolsMenu.add(centerAndDragMenuItem_);
final JMenuItem calibrationMenuItem = new JMenuItem();
toolsMenu.add(calibrationMenuItem);
calibrationMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createCalibrationListDlg();
}
});
calibrationMenuItem.setText("Pixel Size Calibration...");
toolsMenu.add(calibrationMenuItem);
String calibrationTooltip = "Define size calibrations specific to each objective lens. " +
"When the objective in use has a calibration defined, " +
"micromanager will automatically use it when " +
"calculating metadata";
String mrjProp = System.getProperty("mrj.version");
if (mrjProp != null && !mrjProp.equals(null)) // running on a mac
calibrationMenuItem.setToolTipText(calibrationTooltip);
else
calibrationMenuItem.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip(calibrationTooltip));
toolsMenu.addSeparator();
final JMenuItem configuratorMenuItem = new JMenuItem();
configuratorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// true - new wizard
// false - old wizard
runHardwareWizard(false);
}
});
configuratorMenuItem.setText("Hardware Configuration Wizard...");
toolsMenu.add(configuratorMenuItem);
configuratorMenuItem.setToolTipText("Open wizard to create new hardware configuration");
final JMenuItem loadSystemConfigMenuItem = new JMenuItem();
toolsMenu.add(loadSystemConfigMenuItem);
loadSystemConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadConfiguration();
initializeGUI();
}
});
loadSystemConfigMenuItem.setText("Load Hardware Configuration...");
loadSystemConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize new one");
switchConfigurationMenu_ = new JMenu();
for (int i=0; i<5; i++)
{
JMenuItem configItem = new JMenuItem();
configItem.setText(Integer.toString(i));
switchConfigurationMenu_.add(configItem);
}
final JMenuItem reloadConfigMenuItem = new JMenuItem();
toolsMenu.add(reloadConfigMenuItem);
reloadConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemConfiguration();
initializeGUI();
}
});
reloadConfigMenuItem.setText("Reload Hardware Configuration");
reloadConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize most recently loaded configuration");
switchConfigurationMenu_.setText("Switch Hardware Configuration");
toolsMenu.add(switchConfigurationMenu_);
switchConfigurationMenu_.setToolTipText("Switch between recently used configurations");
final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem();
saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
updateChannelCombos();
}
});
saveConfigurationPresetsMenuItem.setText("Save Configuration Settings as...");
toolsMenu.add(saveConfigurationPresetsMenuItem);
saveConfigurationPresetsMenuItem.setToolTipText("Save current configuration settings as new configuration file");
/*
final JMenuItem regenerateConfiguratorDeviceListMenuItem = new JMenuItem();
regenerateConfiguratorDeviceListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(options_.enableDeviceDiscovery_, resultFile,core_);
setCursor(oldc);
}
});
regenerateConfiguratorDeviceListMenuItem.setText("Regenerate Configurator Device List");
toolsMenu.add(regenerateConfiguratorDeviceListMenuItem);
*/
toolsMenu.addSeparator();
final MMStudioMainFrame thisInstance = this;
final JMenuItem optionsMenuItem = new JMenuItem();
optionsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
int oldBufsize = options_.circularBufferSizeMB_;
OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_,
thisInstance, sysConfigFile_);
dlg.setVisible(true);
// adjust memory footprint if necessary
if (oldBufsize != options_.circularBufferSizeMB_) {
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception exc) {
ReportingUtils.showError(exc);
}
}
}
});
optionsMenuItem.setText("Options...");
toolsMenu.add(optionsMenuItem);
final JLabel binningLabel = new JLabel();
binningLabel.setFont(new Font("Arial", Font.PLAIN, 10));
binningLabel.setText("Binning");
topPanel.add(binningLabel);
topLayout.putConstraint(SpringLayout.SOUTH, binningLabel, 64,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, binningLabel, 43,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1,
SpringLayout.WEST, topPanel);
labelImageDimensions_ = new JLabel();
labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10));
bottomPanel.add(labelImageDimensions_);
topLayout.putConstraint(SpringLayout.SOUTH, labelImageDimensions_,
-5, SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, labelImageDimensions_,
-25, SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, labelImageDimensions_,
-5, SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, labelImageDimensions_,
5, SpringLayout.WEST, bottomPanel);
comboBinning_ = new JComboBox();
comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10));
comboBinning_.setMaximumRowCount(4);
comboBinning_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeBinning();
}
});
topPanel.add(comboBinning_);
topLayout.putConstraint(SpringLayout.EAST, comboBinning_, 275,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, comboBinning_, 200,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, comboBinning_, 66,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, comboBinning_, 43,
SpringLayout.NORTH, topPanel);
final JLabel cameraSettingsLabel = new JLabel();
cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11));
cameraSettingsLabel.setText("Camera settings");
topPanel.add(cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.EAST, cameraSettingsLabel,
211, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.WEST, cameraSettingsLabel,
109, SpringLayout.WEST, topPanel);
configPad_ = new ConfigGroupPad();
configPad_.setFont(new Font("", Font.PLAIN, 10));
topPanel.add(configPad_);
topLayout.putConstraint(SpringLayout.EAST, configPad_, -4,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, configPad_, 5,
SpringLayout.EAST, comboBinning_);
topLayout.putConstraint(SpringLayout.SOUTH, configPad_, -21,
SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, configPad_, 21,
SpringLayout.NORTH, topPanel);
configPadButtonPanel_ = new ConfigPadButtonPanel();
configPadButtonPanel_.setConfigPad(configPad_);
configPadButtonPanel_.setGUI(MMStudioMainFrame.this);
topPanel.add(configPadButtonPanel_);
topLayout.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5,
SpringLayout.EAST, comboBinning_);
topLayout.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, 0,
SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, -18,
SpringLayout.SOUTH, topPanel);
final JLabel stateDeviceLabel = new JLabel();
stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11));
stateDeviceLabel.setText("Configuration settings");
topPanel.add(stateDeviceLabel);
topLayout.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0,
SpringLayout.SOUTH, cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0,
SpringLayout.NORTH, cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150,
SpringLayout.WEST, configPad_);
topLayout.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0,
SpringLayout.WEST, configPad_);
final JButton buttonAcqSetup = new JButton();
buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2));
buttonAcqSetup.setIconTextGap(1);
buttonAcqSetup.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/film.png"));
buttonAcqSetup.setToolTipText("Open multi-dimensional acquisition window");
buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAcqSetup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
buttonAcqSetup.setText("Multi-D Acq.");
topPanel.add(buttonAcqSetup);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7,
SpringLayout.WEST, topPanel);
autoShutterCheckBox_ = new JCheckBox();
autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
autoShutterCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shutterLabel_ = core_.getShutterDevice();
if (shutterLabel_.length() == 0) {
toggleButtonShutter_.setEnabled(false);
return;
}
if (autoShutterCheckBox_.isSelected()) {
try {
core_.setAutoShutter(true);
core_.setShutterOpen(false);
toggleButtonShutter_.setSelected(false);
toggleButtonShutter_.setText("Open");
toggleButtonShutter_.setEnabled(false);
} catch (Exception e2) {
ReportingUtils.logError(e2);
}
} else {
try {
core_.setAutoShutter(false);
core_.setShutterOpen(false);
toggleButtonShutter_.setEnabled(true);
toggleButtonShutter_.setText("Open");
} catch (Exception exc) {
ReportingUtils.logError(exc);
}
}
}
});
autoShutterCheckBox_.setIconTextGap(6);
autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);
autoShutterCheckBox_.setText("Auto shutter");
topPanel.add(autoShutterCheckBox_);
topLayout.putConstraint(SpringLayout.EAST, autoShutterCheckBox_,
202 - 3, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, autoShutterCheckBox_,
110 - 3, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_,
141 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_,
118 - 22, SpringLayout.NORTH, topPanel);
final JButton refreshButton = new JButton();
refreshButton.setMargin(new Insets(2, 2, 2, 2));
refreshButton.setIconTextGap(1);
refreshButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_refresh.png"));
refreshButton.setFont(new Font("Arial", Font.PLAIN, 10));
refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware");
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.updateSystemStateCache();
updateGUI(true);
}
});
refreshButton.setText("Refresh");
topPanel.add(refreshButton);
topLayout.putConstraint(SpringLayout.SOUTH, refreshButton, 113,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, refreshButton, 92,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, refreshButton, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, refreshButton, 7,
SpringLayout.WEST, topPanel);
JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>");
topPanel.add(citePleaLabel);
citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11));
topLayout.putConstraint(SpringLayout.SOUTH, citePleaLabel, 139,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, citePleaLabel, 119,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, citePleaLabel, 270,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, citePleaLabel, 7,
SpringLayout.WEST, topPanel);
class Pleader extends Thread{
Pleader(){
super("pleader");
}
@Override
public void run(){
try {
ij.plugin.BrowserLauncher.openURL("https://valelab.ucsf.edu/~MM/MMwiki/index.php/Citing_Micro-Manager");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
}
citePleaLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Pleader p = new Pleader();
p.start();
}
});
// add window listeners
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeSequence();
running_ = false;
}
@Override
public void windowOpened(WindowEvent e) {
// -------------------
// initialize hardware
// -------------------
try {
core_ = new CMMCore();
} catch(UnsatisfiedLinkError ex) {
ReportingUtils.showError(ex, "Failed to open libMMCoreJ_wrap.jnilib");
return;
}
ReportingUtils.setCore(core_);
//core_.setDeviceDiscoveryEnabled(options_.enableDeviceDiscovery_);
core_.enableDebugLog(options_.debugLogEnabled_);
core_.logMessage("MM Studio version: " + getVersion());
core_.logMessage(core_.getVersionInfo());
core_.logMessage(core_.getAPIVersionInfo());
core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
cameraLabel_ = "";
shutterLabel_ = "";
zStageLabel_ = "";
xyStageLabel_ = "";
engine_ = new AcquisitionWrapperEngine();
// register callback for MMCore notifications, this is a global
// to avoid garbage collection
cb_ = new CoreEventCallback();
core_.registerCallback(cb_);
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception e2) {
ReportingUtils.showError(e2);
}
MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow();
if (parent != null) {
engine_.setParentGUI(parent);
}
loadMRUConfigFiles();
initializePlugins();
toFront();
if (!options_.doNotAskForConfigFile_) {
MMIntroDlg introDlg = new MMIntroDlg(VERSION, MRUConfigFiles_);
introDlg.setConfigFile(sysConfigFile_);
introDlg.setBackground(guiColors_.background.get((options_.displayBackground_)));
introDlg.setVisible(true);
sysConfigFile_ = introDlg.getConfigFile();
}
saveMRUConfigFiles();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
paint(MMStudioMainFrame.this.getGraphics());
engine_.setCore(core_, afMgr_);
posList_ = new PositionList();
engine_.setPositionList(posList_);
// load (but do no show) the scriptPanel
createScriptPanel();
// Create an instance of HotKeys so that they can be read in from prefs
hotKeys_ = new org.micromanager.utils.HotKeys();
hotKeys_.loadSettings();
// if an error occurred during config loading,
// do not display more errors than needed
if (!loadSystemConfiguration())
ReportingUtils.showErrorOn(false);
executeStartupScript();
// Create Multi-D window here but do not show it.
// This window needs to be created in order to properly set the "ChannelGroup"
// based on the Multi-D parameters
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this);
addMMBackgroundListener(acqControlWin_);
configPad_.setCore(core_);
if (parent != null) {
configPad_.setParentGUI(parent);
}
configPadButtonPanel_.setCore(core_);
// initialize controls
// initializeGUI(); Not needed since it is already called in loadSystemConfiguration
initializeHelpMenu();
String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, "");
if (afMgr_.hasDevice(afDevice)) {
try {
afMgr_.selectDevice(afDevice);
} catch (MMException e1) {
// this error should never happen
ReportingUtils.showError(e1);
}
}
// switch error reporting back on
ReportingUtils.showErrorOn(true);
}
private void initializePlugins() {
pluginMenu_ = new JMenu();
pluginMenu_.setText("Plugins");
menuBar_.add(pluginMenu_);
new Thread("Plugin loading") {
@Override
public void run() {
// Needed for loading clojure-based jars:
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
loadPlugins();
}
}.run();
}
});
final JButton setRoiButton = new JButton();
setRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/shape_handles.png"));
setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle");
setRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setROI();
}
});
topPanel.add(setRoiButton);
topLayout.putConstraint(SpringLayout.EAST, setRoiButton, 37,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, setRoiButton, 7,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, setRoiButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, setRoiButton, 154,
SpringLayout.NORTH, topPanel);
final JButton clearRoiButton = new JButton();
clearRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_out.png"));
clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
clearRoiButton.setToolTipText("Reset Region of Interest to full frame");
clearRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearROI();
}
});
topPanel.add(clearRoiButton);
topLayout.putConstraint(SpringLayout.EAST, clearRoiButton, 70,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, clearRoiButton, 40,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, clearRoiButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, clearRoiButton, 154,
SpringLayout.NORTH, topPanel);
final JLabel regionOfInterestLabel = new JLabel();
regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel.setText("ROI");
topPanel.add(regionOfInterestLabel);
topLayout.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel,
154, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, regionOfInterestLabel,
140, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel,
71, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel,
8, SpringLayout.WEST, topPanel);
contrastPanel_ = new ContrastPanel();
contrastPanel_.setFont(new Font("", Font.PLAIN, 10));
contrastPanel_.setContrastStretch(stretch);
contrastPanel_.setRejectOutliers(reject);
contrastPanel_.setFractionToReject(rejectFract);
contrastPanel_.setBorder(BorderFactory.createEmptyBorder());
bottomPanel.add(contrastPanel_);
topLayout.putConstraint(SpringLayout.SOUTH, contrastPanel_, -20,
SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, contrastPanel_, 0,
SpringLayout.NORTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, contrastPanel_, 0,
SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, contrastPanel_, 0,
SpringLayout.WEST, bottomPanel);
metadataPanel_ = new MetadataPanel();
metadataPanel_.setVisible(false);
bottomPanel.add(metadataPanel_);
topLayout.putConstraint(SpringLayout.SOUTH, metadataPanel_, -20,
SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, metadataPanel_, 0,
SpringLayout.NORTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, metadataPanel_, 0,
SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, metadataPanel_, 0,
SpringLayout.WEST, bottomPanel);
metadataPanel_.setBorder(BorderFactory.createEmptyBorder());
GUIUtils.registerImageFocusListener(new ImageFocusListener() {
public void focusReceived(ImageWindow focusedWindow) {
if (focusedWindow == null) {
contrastPanel_.setVisible(true);
metadataPanel_.setVisible(false);
} else if (focusedWindow instanceof MMImageWindow) {
contrastPanel_.setVisible(true);
metadataPanel_.setVisible(false);
} else if (focusedWindow.getImagePlus().getStack() instanceof AcquisitionVirtualStack) {
contrastPanel_.setVisible(false);
metadataPanel_.setVisible(true);
}
}
});
final JLabel regionOfInterestLabel_1 = new JLabel();
regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel_1.setText("Zoom");
topPanel.add(regionOfInterestLabel_1);
topLayout.putConstraint(SpringLayout.SOUTH,
regionOfInterestLabel_1, 154, SpringLayout.NORTH,
topPanel);
topLayout.putConstraint(SpringLayout.NORTH,
regionOfInterestLabel_1, 140, SpringLayout.NORTH,
topPanel);
topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1,
139, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1,
81, SpringLayout.WEST, topPanel);
final JButton zoomInButton = new JButton();
zoomInButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomIn();
}
});
zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_in.png"));
zoomInButton.setToolTipText("Zoom in");
zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(zoomInButton);
topLayout.putConstraint(SpringLayout.SOUTH, zoomInButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, zoomInButton, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, zoomInButton, 110,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, zoomInButton, 80,
SpringLayout.WEST, topPanel);
final JButton zoomOutButton = new JButton();
zoomOutButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomOut();
}
});
zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_out.png"));
zoomOutButton.setToolTipText("Zoom out");
zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(zoomOutButton);
topLayout.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, zoomOutButton, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, zoomOutButton, 143,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, zoomOutButton, 113,
SpringLayout.WEST, topPanel);
// Profile
// -------
final JLabel profileLabel_ = new JLabel();
profileLabel_.setFont(new Font("Arial", Font.BOLD, 11));
profileLabel_.setText("Profile");
topPanel.add(profileLabel_);
topLayout.putConstraint(SpringLayout.SOUTH, profileLabel_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, profileLabel_, 140,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, profileLabel_, 217,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, profileLabel_, 154,
SpringLayout.WEST, topPanel);
final JButton buttonProf = new JButton();
buttonProf.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/chart_curve.png"));
buttonProf.setFont(new Font("Arial", Font.PLAIN, 10));
buttonProf.setToolTipText("Open line profile window (requires line selection)");
buttonProf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openLineProfileWindow();
}
});
// buttonProf.setText("Profile");
topPanel.add(buttonProf);
topLayout.putConstraint(SpringLayout.SOUTH, buttonProf, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonProf, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonProf, 183,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonProf, 153,
SpringLayout.WEST, topPanel);
// Autofocus
// -------
final JLabel autofocusLabel_ = new JLabel();
autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11));
autofocusLabel_.setText("Autofocus");
topPanel.add(autofocusLabel_);
topLayout.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, autofocusLabel_, 274,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, autofocusLabel_, 194,
SpringLayout.WEST, topPanel);
buttonAutofocus_ = new JButton();
buttonAutofocus_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/find.png"));
buttonAutofocus_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocus_.setToolTipText("Autofocus now");
buttonAutofocus_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (afMgr_.getDevice() != null) {
new Thread() {
@Override
public void run() {
try {
boolean lmo = isLiveModeOn();
if(lmo)
enableLiveMode(false);
afMgr_.getDevice().fullFocus();
if(lmo)
enableLiveMode(true);
} catch (MMException ex) {
ReportingUtils.logError(ex);
}
}
}.start(); // or any other method from Autofocus.java API
}
}
});
topPanel.add(buttonAutofocus_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAutofocus_, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAutofocus_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAutofocus_, 223,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAutofocus_, 193,
SpringLayout.WEST, topPanel);
buttonAutofocusTools_ = new JButton();
buttonAutofocusTools_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/wrench_orange.png"));
buttonAutofocusTools_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocusTools_.setToolTipText("Set autofocus options");
buttonAutofocusTools_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAutofocusDialog();
}
});
topPanel.add(buttonAutofocusTools_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAutofocusTools_, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAutofocusTools_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAutofocusTools_, 256,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAutofocusTools_, 226,
SpringLayout.WEST, topPanel);
saveConfigButton_ = new JButton();
saveConfigButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
}
});
saveConfigButton_.setToolTipText("Save current presets to the configuration file");
saveConfigButton_.setText("Save");
saveConfigButton_.setEnabled(false);
topPanel.add(saveConfigButton_);
topLayout.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, saveConfigButton_, -5,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, saveConfigButton_, -80,
SpringLayout.EAST, topPanel);
// Add our own keyboard manager that handles Micro-Manager shortcuts
MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD);
}
private void handleException(Exception e, String msg) {
String errText = "Exception occurred: ";
if (msg.length() > 0) {
errText += msg + " -- ";
}
if (options_.debugLogEnabled_) {
errText += e.getMessage();
} else {
errText += e.toString() + "\n";
ReportingUtils.showError(e);
}
handleError(errText);
}
private void handleException(Exception e) {
handleException(e, "");
}
private void handleError(String message) {
if (isLiveModeOn()) {
// Should we always stop live mode on any error?
enableLiveMode(false);
}
JOptionPane.showMessageDialog(this, message);
core_.logMessage(message);
}
public void makeActive() {
toFront();
}
private void setExposure() {
try {
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
// Display the new exposure time
double exposure = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
// Interval for Live Mode changes as well
setLiveModeInterval();
} catch (Exception exp) {
// Do nothing.
}
}
public boolean getConserveRamOption() {
return options_.conserveRam_;
}
public boolean getAutoreloadOption() {
return options_.autoreloadDevices_;
}
private void updateTitle() {
this.setTitle("System: " + sysConfigFile_);
}
private void updateLineProfile() {
if (!isImageWindowOpen() || profileWin_ == null
|| !profileWin_.isShowing()) {
return;
}
calculateLineProfileData(imageWin_.getImagePlus());
profileWin_.setData(lineProfileData_);
}
private void openLineProfileWindow() {
if (imageWin_ == null || imageWin_.isClosed()) {
return;
}
calculateLineProfileData(imageWin_.getImagePlus());
if (lineProfileData_ == null) {
return;
}
profileWin_ = new GraphFrame();
profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
profileWin_.setData(lineProfileData_);
profileWin_.setAutoScale();
profileWin_.setTitle("Live line profile");
profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(profileWin_);
profileWin_.setVisible(true);
}
public Rectangle getROI() throws MMScriptException {
// ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++):
int[][] a = new int[4][1];
try {
core_.getROI(a[0], a[1], a[2], a[3]);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
// Return as a single array with x,y,w,h:
return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);
}
private void calculateLineProfileData(ImagePlus imp) {
// generate line profile
Roi roi = imp.getRoi();
if (roi == null || !roi.isLine()) {
// if there is no line ROI, create one
Rectangle r = imp.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI
+ iWidth / 4, iYROI + iHeight / 4);
imp.setRoi(roi);
roi = imp.getRoi();
}
ImageProcessor ip = imp.getProcessor();
ip.setInterpolate(true);
Line line = (Line) roi;
if (lineProfileData_ == null) {
lineProfileData_ = new GraphData();
}
lineProfileData_.setData(line.getPixels());
}
public void setROI(Rectangle r) throws MMScriptException {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
try {
core_.setROI(r.x, r.y, r.width, r.height);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
}
private void setROI() {
ImagePlus curImage = WindowManager.getCurrentImage();
if (curImage == null) {
return;
}
Roi roi = curImage.getRoi();
try {
if (roi == null) {
// if there is no ROI, create one
Rectangle r = curImage.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iWidth /= 2;
iHeight /= 2;
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
curImage.setRoi(iXROI, iYROI, iWidth, iHeight);
roi = curImage.getRoi();
}
if (roi.getType() != Roi.RECTANGLE) {
handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI.");
return;
}
Rectangle r = roi.getBoundingRect();
// if we already had an ROI defined, correct for the offsets
Rectangle cameraR = getROI();
r.x += cameraR.x;
r.y += cameraR.y;
// Stop (and restart) live mode if it is running
setROI(r);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void clearROI() {
try {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
core_.clearROI();
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private BooleanLock creatingImageWindow_ = new BooleanLock(false);
private static long waitForCreateImageWindowTimeout_ = 5000;
private MMImageWindow createImageWindow() {
if (creatingImageWindow_.isTrue()) {
try {
creatingImageWindow_.waitToSetFalse(waitForCreateImageWindowTimeout_);
} catch (Exception e) {
ReportingUtils.showError(e);
}
return imageWin_;
}
creatingImageWindow_.setValue(true);
MMImageWindow win = imageWin_;
removeMMBackgroundListener(imageWin_);
imageWin_ = null;
try {
if (win != null) {
win.saveAttributes();
win.dispose();
win = null;
}
win = new MMImageWindow(core_, this);
core_.logMessage("createImageWin1");
win.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(win);
setIJCal(win);
// listeners
if (centerAndDragListener_ != null
&& centerAndDragListener_.isRunning()) {
centerAndDragListener_.attach(win.getImagePlus().getWindow());
}
if (zWheelListener_ != null && zWheelListener_.isRunning()) {
zWheelListener_.attach(win.getImagePlus().getWindow());
}
if (xyzKeyListener_ != null && xyzKeyListener_.isRunning()) {
xyzKeyListener_.attach(win.getImagePlus().getWindow());
}
win.getCanvas().requestFocus();
imageWin_ = win;
} catch (Exception e) {
if (win != null) {
win.saveAttributes();
WindowManager.removeWindow(win);
win.dispose();
}
ReportingUtils.showError(e);
}
creatingImageWindow_.setValue(false);
return imageWin_;
}
/**
* Returns instance of the core uManager object;
*/
public CMMCore getMMCore() {
return core_;
}
/**
* Returns singleton instance of MMStudioMainFrame
*/
public static MMStudioMainFrame getInstance() {
return gui_;
}
public final void setExitStrategy(boolean closeOnExit) {
if (closeOnExit)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void saveConfigPresets() {
MicroscopeModel model = new MicroscopeModel();
try {
model.loadFromFile(sysConfigFile_);
model.createSetupConfigsFromHardware(core_);
model.createResolutionsFromHardware(core_);
File f = FileDialogs.save(this, "Save the configuration file", MM_CONFIG_FILE);
if (f != null) {
model.saveToFile(f.getAbsolutePath());
sysConfigFile_ = f.getAbsolutePath();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
updateTitle();
}
} catch (MMConfigFileException e) {
ReportingUtils.showError(e);
}
}
protected void setConfigSaveButtonStatus(boolean changed) {
saveConfigButton_.setEnabled(changed);
}
public String getAcqDirectory() {
return openAcqDirectory_;
}
public void setAcqDirectory(String dir) {
openAcqDirectory_ = dir;
}
/**
* Open an existing acquisition directory and build viewer window.
*
*/
public void openAcquisitionData() {
// choose the directory
// --------------------
File f = FileDialogs.openDir(this, "Please select an image data set", MM_DATA_SET);
if (f != null) {
if (f.isDirectory()) {
openAcqDirectory_ = f.getAbsolutePath();
} else {
openAcqDirectory_ = f.getParent();
}
openAcquisitionData(openAcqDirectory_);
}
}
public void openAcquisitionData(String dir) {
String rootDir = new File(dir).getAbsolutePath();
String name = new File(dir).getName();
rootDir= rootDir.substring(0, rootDir.length() - (name.length() + 1));
try {
acqMgr_.openAcquisition(name, rootDir, true, true, true);
acqMgr_.getAcquisition(name).initialize();
acqMgr_.closeAcquisition(name);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
}
}
protected void zoomOut() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomOut(r.width / 2, r.height / 2);
}
}
protected void zoomIn() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomIn(r.width / 2, r.height / 2);
}
}
protected void changeBinning() {
try {
boolean liveRunning = false;
if (isLiveModeOn() ) {
liveRunning = true;
enableLiveMode(false);
}
if (isCameraAvailable()) {
Object item = comboBinning_.getSelectedItem();
if (item != null) {
core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString());
}
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void createPropertyEditor() {
if (propertyBrowser_ != null) {
propertyBrowser_.dispose();
}
propertyBrowser_ = new PropertyEditor();
propertyBrowser_.setGui(this);
propertyBrowser_.setVisible(true);
propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
propertyBrowser_.setCore(core_);
}
private void createCalibrationListDlg() {
if (calibrationListDlg_ != null) {
calibrationListDlg_.dispose();
}
calibrationListDlg_ = new CalibrationListDlg(core_);
calibrationListDlg_.setVisible(true);
calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
calibrationListDlg_.setParentGUI(this);
}
public CalibrationListDlg getCalibrationListDlg() {
if (calibrationListDlg_ == null) {
createCalibrationListDlg();
}
return calibrationListDlg_;
}
private void createScriptPanel() {
if (scriptPanel_ == null) {
scriptPanel_ = new ScriptPanel(core_, options_, this);
scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);
scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);
scriptPanel_.setParentGUI(this);
scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(scriptPanel_);
}
}
/**
* Updates Status line in main window from cached values
*/
private void updateStaticInfoFromCache() {
String dimText = "Image size: " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X "
+ staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits";
dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix";
if (zStageLabel_.length() > 0) {
dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um";
}
if (xyStageLabel_.length() > 0) {
dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um";
}
labelImageDimensions_.setText(dimText);
}
public void updateXYPos(double x, double y) {
staticInfo_.x_ = x;
staticInfo_.y_ = y;
updateStaticInfoFromCache();
}
public void updateZPos(double z) {
staticInfo_.zPos_ = z;
updateStaticInfoFromCache();
}
public void updateXYPosRelative(double x, double y) {
staticInfo_.x_ += x;
staticInfo_.y_ += y;
updateStaticInfoFromCache();
}
public void updateZPosRelative(double z) {
staticInfo_.zPos_ += z;
updateStaticInfoFromCache();
}
public void updateXYStagePosition(){
double x[] = new double[1];
double y[] = new double[1];
try {
if (xyStageLabel_.length() > 0)
core_.getXYPosition(xyStageLabel_, x, y);
} catch (Exception e) {
ReportingUtils.showError(e);
}
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
private void updatePixSizeUm (double pixSizeUm) {
staticInfo_.pixSizeUm_ = pixSizeUm;
updateStaticInfoFromCache();
}
private void updateStaticInfo() {
double zPos = 0.0;
double x[] = new double[1];
double y[] = new double[1];
try {
if (zStageLabel_.length() > 0) {
zPos = core_.getPosition(zStageLabel_);
}
if (xyStageLabel_.length() > 0) {
core_.getXYPosition(xyStageLabel_, x, y);
}
} catch (Exception e) {
handleException(e);
}
staticInfo_.width_ = core_.getImageWidth();
staticInfo_.height_ = core_.getImageHeight();
staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel();
staticInfo_.imageBitDepth_ = core_.getImageBitDepth();
staticInfo_.pixSizeUm_ = core_.getPixelSizeUm();
staticInfo_.zPos_ = zPos;
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
public void toggleShutter() {
try {
if (!toggleButtonShutter_.isEnabled())
return;
toggleButtonShutter_.requestFocusInWindow();
if (toggleButtonShutter_.getText().equals("Open")) {
setShutterButton(true);
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(false);
setShutterButton(false);
}
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
private void setShutterButton(boolean state) {
if (state) {
// toggleButtonShutter_.setSelected(true);
toggleButtonShutter_.setText("Close");
} else {
// toggleButtonShutter_.setSelected(false);
toggleButtonShutter_.setText("Open");
}
}
// //////////////////////////////////////////////////////////////////////////
// public interface available for scripting access
// //////////////////////////////////////////////////////////////////////////
public void snapSingleImage() {
doSnap();
}
public Object getPixels() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getProcessor().getPixels();
}
return null;
}
public void setPixels(Object obj) {
if (imageWin_ == null) {
return;
}
imageWin_.getImagePlus().getProcessor().setPixels(obj);
}
public int getImageHeight() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getHeight();
}
return 0;
}
public int getImageWidth() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getWidth();
}
return 0;
}
public int getImageDepth() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getBitDepth();
}
return 0;
}
public ImageProcessor getImageProcessor() {
if (imageWin_ == null) {
return null;
}
return imageWin_.getImagePlus().getProcessor();
}
private boolean isCameraAvailable() {
return cameraLabel_.length() > 0;
}
/**
* Part of ScriptInterface API
* Opens the XYPositionList when it is not opened
* Adds the current position to the list (same as pressing the "Mark" button)
*/
public void markCurrentPosition() {
if (posListDlg_ == null) {
showXYPositionList();
}
if (posListDlg_ != null) {
posListDlg_.markPosition();
}
}
/**
* Implements ScriptInterface
*/
public AcqControlDlg getAcqDlg() {
return acqControlWin_;
}
/**
* Implements ScriptInterface
*/
public PositionListDlg getXYPosListDlg() {
if (posListDlg_ == null)
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
return posListDlg_;
}
/**
* Implements ScriptInterface
*/
public boolean isAcquisitionRunning() {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
/**
* Implements ScriptInterface
*/
public boolean versionLessThan(String version) throws MMScriptException {
try {
String[] v = VERSION.split(" ", 2);
String[] m = v[0].split("\\.", 3);
String[] v2 = version.split(" ", 2);
String[] m2 = v2[0].split("\\.", 3);
for (int i=0; i < 3; i++) {
if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) {
return false;
}
}
if (v2.length < 2 || v2[1].equals("") )
return false;
if (v.length < 2 ) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return false;
}
return true;
} catch (Exception ex) {
throw new MMScriptException ("Format of version String should be \"a.b.c\"");
}
}
public boolean isImageWindowOpen() {
boolean ret = imageWin_ != null;
ret = ret && !imageWin_.isClosed();
if (ret) {
try {
Graphics g = imageWin_.getGraphics();
if (null != g) {
int ww = imageWin_.getWidth();
g.clearRect(0, 0, ww, 40);
imageWin_.drawInfo(g);
} else {
// explicitly clean up if Graphics is null, rather
// than cleaning up in the exception handler below..
WindowManager.removeWindow(imageWin_);
imageWin_.saveAttributes();
imageWin_.dispose();
imageWin_ = null;
ret = false;
}
} catch (Exception e) {
WindowManager.removeWindow(imageWin_);
imageWin_.saveAttributes();
imageWin_.dispose();
imageWin_ = null;
ReportingUtils.showError(e);
ret = false;
}
}
return ret;
}
public boolean isLiveModeOn() {
return liveModeTimer_ != null && liveModeTimer_.isRunning();
}
public void enableLiveMode(boolean enable) {
if (core_ == null)
return;
if (enable == isLiveModeOn() )
return;
setLiveModeInterval();
if (core_.getNumberOfComponents() == 1) { //monochrome or multi camera
multiChannelCameraNrCh_ = core_.getNumberOfCameraChannels();
if (multiChannelCameraNrCh_ > 1) {
multiChannelCamera_ = true;
enableMultiCameraLiveMode(enable);
} else
enableMonochromeLiveMode(enable);
} else
enableRGBLiveMode(enable);
updateButtonsForLiveMode(enable);
}
private void manageShutterLiveMode(boolean enable) throws Exception {
shutterLabel_ = core_.getShutterDevice();
if (shutterLabel_.length() > 0) {
if (enable) {
shutterOriginalState_ = core_.getShutterOpen();
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(shutterOriginalState_);
}
}
}
public void updateButtonsForLiveMode(boolean enable) {
toggleButtonShutter_.setEnabled(!enable);
autoShutterCheckBox_.setEnabled(!enable);
buttonSnap_.setEnabled(!enable);
toggleButtonLive_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setSelected(enable);
toggleButtonLive_.setText(enable ? "Stop Live" : "Live");
}
private void enableLiveModeListeners(boolean enable) {
if (enable) {
// attach mouse wheel listener to control focus:
if (zWheelListener_ == null) {
zWheelListener_ = new ZWheelListener(core_, this);
}
zWheelListener_.start(imageWin_);
// attach key listener to control the stage and focus:
if (xyzKeyListener_ == null) {
xyzKeyListener_ = new XYZKeyListener(core_, this);
}
xyzKeyListener_.start(imageWin_);
} else {
if (zWheelListener_ != null) {
zWheelListener_.stop();
}
if (xyzKeyListener_ != null) {
xyzKeyListener_.stop();
}
}
}
private void enableMultiCameraLiveMode(boolean enable) {
if (enable) {
try {
checkMultiChannelWindow();
getAcquisition(MULTI_CAMERA_ACQ).toFront();
setLiveModeInterval();
if (liveModeTimer_ == null)
liveModeTimer_ = new LiveModeTimer((int) liveModeInterval_, LiveModeTimer.MULTI_CAMERA );
else {
liveModeTimer_.setDelay((int) liveModeInterval_);
liveModeTimer_.setType(LiveModeTimer.MULTI_CAMERA);
}
manageShutterLiveMode(enable);
liveModeTimer_.start();
getAcquisition(MULTI_CAMERA_ACQ).getAcquisitionWindow().setWindowTitle("Multi Camera Live Mode (running)");
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to enable live mode.");
}
} else {
try {
liveModeTimer_.stop();
if (acqMgr_.acquisitionExists(MULTI_CAMERA_ACQ))
getAcquisition(MULTI_CAMERA_ACQ).getAcquisitionWindow().setWindowTitle("Multi Camera Live Mode (stopped)");
manageShutterLiveMode(enable);
enableLiveModeListeners(false);
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to disable live mode.");
}
}
}
private void enableMonochromeLiveMode(boolean enable) {
if (enable) {
try {
if (!isImageWindowOpen() && creatingImageWindow_.isFalse()) {
imageWin_ = createImageWindow();
}
imageWin_.drawInfo(imageWin_.getGraphics());
imageWin_.toFront();
enableLiveModeListeners(enable);
if (liveModeTimer_ == null)
liveModeTimer_ = new LiveModeTimer((int) liveModeInterval_,LiveModeTimer.MONOCHROME);
else {
liveModeTimer_.setDelay((int) liveModeInterval_);
liveModeTimer_.setType(LiveModeTimer.MONOCHROME);
}
manageShutterLiveMode(enable);
liveModeTimer_.start();
imageWin_.setSubTitle("Live (running)");
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to enable live mode.");
if (imageWin_ != null) {
imageWin_.saveAttributes();
WindowManager.removeWindow(imageWin_);
imageWin_.dispose();
imageWin_ = null;
}
}
} else {
try {
liveModeTimer_.stop();
manageShutterLiveMode(enable);
enableLiveModeListeners(enable);
imageWin_.setSubTitle("Live (stopped)");
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to disable live mode.");
if (imageWin_ != null) {
WindowManager.removeWindow(imageWin_);
imageWin_.dispose();
imageWin_ = null;
}
}
}
}
private void enableRGBLiveMode(boolean enable) {
if (enable) {
setLiveModeInterval();
if (liveModeTimer_ == null) {
liveModeTimer_ = new LiveModeTimer((int) liveModeInterval_, LiveModeTimer.RGB);
} else {
liveModeTimer_.setDelay((int) liveModeInterval_);
liveModeTimer_.setType(LiveModeTimer.RGB);
}
checkRGBAcquisition();
try {
manageShutterLiveMode(enable);
liveModeTimer_.start();
getAcquisition(RGB_ACQ).getAcquisitionWindow().setWindowTitle("RGB Live Mode (running)");
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
} else {
try {
liveModeTimer_.stop();
manageShutterLiveMode(enable);
if (acqMgr_.acquisitionExists(RGB_ACQ))
getAcquisition(RGB_ACQ).getAcquisitionWindow().setWindowTitle("RGB Live Mode (stopped)");
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
}
public boolean getLiveMode() {
return isLiveModeOn();
}
public boolean updateImage() {
try {
if (isLiveModeOn()) {
enableLiveMode(false);
return true; // nothing to do, just show the last image
}
if (!isImageWindowOpen()) {
createImageWindow();
}
core_.snapImage();
Object img;
img = core_.getImage();
if (imageWin_.windowNeedsResizing()) {
createImageWindow();
}
if (!isCurrentImageFormatSupported()) {
return false;
}
imageWin_.newImage(img);
updateLineProfile();
} catch (Exception e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public boolean displayImage(final Object pixels) {
return displayImage(pixels, true);
}
public boolean displayImage(final Object pixels, boolean wait) {
try {
if (core_.getNumberOfCameraChannels() > 1)
checkMultiChannelWindow();
else {
if (!isImageWindowOpen() || imageWin_.windowNeedsResizing()
&& creatingImageWindow_.isFalse()) {
createImageWindow();
}
Runnable displayRunnable = new Runnable() {
public void run() {
imageWin_.newImage(pixels);
updateLineProfile();
}
};
if (SwingUtilities.isEventDispatchThread()) {
displayRunnable.run();
} else {
if (wait) {
SwingUtilities.invokeAndWait(displayRunnable);
} else {
SwingUtilities.invokeLater(displayRunnable);
}
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
return false;
}
return true;
}
public boolean displayImageWithStatusLine(Object pixels, String statusLine) {
try {
if (!isImageWindowOpen() || imageWin_.windowNeedsResizing()
&& creatingImageWindow_.isFalse()) {
createImageWindow();
}
imageWin_.newImageWithStatusLine(pixels, statusLine);
updateLineProfile();
} catch (Exception e) {
ReportingUtils.logError(e);
return false;
}
return true;
}
public void displayStatusLine(String statusLine) {
try {
if (isImageWindowOpen()) {
imageWin_.displayStatusLine(statusLine);
}
} catch (Exception e) {
ReportingUtils.logError(e);
return;
}
}
private boolean isCurrentImageFormatSupported() {
boolean ret = false;
long channels = core_.getNumberOfComponents();
long bpp = core_.getBytesPerPixel();
if (channels > 1 && channels != 4 && bpp != 1) {
handleError("Unsupported image format.");
} else {
ret = true;
}
return ret;
}
private void doSnap() {
if (core_.getNumberOfComponents() == 1) {
if(4 == core_.getBytesPerPixel()) {
doSnapFloat();
} else {
if (core_.getNumberOfCameraChannels() > 1)
{
doSnapMultiCamera();
} else {
doSnapMonochrome();
}
}
} else {
doSnapColor();
}
}
public void initializeGUI() {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
engine_.setZStageDevice(zStageLabel_);
if (cameraLabel_.length() > 0) {
ActionListener[] listeners;
// binning combo
if (comboBinning_.getItemCount() > 0) {
comboBinning_.removeAllItems();
}
StrVector binSizes = core_.getAllowedPropertyValues(
cameraLabel_, MMCoreJ.getG_Keyword_Binning());
listeners = comboBinning_.getActionListeners();
for (int i = 0; i < listeners.length; i++) {
comboBinning_.removeActionListener(listeners[i]);
}
for (int i = 0; i < binSizes.size(); i++) {
comboBinning_.addItem(binSizes.get(i));
}
comboBinning_.setMaximumRowCount((int) binSizes.size());
if (binSizes.size() == 0) {
comboBinning_.setEditable(true);
} else {
comboBinning_.setEditable(false);
}
for (int i = 0; i < listeners.length; i++) {
comboBinning_.addActionListener(listeners[i]);
}
}
// active shutter combo
try {
shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);
} catch (Exception e) {
ReportingUtils.logError(e);
}
if (shutters_ != null) {
String items[] = new String[(int) shutters_.size()];
for (int i = 0; i < shutters_.size(); i++) {
items[i] = shutters_.get(i);
}
GUIUtils.replaceComboContents(shutterComboBox_, items);
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// Autofocus
buttonAutofocusTools_.setEnabled(afMgr_.getDevice() != null);
buttonAutofocus_.setEnabled(afMgr_.getDevice() != null);
// Rebuild stage list in XY PositinList
if (posListDlg_ != null) {
posListDlg_.rebuildAxisList();
}
// Mouse moves stage
centerAndDragListener_ = new CenterAndDragListener(core_, gui_);
if (centerAndDragMenuItem_.isSelected()) {
centerAndDragListener_.start();
}
updateGUI(true);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getVersion() {
return VERSION;
}
private void addPluginToMenu(final PluginItem plugin, Class<?> cl) {
// add plugin menu items
final JMenuItem newMenuItem = new JMenuItem();
newMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
ReportingUtils.logMessage("Plugin command: "
+ e.getActionCommand());
plugin.instantiate();
plugin.plugin.show();
}
});
newMenuItem.setText(plugin.menuItem);
String toolTipDescription = "";
try {
// Get this static field from the class implementing MMPlugin.
toolTipDescription = (String) cl.getDeclaredField("tooltipDescription").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
toolTipDescription = "Description not available";
} catch (NoSuchFieldException e) {
toolTipDescription = "Description not available";
ReportingUtils.logError(cl.getName() + " fails to implement static String tooltipDescription.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
String mrjProp = System.getProperty("mrj.version");
if (mrjProp != null && !mrjProp.equals(null)) // running on a mac
newMenuItem.setToolTipText(toolTipDescription);
else
newMenuItem.setToolTipText( TooltipTextMaker.addHTMLBreaksForTooltip(toolTipDescription) );
pluginMenu_.add(newMenuItem);
pluginMenu_.validate();
menuBar_.validate();
}
public void updateGUI(boolean updateConfigPadStructure) {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
afMgr_.refresh();
// camera settings
if (isCameraAvailable()) {
double exp = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp));
String binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning());
GUIUtils.setComboSelection(comboBinning_, binSize);
long bitDepth = 8;
if (imageWin_ != null) {
long hsz = imageWin_.getRawHistogramSize();
bitDepth = (long) Math.log(hsz);
}
bitDepth = core_.getImageBitDepth();
contrastPanel_.setPixelBitDepth((int) bitDepth, false);
}
if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) {
autoShutterCheckBox_.setSelected(core_.getAutoShutter());
boolean shutterOpen = core_.getShutterOpen();
setShutterButton(shutterOpen);
if (autoShutterCheckBox_.isSelected()) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
}
// active shutter combo
if (shutters_ != null) {
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// state devices
if (updateConfigPadStructure && (configPad_ != null)) {
configPad_.refreshStructure();
// Needed to update read-only properties. May slow things down...
core_.updateSystemStateCache();
}
// update Channel menus in Multi-dimensional acquisition dialog
updateChannelCombos();
} catch (Exception e) {
ReportingUtils.logError(e);
}
updateStaticInfo();
updateTitle();
}
public boolean okToAcquire() {
return !isLiveModeOn();
}
public void stopAllActivity() {
enableLiveMode(false);
}
public void refreshImage() {
if (imageWin_ != null) {
imageWin_.getImagePlus().updateAndDraw();
}
}
private void cleanupOnClose() {
// NS: Save config presets if they were changed.
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
}
if (liveModeTimer_ != null)
liveModeTimer_.stop();
try{
if (imageWin_ != null) {
if (!imageWin_.isClosed())
imageWin_.close();
imageWin_.dispose();
imageWin_ = null;
}
}
catch( Throwable t){
ReportingUtils.logError(t, "closing ImageWin_");
}
if (profileWin_ != null) {
removeMMBackgroundListener(profileWin_);
profileWin_.dispose();
}
if (scriptPanel_ != null) {
removeMMBackgroundListener(scriptPanel_);
scriptPanel_.closePanel();
}
if (propertyBrowser_ != null) {
removeMMBackgroundListener(propertyBrowser_);
propertyBrowser_.dispose();
}
if (acqControlWin_ != null) {
removeMMBackgroundListener(acqControlWin_);
acqControlWin_.close();
}
if (engine_ != null) {
engine_.shutdown();
}
if (afMgr_ != null) {
afMgr_.closeOptionsDialog();
}
// dispose plugins
for (int i = 0; i < plugins_.size(); i++) {
MMPlugin plugin = (MMPlugin) plugins_.get(i).plugin;
if (plugin != null) {
plugin.dispose();
}
}
synchronized (shutdownLock_) {
try {
if (core_ != null){
core_.delete();
core_ = null;
}
} catch (Exception err) {
ReportingUtils.showError(err);
}
}
}
private void saveSettings() {
Rectangle r = this.getBounds();
mainPrefs_.putInt(MAIN_FRAME_X, r.x);
mainPrefs_.putInt(MAIN_FRAME_Y, r.y);
mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width);
mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height);
mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation());
mainPrefs_.putBoolean(MAIN_STRETCH_CONTRAST, contrastPanel_.isContrastStretch());
mainPrefs_.putBoolean(MAIN_REJECT_OUTLIERS, contrastPanel_.isRejectOutliers());
mainPrefs_.putDouble(MAIN_REJECT_FRACTION, contrastPanel_.getFractionToReject());
mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);
// save field values from the main window
// NOTE: automatically restoring these values on startup may cause
// problems
mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText());
// NOTE: do not save auto shutter state
if (afMgr_ != null && afMgr_.getDevice() != null) {
mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());
}
}
private void loadConfiguration() {
File f = FileDialogs.openFile(this, "Load a config file",MM_CONFIG_FILE);
if (f != null) {
sysConfigFile_ = f.getAbsolutePath();
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
}
}
private void loadSystemState() {
File f = FileDialogs.openFile(this, "Load a system state file", MM_CONFIG_FILE);
if (f != null) {
sysStateFile_ = f.getAbsolutePath();
try {
// WaitDialog waitDlg = new
// WaitDialog("Loading saved state, please wait...");
// waitDlg.showDialog();
core_.loadSystemState(sysStateFile_);
GUIUtils.preventDisplayAdapterChangeExceptions();
// waitDlg.closeDialog();
initializeGUI();
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
private void saveSystemState() {
File f = FileDialogs.save(this,
"Save the system state to a config file", MM_CONFIG_FILE);
if (f != null) {
sysStateFile_ = f.getAbsolutePath();
try {
core_.saveSystemState(sysStateFile_);
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
public void closeSequence() {
if (!this.isRunning())
return;
if (engine_ != null && engine_.isAcquisitionRunning()) {
int result = JOptionPane.showConfirmDialog(
this,
"Acquisition in progress. Are you sure you want to exit and discard all data?",
"Micro-Manager", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
return;
}
}
stopAllActivity();
cleanupOnClose();
saveSettings();
try {
configPad_.saveSettings();
options_.saveSettings();
hotKeys_.saveSettings();
} catch (NullPointerException e) {
if (core_ != null)
this.logError(e);
}
this.dispose();
if (options_.closeOnExit_) {
if (!runsAsPlugin_) {
System.exit(0);
} else {
ImageJ ij = IJ.getInstance();
if (ij != null) {
ij.quit();
}
}
}
}
public void applyContrastSettings(ContrastSettings contrast8,
ContrastSettings contrast16) {
contrastPanel_.applyContrastSettings(contrast8, contrast16);
}
public ContrastSettings getContrastSettings() {
return contrastPanel_.getContrastSettings();
}
public boolean is16bit() {
if (isImageWindowOpen()
&& imageWin_.getImagePlus().getProcessor() instanceof ShortProcessor) {
return true;
}
return false;
}
public boolean isRunning() {
return running_;
}
/**
* Executes the beanShell script. This script instance only supports
* commands directed to the core object.
*/
private void executeStartupScript() {
// execute startup script
File f = new File(startupScriptFile_);
if (startupScriptFile_.length() > 0 && f.exists()) {
WaitDialog waitDlg = new WaitDialog(
"Executing startup script, please wait...");
waitDlg.showDialog();
Interpreter interp = new Interpreter();
try {
// insert core object only
interp.set(SCRIPT_CORE_OBJECT, core_);
interp.set(SCRIPT_ACQENG_OBJECT, engine_);
interp.set(SCRIPT_GUI_OBJECT, this);
// read text file and evaluate
interp.eval(TextUtils.readTextFile(startupScriptFile_));
} catch (IOException exc) {
ReportingUtils.showError(exc, "Unable to read the startup script (" + startupScriptFile_ + ").");
} catch (EvalError exc) {
ReportingUtils.showError(exc);
} finally {
waitDlg.closeDialog();
}
} else {
if (startupScriptFile_.length() > 0)
ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present.");
}
}
/**
* Loads system configuration from the cfg file.
*/
private boolean loadSystemConfiguration() {
boolean result = true;
saveMRUConfigFiles();
final WaitDialog waitDlg = new WaitDialog(
"Loading system configuration, please wait...");
waitDlg.setAlwaysOnTop(true);
waitDlg.showDialog();
this.setEnabled(false);
try {
if (sysConfigFile_.length() > 0) {
GUIUtils.preventDisplayAdapterChangeExceptions();
core_.waitForSystem();
ignorePropertyChanges_ = true;
core_.loadSystemConfiguration(sysConfigFile_);
ignorePropertyChanges_ = false;
GUIUtils.preventDisplayAdapterChangeExceptions();
}
} catch (final Exception err) {
GUIUtils.preventDisplayAdapterChangeExceptions();
ReportingUtils.showError(err);
result = false;
} finally {
waitDlg.closeDialog();
}
setEnabled(true);
initializeGUI();
updateSwitchConfigurationMenu();
FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_));
return result;
}
private void saveMRUConfigFiles() {
if (0 < sysConfigFile_.length()) {
if (MRUConfigFiles_.contains(sysConfigFile_)) {
MRUConfigFiles_.remove(sysConfigFile_);
}
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
// save the MRU list to the preferences
for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {
String value = "";
if (null != MRUConfigFiles_.get(icfg)) {
value = MRUConfigFiles_.get(icfg).toString();
}
mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);
}
}
}
private void loadMRUConfigFiles() {
sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_);
// startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE,
// startupScriptFile_);
MRUConfigFiles_ = new ArrayList<String>();
for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {
String value = "";
value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);
if (0 < value.length()) {
File ruFile = new File(value);
if (ruFile.exists()) {
if (!MRUConfigFiles_.contains(value)) {
MRUConfigFiles_.add(value);
}
}
}
}
// initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE
if (0 < sysConfigFile_.length()) {
if (!MRUConfigFiles_.contains(sysConfigFile_)) {
// in case persistant data is inconsistent
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
}
}
}
/**
* Opens Acquisition dialog.
*/
private void openAcqControlDialog() {
try {
if (acqControlWin_ == null) {
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this);
}
if (acqControlWin_.isActive()) {
acqControlWin_.setTopPosition();
}
acqControlWin_.setVisible(true);
acqControlWin_.repaint();
// TODO: this call causes a strange exception the first time the
// dialog is created
// something to do with the order in which combo box creation is
// performed
// acqControlWin_.updateGroupsCombo();
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nAcquistion window failed to open due to invalid or corrupted settings.\n"
+ "Try resetting registry settings to factory defaults (Menu Tools|Options).");
}
}
/**
* /** Opens a dialog to record stage positions
*/
@Override
public void showXYPositionList() {
if (posListDlg_ == null) {
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
}
posListDlg_.setVisible(true);
}
private void updateChannelCombos() {
if (this.acqControlWin_ != null) {
this.acqControlWin_.updateChannelAndGroupCombo();
}
}
@Override
public void setConfigChanged(boolean status) {
configChanged_ = status;
setConfigSaveButtonStatus(configChanged_);
}
/**
* Returns the current background color
* @return
*/
@Override
public Color getBackgroundColor() {
return guiColors_.background.get((options_.displayBackground_));
}
/*
* Changes background color of this window and all other MM windows
*/
@Override
public void setBackgroundStyle(String backgroundType) {
setBackground(guiColors_.background.get((backgroundType)));
paint(MMStudioMainFrame.this.getGraphics());
// sets background of all registered Components
for (Component comp:MMFrames_) {
if (comp != null)
comp.setBackground(guiColors_.background.get(backgroundType));
}
}
@Override
public String getBackgroundStyle() {
return options_.displayBackground_;
}
// Set ImageJ pixel calibration
private void setIJCal(MMImageWindow imageWin) {
if (imageWin != null) {
imageWin.setIJCal();
}
}
// //////////////////////////////////////////////////////////////////////////
// Scripting interface
// //////////////////////////////////////////////////////////////////////////
private class ExecuteAcq implements Runnable {
public ExecuteAcq() {
}
@Override
public void run() {
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
}
}
}
private class LoadAcq implements Runnable {
private String filePath_;
public LoadAcq(String path) {
filePath_ = path;
}
@Override
public void run() {
// stop current acquisition if any
engine_.shutdown();
// load protocol
if (acqControlWin_ != null) {
acqControlWin_.loadAcqSettingsFromFile(filePath_);
}
}
}
private void testForAbortRequests() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
}
}
@Override
public void startAcquisition() throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new ExecuteAcq());
}
@Override
public void runAcquisition() throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(50);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
} else {
throw new MMScriptException(
"Acquisition window must be open for this command to work.");
}
}
@Override
public void runAcquisition(String name, String root)
throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition(name, root);
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(100);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
} else {
throw new MMScriptException(
"Acquisition window must be open for this command to work.");
}
}
@Override
public void runAcqusition(String name, String root) throws MMScriptException {
runAcquisition(name, root);
}
@Override
public void loadAcquisition(String path) throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new LoadAcq(path));
}
@Override
public void setPositionList(PositionList pl) throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
posList_ = pl; // PositionList.newInstance(pl);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (posListDlg_ != null) {
posListDlg_.setPositionList(posList_);
engine_.setPositionList(posList_);
}
}
});
}
@Override
public PositionList getPositionList() throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
return posList_; //PositionList.newInstance(posList_);
}
@Override
public void sleep(long ms) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.sleep(ms);
}
}
@Override
public String getUniqueAcquisitionName(String stub) {
return acqMgr_.getUniqueAcquisitionName(stub);
}
// TODO:
@Override
public MMAcquisition getCurrentAcquisition() {
return null; // if none available
}
public void openAcquisition(String name, String rootDir) throws MMScriptException {
openAcquisition(name, rootDir, true);
}
public void openAcquisition(String name, String rootDir, boolean show) throws MMScriptException {
//acqMgr_.openAcquisition(name, rootDir, show);
TaggedImageStorage imageFileManager = new TaggedImageStorageDiskDefault((new File(rootDir, name)).getAbsolutePath());
MMImageCache cache = new MMImageCache(imageFileManager);
VirtualAcquisitionDisplay display = new VirtualAcquisitionDisplay(cache, null);
display.show();
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions) throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,
nrPositions, true, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices) throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show, boolean virtual)
throws MMScriptException {
acqMgr_.openAcquisition(name, rootDir, show, virtual);
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show, boolean virtual)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual);
}
private void openAcquisitionSnap(String name, String rootDir, boolean show)
throws MMScriptException {
/*
MMAcquisition acq = acqMgr_.openAcquisitionSnap(name, rootDir, this,
show);
acq.setDimensions(0, 1, 1, 1);
try {
// acq.getAcqData().setPixelSizeUm(core_.getPixelSizeUm());
acq.setProperty(SummaryKeys.IMAGE_PIXEL_SIZE_UM, String.valueOf(core_.getPixelSizeUm()));
} catch (Exception e) {
ReportingUtils.showError(e);
}
*
*/
}
@Override
public void initializeAcquisition(String name, int width, int height,
int depth) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setImagePhysicalDimensions(width, height, depth);
acq.initialize();
}
@Override
public int getAcquisitionImageWidth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getWidth();
}
@Override
public int getAcquisitionImageHeight(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getHeight();
}
@Override
public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getDepth();
}
@Override
public Boolean acquisitionExists(String name) {
return acqMgr_.acquisitionExists(name);
}
@Override
public void closeAcquisition(String name) throws MMScriptException {
acqMgr_.closeAcquisition(name);
}
@Override
public void closeAcquisitionImage5D(String title) throws MMScriptException {
acqMgr_.closeImage5D(title);
}
/**
* Since Burst and normal acquisition are now carried out by the same engine,
* loadBurstAcquistion simply calls loadAcquisition
* t
* @param path - path to file specifying acquisition settings
*/
@Override
public void loadBurstAcquisition(String path) throws MMScriptException {
this.loadAcquisition(path);
}
@Override
public void refreshGUI() {
updateGUI(true);
}
public void setAcquisitionProperty(String acqName, String propertyName,
String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(propertyName, value);
}
public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSystemState(md);
}
public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSummaryProperties(md);
}
public void setImageProperty(String acqName, int frame, int channel,
int slice, String propName, String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(frame, channel, slice, propName, value);
}
public void snapAndAddImage(String name, int frame, int channel, int slice)
throws MMScriptException {
snapAndAddImage(name, frame, channel, slice, 0);
}
public void snapAndAddImage(String name, int frame, int channel, int slice, int position)
throws MMScriptException {
Metadata md = new Metadata();
try {
Object img;
if (core_.isSequenceRunning()) {
img = core_.getLastImage();
core_.getLastImageMD(0, 0, md);
} else {
core_.snapImage();
img = core_.getImage();
}
MMAcquisition acq = acqMgr_.getAcquisition(name);
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
if (!acq.isInitialized()) {
acq.setImagePhysicalDimensions((int) width, (int) height,
(int) depth);
acq.initialize();
}
acq.insertImage(img, frame, channel, slice, position);
// Insert exposure in metadata
// acq.setProperty(frame, channel, slice, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
/*
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
acq.setProperty(frame, channel, slice, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
acq.setProperty(frame, channel, slice, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
acq.setSystemState(frame, channel, slice, state);
*/
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public void addToSnapSeries(Object img, String acqName) {
try {
acqMgr_.getCurrentAlbum();
if (acqName == null) {
acqName = "Snap" + snapCount_;
}
Boolean newSnap = false;
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
//MMAcquisitionSnap acq = null;
if (! acqMgr_.hasActiveImage5D(acqName)) {
newSnap = true;
}
if (newSnap) {
snapCount_++;
acqName = "Snap" + snapCount_;
this.openAcquisitionSnap(acqName, null, true); // (dir=null) ->
// keep in
// memory; don't
// save to file.
initializeAcquisition(acqName, (int) width, (int) height,
(int) depth);
}
setChannelColor(acqName, 0, Color.WHITE);
setChannelName(acqName, 0, "Snap");
// acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName);
// acq.appendImage(img);
// add exposure to metadata
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
// JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
// acq.setSystemState(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, state);
// closeAcquisition(acqName);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getCurrentAlbum() {
return acqMgr_.getCurrentAlbum();
}
public String createNewAlbum() {
return acqMgr_.createNewAlbum();
}
public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
int f = 1 + acq.getLastAcquiredFrame();
try {
MDUtils.setFrameIndex(taggedImg.tags, f);
} catch (JSONException e) {
throw new MMScriptException("Unable to set the frame index.");
}
acq.insertTaggedImage(taggedImg, f, 0, 0);
}
public void addToAlbum(TaggedImage taggedImg) throws MMScriptException {
acqMgr_.addToAlbum(taggedImg);
}
public void addImage(String name, Object img, int frame, int channel,
int slice) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.insertImage(img, frame, channel, slice);
}
public void addImage(String name, TaggedImage taggedImg) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg);
}
public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay);
}
public void addImage(String name, TaggedImage taggedImg,
boolean updateDisplay,
boolean waitForDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay);
}
public void addImage(String name, TaggedImage taggedImg,
boolean updateDisplay,
boolean waitForDisplay,
boolean allowContrastToChange) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay, allowContrastToChange);
}
public void closeAllAcquisitions() {
acqMgr_.closeAll();
}
public String[] getAcquisitionNames()
{
return acqMgr_.getAcqusitionNames();
}
public MMAcquisition getAcquisition(String name) throws MMScriptException {
return acqMgr_.getAcquisition(name);
}
private class ScriptConsoleMessage implements Runnable {
String msg_;
public ScriptConsoleMessage(String text) {
msg_ = text;
}
public void run() {
if (scriptPanel_ != null)
scriptPanel_.message(msg_);
}
}
public void message(String text) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
SwingUtilities.invokeLater(new ScriptConsoleMessage(text));
}
}
public void clearMessageWindow() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.clearOutput();
}
}
public void clearOutput() throws MMScriptException {
clearMessageWindow();
}
public void clear() throws MMScriptException {
clearMessageWindow();
}
public void setChannelContrast(String title, int channel, int min, int max)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelContrast(channel, min, max);
}
public void setChannelName(String title, int channel, String name)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelName(channel, name);
}
public void setChannelColor(String title, int channel, Color color)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelColor(channel, color.getRGB());
}
public void setContrastBasedOnFrame(String title, int frame, int slice)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setContrastBasedOnFrame(frame, slice);
}
public void setStagePosition(double z) throws MMScriptException {
try {
core_.setPosition(core_.getFocusDevice(),z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setRelativeStagePosition(double z) throws MMScriptException {
try {
core_.setRelativePosition(core_.getFocusDevice(), z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setRelativeXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public Point2D.Double getXYStagePosition() throws MMScriptException {
String stage = core_.getXYStageDevice();
if (stage.length() == 0) {
throw new MMScriptException("XY Stage device is not available");
}
double x[] = new double[1];
double y[] = new double[1];
try {
core_.getXYPosition(stage, x, y);
Point2D.Double pt = new Point2D.Double(x[0], y[0]);
return pt;
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public String getXYStageName() {
return core_.getXYStageDevice();
}
public void setXYOrigin(double x, double y) throws MMScriptException {
String xyStage = core_.getXYStageDevice();
try {
core_.setAdapterOriginXY(xyStage, x, y);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
public AcquisitionEngine getAcquisitionEngine() {
return engine_;
}
public String installPlugin(Class<?> cl) {
String className = cl.getSimpleName();
String msg = className + " module loaded.";
try {
for (PluginItem plugin : plugins_) {
if (plugin.className.contentEquals(className)) {
return className + " already loaded.";
}
}
PluginItem pi = new PluginItem();
pi.className = className;
try {
// Get this static field from the class implementing MMPlugin.
pi.menuItem = (String) cl.getDeclaredField("menuName").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
pi.menuItem = className;
} catch (NoSuchFieldException e) {
pi.menuItem = className;
ReportingUtils.logError(className + " fails to implement static String menuName.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
if (pi.menuItem == null) {
pi.menuItem = className;
//core_.logMessage(className + " fails to implement static String menuName.");
}
pi.menuItem = pi.menuItem.replace("_", " ");
pi.pluginClass = cl;
plugins_.add(pi);
final PluginItem pi2 = pi;
final Class<?> cl2 = cl;
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
addPluginToMenu(pi2, cl2);
}
});
} catch (NoClassDefFoundError e) {
msg = className + " class definition not found.";
ReportingUtils.logError(e, msg);
}
return msg;
}
public String installPlugin(String className, String menuName) {
String msg = "installPlugin(String className, String menuName) is deprecated. Use installPlugin(String className) instead.";
core_.logMessage(msg);
installPlugin(className);
return msg;
}
public String installPlugin(String className) {
String msg = "";
try {
Class clazz = Class.forName(className);
return installPlugin(clazz);
} catch (ClassNotFoundException e) {
msg = className + " plugin not found.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(String className) {
try {
return installAutofocusPlugin(Class.forName(className));
} catch (ClassNotFoundException e) {
String msg = "Internal error: AF manager not instantiated.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(Class<?> autofocus) {
String msg = autofocus.getSimpleName() + " module loaded.";
if (afMgr_ != null) {
try {
afMgr_.refresh();
} catch (MMException e) {
msg = e.getMessage();
ReportingUtils.logError(e);
}
afMgr_.setAFPluginClassName(autofocus.getSimpleName());
} else {
msg = "Internal error: AF manager not instantiated.";
}
return msg;
}
public CMMCore getCore() {
return core_;
}
public Pipeline getPipeline() {
try {
pipelineClassLoadingThread_.join();
if (acquirePipeline_ == null) {
acquirePipeline_ = (Pipeline) pipelineClass_.newInstance();
}
return acquirePipeline_;
} catch (Exception e) {
ReportingUtils.logError(e);
return null;
}
}
public void snapAndAddToImage5D() {
try {
getPipeline().acquireSingle();
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public void setAcquisitionEngine(AcquisitionEngine eng) {
engine_ = eng;
}
public void suspendLiveMode() {
liveModeSuspended_ = isLiveModeOn();
enableLiveMode(false);
}
public void resumeLiveMode() {
if (liveModeSuspended_) {
enableLiveMode(true);
}
}
public Autofocus getAutofocus() {
return afMgr_.getDevice();
}
public void showAutofocusDialog() {
if (afMgr_.getDevice() != null) {
afMgr_.showOptionsDialog();
}
}
public AutofocusManager getAutofocusManager() {
return afMgr_;
}
public void selectConfigGroup(String groupName) {
configPad_.setGroup(groupName);
}
public String regenerateDeviceList() {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(resultFile, core_);
//MicroscopeModel.generateDeviceListFile();
setCursor(oldc);
return resultFile.toString();
}
private void loadPlugins() {
afMgr_ = new AutofocusManager(this);
ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>();
ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>();
List<Class<?>> classes;
try {
long t1 = System.currentTimeMillis();
classes = JavaUtils.findClasses(new File("mmplugins"), 2);
//System.out.println("findClasses: " + (System.currentTimeMillis() - t1));
//System.out.println(classes.size());
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == MMPlugin.class) {
pluginClasses.add(clazz);
}
}
}
classes = JavaUtils.findClasses(new File("mmautofocus"), 2);
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == Autofocus.class) {
autofocusClasses.add(clazz);
}
}
}
} catch (ClassNotFoundException e1) {
ReportingUtils.logError(e1);
}
for (Class<?> plugin : pluginClasses) {
try {
ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName());
installPlugin(plugin);
} catch (Exception e) {
ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin .");
}
}
for (Class<?> autofocus : autofocusClasses) {
try {
ReportingUtils.logMessage("Attempting to install autofocus plugin " + autofocus.getName());
installAutofocusPlugin(autofocus.getName());
} catch (Exception e) {
ReportingUtils.logError("Failed to install the \"" + autofocus.getName() + "\" autofocus plugin.");
}
}
}
/**
*
*/
private void setLiveModeInterval() {
double interval = 33.0;
try {
if (core_.getExposure() > 33.0) {
interval = core_.getExposure();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
liveModeInterval_ = interval;
}
public void logMessage(String msg) {
ReportingUtils.logMessage(msg);
}
public void showMessage(String msg) {
ReportingUtils.showMessage(msg);
}
public void logError(Exception e, String msg) {
ReportingUtils.logError(e, msg);
}
public void logError(Exception e) {
ReportingUtils.logError(e);
}
public void logError(String msg) {
ReportingUtils.logError(msg);
}
public void showError(Exception e, String msg) {
ReportingUtils.showError(e, msg);
}
public void showError(Exception e) {
ReportingUtils.showError(e);
}
public void showError(String msg) {
ReportingUtils.showError(msg);
}
private void runHardwareWizard(boolean v2) {
try {
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
configChanged_ = false;
}
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
// unload all devices before starting configurator
core_.reset();
GUIUtils.preventDisplayAdapterChangeExceptions();
// run Configurator
if (v2) {
ConfiguratorDlg2 cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_);
cfg2.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = cfg2.getFileName();
} else {
ConfiguratorDlg configurator = new ConfiguratorDlg(core_, sysConfigFile_);
configurator.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = configurator.getFileName();
}
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
GUIUtils.preventDisplayAdapterChangeExceptions();
if (liveRunning) {
enableLiveMode(liveRunning);
}
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
class BooleanLock extends Object {
private boolean value;
public BooleanLock(boolean initialValue) {
value = initialValue;
}
public BooleanLock() {
this(false);
}
public synchronized void setValue(boolean newValue) {
if (newValue != value) {
value = newValue;
notifyAll();
}
}
public synchronized boolean waitToSetTrue(long msTimeout)
throws InterruptedException {
boolean success = waitUntilFalse(msTimeout);
if (success) {
setValue(true);
}
return success;
}
public synchronized boolean waitToSetFalse(long msTimeout)
throws InterruptedException {
boolean success = waitUntilTrue(msTimeout);
if (success) {
setValue(false);
}
return success;
}
public synchronized boolean isTrue() {
return value;
}
public synchronized boolean isFalse() {
return !value;
}
public synchronized boolean waitUntilTrue(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(true, msTimeout);
}
public synchronized boolean waitUntilFalse(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(false, msTimeout);
}
public synchronized boolean waitUntilStateIs(
boolean state,
long msTimeout) throws InterruptedException {
if (msTimeout == 0L) {
while (value != state) {
wait();
}
return true;
}
long endTime = System.currentTimeMillis() + msTimeout;
long msRemaining = msTimeout;
while ((value != state) && (msRemaining > 0L)) {
wait(msRemaining);
msRemaining = endTime - System.currentTimeMillis();
}
return (value == state);
}
}
| mmstudio/src/org/micromanager/MMStudioMainFrame.java | ///////////////////////////////////////////////////////////////////////////////
//FILE: MMStudioMainFrame.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//AUTHOR: Nenad Amodaj, [email protected], Jul 18, 2005
// Modifications by Arthur Edelstein, Nico Stuurman
//COPYRIGHT: University of California, San Francisco, 2006-2010
// 100X Imaging Inc, www.100ximaging.com, 2008
//LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//CVS: $Id$
//
package org.micromanager;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.Line;
import ij.gui.Roi;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import java.util.Timer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.event.AncestorEvent;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.MMEventCallback;
import mmcorej.Metadata;
import mmcorej.StrVector;
import org.json.JSONObject;
import org.micromanager.acquisition.AcquisitionManager;
import org.micromanager.api.ImageCache;
import org.micromanager.api.ImageCacheListener;
import org.micromanager.acquisition.MMImageCache;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.Autofocus;
import org.micromanager.api.DeviceControlGUI;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.MMListenerInterface;
import org.micromanager.conf2.ConfiguratorDlg2;
import org.micromanager.conf.ConfiguratorDlg;
import org.micromanager.conf.MMConfigFileException;
import org.micromanager.conf.MicroscopeModel;
import org.micromanager.graph.ContrastPanel;
import org.micromanager.graph.GraphData;
import org.micromanager.graph.GraphFrame;
import org.micromanager.navigation.CenterAndDragListener;
import org.micromanager.navigation.PositionList;
import org.micromanager.navigation.XYZKeyListener;
import org.micromanager.navigation.ZWheelListener;
import org.micromanager.utils.AutofocusManager;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMImageWindow;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.TextUtils;
import org.micromanager.utils.TooltipTextMaker;
import org.micromanager.utils.WaitDialog;
import bsh.EvalError;
import bsh.Interpreter;
import com.swtdesigner.SwingResourceManager;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.process.FloatProcessor;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.KeyboardFocusManager;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.HashMap;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.event.AncestorListener;
import mmcorej.TaggedImage;
import org.json.JSONException;
import org.micromanager.acquisition.AcquisitionVirtualStack;
import org.micromanager.acquisition.AcquisitionWrapperEngine;
import org.micromanager.acquisition.LiveModeTimer;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.acquisition.MetadataPanel;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.acquisition.VirtualAcquisitionDisplay;
import org.micromanager.utils.ImageFocusListener;
import org.micromanager.api.Pipeline;
import org.micromanager.api.TaggedImageStorage;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.HotKeysDialog;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMKeyDispatcher;
import org.micromanager.utils.ReportingUtils;
/*
* Main panel and application class for the MMStudio.
*/
public class MMStudioMainFrame extends JFrame implements DeviceControlGUI, ScriptInterface {
private static final String MICRO_MANAGER_TITLE = "Micro-Manager 1.4";
private static final String VERSION = "1.4.7 20111110";
private static final long serialVersionUID = 3556500289598574541L;
private static final String MAIN_FRAME_X = "x";
private static final String MAIN_FRAME_Y = "y";
private static final String MAIN_FRAME_WIDTH = "width";
private static final String MAIN_FRAME_HEIGHT = "height";
private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos";
private static final String MAIN_EXPOSURE = "exposure";
private static final String SYSTEM_CONFIG_FILE = "sysconfig_file";
private static final String MAIN_STRETCH_CONTRAST = "stretch_contrast";
private static final String MAIN_REJECT_OUTLIERS = "reject_outliers";
private static final String MAIN_REJECT_FRACTION = "reject_fraction";
private static final String CONTRAST_SETTINGS_8_MIN = "contrast8_MIN";
private static final String CONTRAST_SETTINGS_8_MAX = "contrast8_MAX";
private static final String CONTRAST_SETTINGS_16_MIN = "contrast16_MIN";
private static final String CONTRAST_SETTINGS_16_MAX = "contrast16_MAX";
private static final String OPEN_ACQ_DIR = "openDataDir";
private static final String SCRIPT_CORE_OBJECT = "mmc";
private static final String SCRIPT_ACQENG_OBJECT = "acq";
private static final String SCRIPT_GUI_OBJECT = "gui";
private static final String AUTOFOCUS_DEVICE = "autofocus_device";
private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage";
private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000;
private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000;
// cfg file saving
private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4}
// GUI components
private JComboBox comboBinning_;
private JComboBox shutterComboBox_;
private JTextField textFieldExp_;
private JLabel labelImageDimensions_;
private JToggleButton toggleButtonLive_;
private JCheckBox autoShutterCheckBox_;
private boolean autoShutterOrg_;
private boolean shutterOrg_;
private MMOptions options_;
private boolean runsAsPlugin_;
private JCheckBoxMenuItem centerAndDragMenuItem_;
private JButton buttonSnap_;
private JButton buttonAutofocus_;
private JButton buttonAutofocusTools_;
private JToggleButton toggleButtonShutter_;
private GUIColors guiColors_;
private GraphFrame profileWin_;
private PropertyEditor propertyBrowser_;
private CalibrationListDlg calibrationListDlg_;
private AcqControlDlg acqControlWin_;
private ReportProblemDialog reportProblemDialog_;
private JMenu pluginMenu_;
private ArrayList<PluginItem> plugins_;
private List<MMListenerInterface> MMListeners_
= (List<MMListenerInterface>)
Collections.synchronizedList(new ArrayList<MMListenerInterface>());
private List<Component> MMFrames_
= (List<Component>)
Collections.synchronizedList(new ArrayList<Component>());
private AutofocusManager afMgr_;
private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg";
private ArrayList<String> MRUConfigFiles_;
private static final int maxMRUCfgs_ = 5;
private String sysConfigFile_;
private String startupScriptFile_;
private String sysStateFile_ = "MMSystemState.cfg";
private ConfigGroupPad configPad_;
private ContrastPanel contrastPanel_;
// Timer interval - image display interval
private double liveModeInterval_ = 40;
private LiveModeTimer liveModeTimer_;
private GraphData lineProfileData_;
// labels for standard devices
private String cameraLabel_;
private String zStageLabel_;
private String shutterLabel_;
private String xyStageLabel_;
// applications settings
private Preferences mainPrefs_;
private Preferences systemPrefs_;
private Preferences colorPrefs_;
// MMcore
private CMMCore core_;
private AcquisitionEngine engine_;
private PositionList posList_;
private PositionListDlg posListDlg_;
private String openAcqDirectory_ = "";
private boolean running_;
private boolean configChanged_ = false;
private StrVector shutters_ = null;
private JButton saveConfigButton_;
private ScriptPanel scriptPanel_;
private org.micromanager.utils.HotKeys hotKeys_;
private CenterAndDragListener centerAndDragListener_;
private ZWheelListener zWheelListener_;
private XYZKeyListener xyzKeyListener_;
private AcquisitionManager acqMgr_;
private static MMImageWindow imageWin_;
private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN};
private boolean multiChannelCamera_ = false;
private long multiChannelCameraNrCh_ = 0;
private int snapCount_ = -1;
private boolean liveModeSuspended_;
public Font defaultScriptFont_ = null;
public static final String MULTI_CAMERA_ACQ = "Multi-Camera Snap";
public static final String RGB_ACQ = "RGB-Camera Acquisition";
public static FileType MM_CONFIG_FILE
= new FileType("MM_CONFIG_FILE",
"Micro-Manager Config File",
"./MyScope.cfg",
true, "cfg");
// Our instance
private static MMStudioMainFrame gui_;
// Callback
private CoreEventCallback cb_;
// Lock invoked while shutting down
private final Object shutdownLock_ = new Object();
private JMenuBar menuBar_;
private ConfigPadButtonPanel configPadButtonPanel_;
private final JMenu switchConfigurationMenu_;
private final MetadataPanel metadataPanel_;
public static FileType MM_DATA_SET
= new FileType("MM_DATA_SET",
"Micro-Manager Image Location",
System.getProperty("user.home") + "/Untitled",
false, (String[]) null);
private Thread pipelineClassLoadingThread_ = null;
private Class pipelineClass_ = null;
private Pipeline acquirePipeline_ = null;
private final JSplitPane splitPane_;
private volatile boolean ignorePropertyChanges_;
public ImageWindow getImageWin() {
return imageWin_;
}
public static MMImageWindow getLiveWin() {
return imageWin_;
}
private void doSnapColor() {
checkRGBAcquisition();
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
core_.snapImage();
getAcquisition(RGB_ACQ).toFront();
TaggedImage ti = ImageUtils.makeTaggedImage(core_.getImage(),
0,
0,
0,
0,
getAcquisitionImageWidth(RGB_ACQ),
getAcquisitionImageHeight(RGB_ACQ),
getAcquisitionImageByteDepth(RGB_ACQ) );
addImage(RGB_ACQ,ti, true, true, false);
getAcquisition(RGB_ACQ).getAcquisitionWindow().setWindowTitle("RGB Snap");
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
private void doSnapFloat() {
try {
// just a test harness
core_.snapImage();
byte[] byteImage = (byte[]) core_.getImage();
int ii = (int)core_.getImageWidth();
int jj = (int)core_.getImageHeight();
int npoints = ii*jj;
float[] floatImage = new float[npoints];
ImagePlus implus = new ImagePlus();
int iiterator = 0;
int oiterator = 0;
for (; oiterator < npoints; ++oiterator) {
floatImage[oiterator] = Float.intBitsToFloat(((int) byteImage[iiterator+3 ] << 24) + ((int) byteImage[iiterator + 2] << 16) + ((int) byteImage[iiterator + 1] << 8) + (int) byteImage[iiterator]);
iiterator += 4;
}
FloatProcessor fp = new FloatProcessor(ii, jj, floatImage, null);
implus.setProcessor(fp);
ImageWindow iwindow = new ImageWindow(implus);
WindowManager.setCurrentWindow(iwindow);
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
private void doSnapMonochrome() {
try {
Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitCursor);
if (!isImageWindowOpen()) {
imageWin_ = createImageWindow();
}
if (imageWin_ == null) {
return;
}
imageWin_.toFront();
setIJCal(imageWin_);
// this is needed to clear the subtite, should be folded into
// drawInfo
imageWin_.getGraphics().clearRect(0, 0, imageWin_.getWidth(), 40);
imageWin_.drawInfo(imageWin_.getGraphics());
imageWin_.setSubTitle("Snap");
String expStr = textFieldExp_.getText();
if (expStr.length() > 0) {
core_.setExposure(NumberUtils.displayStringToDouble(expStr));
updateImage();
} else {
handleError("Exposure field is empty!");
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
private void checkMultiChannelWindow()
{
int w = (int) core_.getImageWidth();
int h = (int) core_.getImageHeight();
int d = (int) core_.getBytesPerPixel();
long c = core_.getNumberOfCameraChannels();
if (c > 1)
{
try {
ArrayList<String> chNames = new ArrayList<String>();
for (long i = 0; i < c; i++) {
chNames.add(core_.getCameraChannelName(i));
}
if (acquisitionExists(MULTI_CAMERA_ACQ)) {
if (c != (getAcquisition(MULTI_CAMERA_ACQ)).getChannels()) {
closeAcquisitionImage5D(MULTI_CAMERA_ACQ);
closeAcquisition(MULTI_CAMERA_ACQ);
}
if ( (getAcquisitionImageWidth(MULTI_CAMERA_ACQ) != w) ||
(getAcquisitionImageHeight(MULTI_CAMERA_ACQ) != h) ||
(getAcquisitionImageByteDepth(MULTI_CAMERA_ACQ) != d) ) {
closeAcquisitionImage5D(MULTI_CAMERA_ACQ);
closeAcquisition(MULTI_CAMERA_ACQ);
}
}
if (!acquisitionExists(MULTI_CAMERA_ACQ)) {
openAcquisition(MULTI_CAMERA_ACQ, "", 1, (int) c, 1, true);
for (long i = 0; i < c; i++) {
String chName = core_.getCameraChannelName(i);
int defaultColor = multiCameraColors_[(int)i % multiCameraColors_.length].getRGB();
setChannelColor(MULTI_CAMERA_ACQ, (int) i,
getChannelColor(chName, defaultColor) );
setChannelName(MULTI_CAMERA_ACQ, (int) i, chName);
}
initializeAcquisition(MULTI_CAMERA_ACQ, w, h, d);
getAcquisition(MULTI_CAMERA_ACQ).promptToSave(false);
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
}
private void checkRGBAcquisition()
{
int w = (int) core_.getImageWidth();
int h = (int) core_.getImageHeight();
int d = (int) core_.getBytesPerPixel();
try {
if (acquisitionExists(RGB_ACQ)) {
if ( (getAcquisitionImageWidth(RGB_ACQ) != w) ||
(getAcquisitionImageHeight(RGB_ACQ) != h) ||
(getAcquisitionImageByteDepth(RGB_ACQ) != d) )
{
closeAcquisitionImage5D(RGB_ACQ);
closeAcquisition(RGB_ACQ);
openAcquisition(RGB_ACQ, "", 1, 1, 1, true);
initializeAcquisition(RGB_ACQ, w, h, d);
getAcquisition(RGB_ACQ).promptToSave(false);
}
} else {
openAcquisition(RGB_ACQ, "", 1, 1, 1, true); //creates new acquisition
initializeAcquisition(RGB_ACQ, w, h, d);
getAcquisition(RGB_ACQ).promptToSave(false);
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
public void saveChannelColor(String chName, int rgb)
{
if (colorPrefs_ != null) {
colorPrefs_.putInt("Color_" + chName, rgb);
}
}
public Color getChannelColor(String chName, int defaultColor)
{
if (colorPrefs_ != null) {
defaultColor = colorPrefs_.getInt("Color_" + chName, defaultColor);
}
return new Color(defaultColor);
}
/**
* Snaps an image for a multi-Channel camera
* This version does not (yet) support attachment of mouse listeners
* for stage movement.
*/
private void doSnapMultiCamera()
{
checkMultiChannelWindow();
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
core_.snapImage();
getAcquisition(MULTI_CAMERA_ACQ).toFront();
long c = core_.getNumberOfCameraChannels();
for (int i = 0; i < c; i++) {
TaggedImage ti = ImageUtils.makeTaggedImage(core_.getImage(i),
i,
0,
0,
0,
getAcquisitionImageWidth(MULTI_CAMERA_ACQ),
getAcquisitionImageHeight(MULTI_CAMERA_ACQ),
getAcquisitionImageByteDepth(MULTI_CAMERA_ACQ) );
boolean update = false;
if (i == c -1)
update = true;
addImage(MULTI_CAMERA_ACQ,ti, update, true, false);
getAcquisition(MULTI_CAMERA_ACQ).getAcquisitionWindow().setWindowTitle("Multi Camera Snap");
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
private void initializeHelpMenu() {
// add help menu item
final JMenu helpMenu = new JMenu();
helpMenu.setText("Help");
menuBar_.add(helpMenu);
final JMenuItem usersGuideMenuItem = new JMenuItem();
usersGuideMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_User%27s_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
usersGuideMenuItem.setText("User's Guide...");
helpMenu.add(usersGuideMenuItem);
final JMenuItem configGuideMenuItem = new JMenuItem();
configGuideMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_Configuration_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
configGuideMenuItem.setText("Configuration Guide...");
helpMenu.add(configGuideMenuItem);
if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) {
final JMenuItem registerMenuItem = new JMenuItem();
registerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_);
regDlg.setVisible(true);
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
});
registerMenuItem.setText("Register your copy of Micro-Manager...");
helpMenu.add(registerMenuItem);
}
final MMStudioMainFrame thisFrame = this;
final JMenuItem reportProblemMenuItem = new JMenuItem();
reportProblemMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (null == reportProblemDialog_) {
reportProblemDialog_ = new ReportProblemDialog(core_, thisFrame, sysConfigFile_, options_);
thisFrame.addMMBackgroundListener(reportProblemDialog_);
reportProblemDialog_.setBackground(guiColors_.background.get(options_.displayBackground_));
}
reportProblemDialog_.setVisible(true);
}
});
reportProblemMenuItem.setText("Report Problem");
helpMenu.add(reportProblemMenuItem);
final JMenuItem aboutMenuItem = new JMenuItem();
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MMAboutDlg dlg = new MMAboutDlg();
String versionInfo = "MM Studio version: " + VERSION;
versionInfo += "\n" + core_.getVersionInfo();
versionInfo += "\n" + core_.getAPIVersionInfo();
versionInfo += "\nUser: " + core_.getUserId();
versionInfo += "\nHost: " + core_.getHostName();
dlg.setVersionInfo(versionInfo);
dlg.setVisible(true);
}
});
aboutMenuItem.setText("About Micromanager...");
helpMenu.add(aboutMenuItem);
menuBar_.validate();
}
private void updateSwitchConfigurationMenu() {
switchConfigurationMenu_.removeAll();
for (final String configFile : MRUConfigFiles_) {
if (! configFile.equals(sysConfigFile_)) {
JMenuItem configMenuItem = new JMenuItem();
configMenuItem.setText(configFile);
configMenuItem.addActionListener(new ActionListener() {
String theConfigFile = configFile;
public void actionPerformed(ActionEvent e) {
sysConfigFile_ = theConfigFile;
loadSystemConfiguration();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
}
});
switchConfigurationMenu_.add(configMenuItem);
}
}
}
/**
* Allows MMListeners to register themselves
*/
public void addMMListener(MMListenerInterface newL) {
if (MMListeners_.contains(newL))
return;
MMListeners_.add(newL);
}
/**
* Allows MMListeners to remove themselves
*/
public void removeMMListener(MMListenerInterface oldL) {
if (!MMListeners_.contains(oldL))
return;
MMListeners_.remove(oldL);
}
/**
* Lets JComponents register themselves so that their background can be
* manipulated
*/
public void addMMBackgroundListener(Component comp) {
if (MMFrames_.contains(comp))
return;
MMFrames_.add(comp);
}
/**
* Lets JComponents remove themselves from the list whose background gets
* changes
*/
public void removeMMBackgroundListener(Component comp) {
if (!MMFrames_.contains(comp))
return;
MMFrames_.remove(comp);
}
public void updateContrast(ImagePlus iplus) {
contrastPanel_.updateContrast(iplus);
}
/**
* Part of ScriptInterface
* Manipulate acquisition so that it looks like a burst
*/
public void runBurstAcquisition() throws MMScriptException {
double interval = engine_.getFrameIntervalMs();
int nr = engine_.getNumFrames();
boolean doZStack = engine_.isZSliceSettingEnabled();
boolean doChannels = engine_.isChannelsSettingEnabled();
engine_.enableZSliceSetting(false);
engine_.setFrames(nr, 0);
engine_.enableChannelsSetting(false);
try {
engine_.acquire();
} catch (MMException e) {
throw new MMScriptException(e);
}
engine_.setFrames(nr, interval);
engine_.enableZSliceSetting(doZStack);
engine_.enableChannelsSetting(doChannels);
}
public void runBurstAcquisition(int nr) throws MMScriptException {
int originalNr = engine_.getNumFrames();
double interval = engine_.getFrameIntervalMs();
engine_.setFrames(nr, 0);
this.runBurstAcquisition();
engine_.setFrames(originalNr, interval);
}
public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException {
//String originalName = engine_.getDirName();
String originalRoot = engine_.getRootName();
engine_.setDirName(name);
engine_.setRootName(root);
this.runBurstAcquisition(nr);
engine_.setRootName(originalRoot);
//engine_.setDirName(originalDirName);
}
/**
* @deprecated
* @throws MMScriptException
*/
public void startBurstAcquisition() throws MMScriptException {
runAcquisition();
}
public boolean isBurstAcquisitionRunning() throws MMScriptException {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
private void startLoadingPipelineClass() {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
pipelineClassLoadingThread_ = new Thread("Pipeline Class loading thread") {
@Override
public void run() {
try {
pipelineClass_ = Class.forName("org.micromanager.AcqEngine");
} catch (Exception ex) {
ReportingUtils.logError(ex);
pipelineClass_ = null;
}
}
};
pipelineClassLoadingThread_.start();
}
public void addImageStorageListener(ImageCacheListener listener) {
throw new UnsupportedOperationException("Not supported yet.");
}
public ImageCache getAcquisitionImageCache(String acquisitionName) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Callback to update GUI when a change happens in the MMCore.
*/
public class CoreEventCallback extends MMEventCallback {
public CoreEventCallback() {
super();
}
@Override
public void onPropertiesChanged() {
// TODO: remove test once acquisition engine is fully multithreaded
if (engine_ != null && engine_.isAcquisitionRunning()) {
core_.logMessage("Notification from MMCore ignored because acquistion is running!");
} else {
if (ignorePropertyChanges_) {
core_.logMessage("Notification from MMCore ignored since the system is still loading");
} else {
core_.updateSystemStateCache();
updateGUI(true);
// update all registered listeners
for (MMListenerInterface mmIntf : MMListeners_) {
mmIntf.propertiesChangedAlert();
}
core_.logMessage("Notification from MMCore!");
}
}
}
@Override
public void onPropertyChanged(String deviceName, String propName, String propValue) {
core_.logMessage("Notification for Device: " + deviceName + " Property: " +
propName + " changed to value: " + propValue);
// update all registered listeners
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.propertyChangedAlert(deviceName, propName, propValue);
}
}
@Override
public void onConfigGroupChanged(String groupName, String newConfig) {
try {
configPad_.refreshGroup(groupName, newConfig);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.configGroupChangedAlert(groupName, newConfig);
}
} catch (Exception e) {
}
}
@Override
public void onPixelSizeChanged(double newPixelSizeUm) {
updatePixSizeUm (newPixelSizeUm);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.pixelSizeChangedAlert(newPixelSizeUm);
}
}
@Override
public void onStagePositionChanged(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_)) {
updateZPos(pos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.stagePositionChangedAlert(deviceName, pos);
}
}
}
@Override
public void onStagePositionChangedRelative(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_))
updateZPosRelative(pos);
}
@Override
public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_)) {
updateXYPos(xPos, yPos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.xyStagePositionChanged(deviceName, xPos, yPos);
}
}
}
@Override
public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_))
updateXYPosRelative(xPos, yPos);
}
}
private class PluginItem {
public Class<?> pluginClass = null;
public String menuItem = "undefined";
public MMPlugin plugin = null;
public String className = "";
public void instantiate() {
try {
if (plugin == null) {
plugin = (MMPlugin) pluginClass.newInstance();
}
} catch (InstantiationException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
plugin.setApp(MMStudioMainFrame.this);
}
}
/*
* Simple class used to cache static info
*/
private class StaticInfo {
public long width_;
public long height_;
public long bytesPerPixel_;
public long imageBitDepth_;
public double pixSizeUm_;
public double zPos_;
public double x_;
public double y_;
}
private StaticInfo staticInfo_ = new StaticInfo();
/**
* Main procedure for stand alone operation.
*/
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MMStudioMainFrame frame = new MMStudioMainFrame(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
} catch (Throwable e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
}
}
public MMStudioMainFrame(boolean pluginStatus) {
super();
startLoadingPipelineClass();
options_ = new MMOptions();
try {
options_.loadSettings();
} catch (NullPointerException ex) {
ReportingUtils.logError(ex);
}
guiColors_ = new GUIColors();
plugins_ = new ArrayList<PluginItem>();
gui_ = this;
runsAsPlugin_ = pluginStatus;
setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class,
"icons/microscope.gif"));
running_ = true;
acqMgr_ = new AcquisitionManager();
sysConfigFile_ = System.getProperty("user.dir") + "/"
+ DEFAULT_CONFIG_FILE_NAME;
if (options_.startupScript_.length() > 0) {
startupScriptFile_ = System.getProperty("user.dir") + "/"
+ options_.startupScript_;
} else {
startupScriptFile_ = "";
}
ReportingUtils.SetContainingFrame(gui_);
// set the location for app preferences
try {
mainPrefs_ = Preferences.userNodeForPackage(this.getClass());
} catch (Exception e) {
ReportingUtils.logError(e);
}
systemPrefs_ = mainPrefs_;
colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
AcqControlDlg.COLOR_SETTINGS_NODE);
// check system preferences
try {
Preferences p = Preferences.systemNodeForPackage(this.getClass());
if (null != p) {
// if we can not write to the systemPrefs, use AppPrefs instead
if (JavaUtils.backingStoreAvailable(p)) {
systemPrefs_ = p;
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
// show registration dialog if not already registered
// first check user preferences (for legacy compatibility reasons)
boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,
false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!userReg) {
boolean systemReg = systemPrefs_.getBoolean(
RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!systemReg) {
// prompt for registration info
RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);
dlg.setVisible(true);
}
}
// load application preferences
// NOTE: only window size and position preferences are loaded,
// not the settings for the camera and live imaging -
// attempting to set those automatically on startup may cause problems
// with the hardware
int x = mainPrefs_.getInt(MAIN_FRAME_X, 100);
int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100);
int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 580);
int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 482);
boolean stretch = mainPrefs_.getBoolean(MAIN_STRETCH_CONTRAST, true);
boolean reject = mainPrefs_.getBoolean(MAIN_REJECT_OUTLIERS, false);
double rejectFract = mainPrefs_.getDouble(MAIN_REJECT_FRACTION, 0.027);
int dividerPos = mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 178);
openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, "");
ToolTipManager ttManager = ToolTipManager.sharedInstance();
ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS);
ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS);
setBounds(x, y, width, height);
setExitStrategy(options_.closeOnExit_);
setTitle(MICRO_MANAGER_TITLE);
setBackground(guiColors_.background.get((options_.displayBackground_)));
SpringLayout topLayout = new SpringLayout();
this.setMinimumSize(new Dimension(580,480));
JPanel topPanel = new JPanel();
topPanel.setLayout(topLayout);
topPanel.setMinimumSize(new Dimension(580, 175));
class ListeningJPanel extends JPanel implements AncestorListener {
public void ancestorMoved(AncestorEvent event) {
//System.out.println("moved!");
}
public void ancestorRemoved(AncestorEvent event) {}
public void ancestorAdded(AncestorEvent event) {}
}
ListeningJPanel bottomPanel = new ListeningJPanel();
bottomPanel.setLayout(topLayout);
splitPane_ = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
topPanel, bottomPanel);
splitPane_.setBorder(BorderFactory.createEmptyBorder());
splitPane_.setDividerLocation(dividerPos);
splitPane_.setResizeWeight(0.0);
splitPane_.addAncestorListener(bottomPanel);
getContentPane().add(splitPane_);
// Snap button
// -----------
buttonSnap_ = new JButton();
buttonSnap_.setIconTextGap(6);
buttonSnap_.setText("Snap");
buttonSnap_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/camera.png"));
buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonSnap_.setToolTipText("Snap single image");
buttonSnap_.setMaximumSize(new Dimension(0, 0));
buttonSnap_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSnap();
}
});
topPanel.add(buttonSnap_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonSnap_, 4,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonSnap_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonSnap_, 7,
SpringLayout.WEST, topPanel);
// Initialize
// ----------
// Exposure field
// ---------------
final JLabel label_1 = new JLabel();
label_1.setFont(new Font("Arial", Font.PLAIN, 10));
label_1.setText("Exposure [ms]");
topPanel.add(label_1);
topLayout.putConstraint(SpringLayout.EAST, label_1, 198,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, label_1, 111,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, label_1, 39,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, label_1, 23,
SpringLayout.NORTH, topPanel);
textFieldExp_ = new JTextField();
textFieldExp_.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent fe) {
synchronized(shutdownLock_) {
if (core_ != null)
setExposure();
}
}
});
textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10));
textFieldExp_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setExposure();
}
});
topPanel.add(textFieldExp_);
topLayout.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, textFieldExp_, 21,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, textFieldExp_, 276,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, textFieldExp_, 203,
SpringLayout.WEST, topPanel);
// Live button
// -----------
toggleButtonLive_ = new JToggleButton();
toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2));
toggleButtonLive_.setIconTextGap(1);
toggleButtonLive_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setIconTextGap(6);
toggleButtonLive_.setToolTipText("Continuous live view");
toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10));
toggleButtonLive_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!isLiveModeOn()) {
// Display interval for Live Mode changes as well
setLiveModeInterval();
}
enableLiveMode(!isLiveModeOn());
}
});
toggleButtonLive_.setText("Live");
topPanel.add(toggleButtonLive_);
topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7,
SpringLayout.WEST, topPanel);
// Acquire button
// -----------
JButton acquireButton = new JButton();
acquireButton.setMargin(new Insets(2, 2, 2, 2));
acquireButton.setIconTextGap(1);
acquireButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/snapAppend.png"));
acquireButton.setIconTextGap(6);
acquireButton.setToolTipText("Acquire single frame and add to an album");
acquireButton.setFont(new Font("Arial", Font.PLAIN, 10));
acquireButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snapAndAddToImage5D();
}
});
acquireButton.setText("Acquire");
topPanel.add(acquireButton);
topLayout.putConstraint(SpringLayout.SOUTH, acquireButton, 69,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, acquireButton, 48,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, acquireButton, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, acquireButton, 7,
SpringLayout.WEST, topPanel);
// Shutter button
// --------------
toggleButtonShutter_ = new JToggleButton();
toggleButtonShutter_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
toggleShutter();
}
});
toggleButtonShutter_.setToolTipText("Open/close the shutter");
toggleButtonShutter_.setIconTextGap(6);
toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10));
toggleButtonShutter_.setText("Open");
topPanel.add(toggleButtonShutter_);
topLayout.putConstraint(SpringLayout.EAST, toggleButtonShutter_,
275, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toggleButtonShutter_,
203, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_,
138 - 21, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toggleButtonShutter_,
117 - 21, SpringLayout.NORTH, topPanel);
// Active shutter label
final JLabel activeShutterLabel = new JLabel();
activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10));
activeShutterLabel.setText("Shutter");
topPanel.add(activeShutterLabel);
topLayout.putConstraint(SpringLayout.SOUTH, activeShutterLabel,
108 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, activeShutterLabel,
95 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, activeShutterLabel,
160 - 2, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, activeShutterLabel,
113 - 2, SpringLayout.WEST, topPanel);
// Active shutter Combo Box
shutterComboBox_ = new JComboBox();
shutterComboBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
if (shutterComboBox_.getSelectedItem() != null) {
core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
return;
}
});
topPanel.add(shutterComboBox_);
topLayout.putConstraint(SpringLayout.SOUTH, shutterComboBox_,
114 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, shutterComboBox_,
92 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, shutterComboBox_, 275,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, shutterComboBox_, 170,
SpringLayout.WEST, topPanel);
menuBar_ = new JMenuBar();
setJMenuBar(menuBar_);
final JMenu fileMenu = new JMenu();
fileMenu.setText("File");
menuBar_.add(fileMenu);
final JMenuItem openMenuItem = new JMenuItem();
openMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
openAcquisitionData();
}
}.start();
}
});
openMenuItem.setText("Open Acquisition Data...");
fileMenu.add(openMenuItem);
fileMenu.addSeparator();
final JMenuItem loadState = new JMenuItem();
loadState.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemState();
}
});
loadState.setText("Load System State...");
fileMenu.add(loadState);
final JMenuItem saveStateAs = new JMenuItem();
fileMenu.add(saveStateAs);
saveStateAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveSystemState();
}
});
saveStateAs.setText("Save System State As...");
fileMenu.addSeparator();
final JMenuItem exitMenuItem = new JMenuItem();
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeSequence();
}
});
fileMenu.add(exitMenuItem);
exitMenuItem.setText("Exit");
/*
final JMenu image5dMenu = new JMenu();
image5dMenu.setText("Image5D");
menuBar_.add(image5dMenu);
final JMenuItem closeAllMenuItem = new JMenuItem();
closeAllMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
WindowManager.closeAllWindows();
}
});
closeAllMenuItem.setText("Close All");
image5dMenu.add(closeAllMenuItem);
final JMenuItem duplicateMenuItem = new JMenuItem();
duplicateMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Duplicate_Image5D duplicate = new Duplicate_Image5D();
duplicate.run("");
}
});
duplicateMenuItem.setText("Duplicate");
image5dMenu.add(duplicateMenuItem);
final JMenuItem cropMenuItem = new JMenuItem();
cropMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Crop_Image5D crop = new Crop_Image5D();
crop.run("");
}
});
cropMenuItem.setText("Crop");
image5dMenu.add(cropMenuItem);
final JMenuItem makeMontageMenuItem = new JMenuItem();
makeMontageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Make_Montage makeMontage = new Make_Montage();
makeMontage.run("");
}
});
makeMontageMenuItem.setText("Make Montage");
image5dMenu.add(makeMontageMenuItem);
final JMenuItem zProjectMenuItem = new JMenuItem();
zProjectMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Z_Project projection = new Z_Project();
projection.run("");
}
});
zProjectMenuItem.setText("Z Project");
image5dMenu.add(zProjectMenuItem);
final JMenuItem convertToRgbMenuItem = new JMenuItem();
convertToRgbMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB();
stackToRGB.run("");
}
});
convertToRgbMenuItem.setText("Copy to RGB Stack(z)");
image5dMenu.add(convertToRgbMenuItem);
final JMenuItem convertToRgbtMenuItem = new JMenuItem();
convertToRgbtMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t();
stackToRGB_t.run("");
}
});
convertToRgbtMenuItem.setText("Copy to RGB Stack(t)");
image5dMenu.add(convertToRgbtMenuItem);
final JMenuItem convertToStackMenuItem = new JMenuItem();
convertToStackMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_Stack image5DToStack = new Image5D_to_Stack();
image5DToStack.run("");
}
});
convertToStackMenuItem.setText("Copy to Stack");
image5dMenu.add(convertToStackMenuItem);
final JMenuItem convertToStacksMenuItem = new JMenuItem();
convertToStacksMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks();
image5DToStacks.run("");
}
});
convertToStacksMenuItem.setText("Copy to Stacks (channels)");
image5dMenu.add(convertToStacksMenuItem);
final JMenuItem volumeViewerMenuItem = new JMenuItem();
volumeViewerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer();
volumeViewer.run("");
}
});
volumeViewerMenuItem.setText("VolumeViewer");
image5dMenu.add(volumeViewerMenuItem);
final JMenuItem splitImageMenuItem = new JMenuItem();
splitImageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Split_Image5D splitImage = new Split_Image5D();
splitImage.run("");
}
});
splitImageMenuItem.setText("SplitView");
image5dMenu.add(splitImageMenuItem);
*/
final JMenu toolsMenu = new JMenu();
toolsMenu.setText("Tools");
menuBar_.add(toolsMenu);
final JMenuItem refreshMenuItem = new JMenuItem();
refreshMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/arrow_refresh.png"));
refreshMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.updateSystemStateCache();
updateGUI(true);
}
});
refreshMenuItem.setText("Refresh GUI");
refreshMenuItem.setToolTipText("Refresh all GUI controls directly from the hardware");
toolsMenu.add(refreshMenuItem);
final JMenuItem rebuildGuiMenuItem = new JMenuItem();
rebuildGuiMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
initializeGUI();
core_.updateSystemStateCache();
}
});
rebuildGuiMenuItem.setText("Rebuild GUI");
rebuildGuiMenuItem.setToolTipText("Regenerate micromanager user interface");
toolsMenu.add(rebuildGuiMenuItem);
toolsMenu.addSeparator();
final JMenuItem scriptPanelMenuItem = new JMenuItem();
toolsMenu.add(scriptPanelMenuItem);
scriptPanelMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scriptPanel_.setVisible(true);
}
});
scriptPanelMenuItem.setText("Script Panel...");
scriptPanelMenuItem.setToolTipText("Open micromanager script editor window");
final JMenuItem hotKeysMenuItem = new JMenuItem();
toolsMenu.add(hotKeysMenuItem);
hotKeysMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
HotKeysDialog hk = new HotKeysDialog
(guiColors_.background.get((options_.displayBackground_)));
//hk.setBackground(guiColors_.background.get((options_.displayBackground_)));
}
});
hotKeysMenuItem.setText("Shortcuts...");
hotKeysMenuItem.setToolTipText("Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts");
final JMenuItem propertyEditorMenuItem = new JMenuItem();
toolsMenu.add(propertyEditorMenuItem);
propertyEditorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createPropertyEditor();
}
});
propertyEditorMenuItem.setText("Device/Property Browser...");
propertyEditorMenuItem.setToolTipText("Open new window to view and edit property values in current configuration");
toolsMenu.addSeparator();
final JMenuItem xyListMenuItem = new JMenuItem();
xyListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showXYPositionList();
}
});
xyListMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/application_view_list.png"));
xyListMenuItem.setText("XY List...");
toolsMenu.add(xyListMenuItem);
xyListMenuItem.setToolTipText("Open position list manager window");
final JMenuItem acquisitionMenuItem = new JMenuItem();
acquisitionMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
acquisitionMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/film.png"));
acquisitionMenuItem.setText("Multi-Dimensional Acquisition...");
toolsMenu.add(acquisitionMenuItem);
acquisitionMenuItem.setToolTipText("Open multi-dimensional acquisition window");
/*
final JMenuItem splitViewMenuItem = new JMenuItem();
splitViewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
splitViewDialog();
}
});
splitViewMenuItem.setText("Split View...");
toolsMenu.add(splitViewMenuItem);
*/
centerAndDragMenuItem_ = new JCheckBoxMenuItem();
centerAndDragMenuItem_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (centerAndDragListener_ == null) {
centerAndDragListener_ = new CenterAndDragListener(core_, gui_);
}
if (!centerAndDragListener_.isRunning()) {
centerAndDragListener_.start();
centerAndDragMenuItem_.setSelected(true);
} else {
centerAndDragListener_.stop();
centerAndDragMenuItem_.setSelected(false);
}
mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected());
}
});
centerAndDragMenuItem_.setText("Mouse Moves Stage");
centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false));
centerAndDragMenuItem_.setToolTipText("When enabled, double clicking in live window moves stage");
toolsMenu.add(centerAndDragMenuItem_);
final JMenuItem calibrationMenuItem = new JMenuItem();
toolsMenu.add(calibrationMenuItem);
calibrationMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createCalibrationListDlg();
}
});
calibrationMenuItem.setText("Pixel Size Calibration...");
toolsMenu.add(calibrationMenuItem);
String calibrationTooltip = "Define size calibrations specific to each objective lens. " +
"When the objective in use has a calibration defined, " +
"micromanager will automatically use it when " +
"calculating metadata";
String mrjProp = System.getProperty("mrj.version");
if (mrjProp != null && !mrjProp.equals(null)) // running on a mac
calibrationMenuItem.setToolTipText(calibrationTooltip);
else
calibrationMenuItem.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip(calibrationTooltip));
toolsMenu.addSeparator();
final JMenuItem configuratorMenuItem = new JMenuItem();
configuratorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// true - new wizard
// false - old wizard
runHardwareWizard(false);
}
});
configuratorMenuItem.setText("Hardware Configuration Wizard...");
toolsMenu.add(configuratorMenuItem);
configuratorMenuItem.setToolTipText("Open wizard to create new hardware configuration");
final JMenuItem loadSystemConfigMenuItem = new JMenuItem();
toolsMenu.add(loadSystemConfigMenuItem);
loadSystemConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadConfiguration();
initializeGUI();
}
});
loadSystemConfigMenuItem.setText("Load Hardware Configuration...");
loadSystemConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize new one");
switchConfigurationMenu_ = new JMenu();
for (int i=0; i<5; i++)
{
JMenuItem configItem = new JMenuItem();
configItem.setText(Integer.toString(i));
switchConfigurationMenu_.add(configItem);
}
final JMenuItem reloadConfigMenuItem = new JMenuItem();
toolsMenu.add(reloadConfigMenuItem);
reloadConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemConfiguration();
initializeGUI();
}
});
reloadConfigMenuItem.setText("Reload Hardware Configuration");
reloadConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize most recently loaded configuration");
switchConfigurationMenu_.setText("Switch Hardware Configuration");
toolsMenu.add(switchConfigurationMenu_);
switchConfigurationMenu_.setToolTipText("Switch between recently used configurations");
final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem();
saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
updateChannelCombos();
}
});
saveConfigurationPresetsMenuItem.setText("Save Configuration Settings as...");
toolsMenu.add(saveConfigurationPresetsMenuItem);
saveConfigurationPresetsMenuItem.setToolTipText("Save current configuration settings as new configuration file");
/*
final JMenuItem regenerateConfiguratorDeviceListMenuItem = new JMenuItem();
regenerateConfiguratorDeviceListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(options_.enableDeviceDiscovery_, resultFile,core_);
setCursor(oldc);
}
});
regenerateConfiguratorDeviceListMenuItem.setText("Regenerate Configurator Device List");
toolsMenu.add(regenerateConfiguratorDeviceListMenuItem);
*/
toolsMenu.addSeparator();
final MMStudioMainFrame thisInstance = this;
final JMenuItem optionsMenuItem = new JMenuItem();
optionsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
int oldBufsize = options_.circularBufferSizeMB_;
OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_,
thisInstance, sysConfigFile_);
dlg.setVisible(true);
// adjust memory footprint if necessary
if (oldBufsize != options_.circularBufferSizeMB_) {
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception exc) {
ReportingUtils.showError(exc);
}
}
}
});
optionsMenuItem.setText("Options...");
toolsMenu.add(optionsMenuItem);
final JLabel binningLabel = new JLabel();
binningLabel.setFont(new Font("Arial", Font.PLAIN, 10));
binningLabel.setText("Binning");
topPanel.add(binningLabel);
topLayout.putConstraint(SpringLayout.SOUTH, binningLabel, 64,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, binningLabel, 43,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1,
SpringLayout.WEST, topPanel);
labelImageDimensions_ = new JLabel();
labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10));
bottomPanel.add(labelImageDimensions_);
topLayout.putConstraint(SpringLayout.SOUTH, labelImageDimensions_,
-5, SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, labelImageDimensions_,
-25, SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, labelImageDimensions_,
-5, SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, labelImageDimensions_,
5, SpringLayout.WEST, bottomPanel);
comboBinning_ = new JComboBox();
comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10));
comboBinning_.setMaximumRowCount(4);
comboBinning_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeBinning();
}
});
topPanel.add(comboBinning_);
topLayout.putConstraint(SpringLayout.EAST, comboBinning_, 275,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, comboBinning_, 200,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, comboBinning_, 66,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, comboBinning_, 43,
SpringLayout.NORTH, topPanel);
final JLabel cameraSettingsLabel = new JLabel();
cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11));
cameraSettingsLabel.setText("Camera settings");
topPanel.add(cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.EAST, cameraSettingsLabel,
211, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.WEST, cameraSettingsLabel,
109, SpringLayout.WEST, topPanel);
configPad_ = new ConfigGroupPad();
configPad_.setFont(new Font("", Font.PLAIN, 10));
topPanel.add(configPad_);
topLayout.putConstraint(SpringLayout.EAST, configPad_, -4,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, configPad_, 5,
SpringLayout.EAST, comboBinning_);
topLayout.putConstraint(SpringLayout.SOUTH, configPad_, -21,
SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, configPad_, 21,
SpringLayout.NORTH, topPanel);
configPadButtonPanel_ = new ConfigPadButtonPanel();
configPadButtonPanel_.setConfigPad(configPad_);
configPadButtonPanel_.setGUI(MMStudioMainFrame.this);
topPanel.add(configPadButtonPanel_);
topLayout.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5,
SpringLayout.EAST, comboBinning_);
topLayout.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, 0,
SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, -18,
SpringLayout.SOUTH, topPanel);
final JLabel stateDeviceLabel = new JLabel();
stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11));
stateDeviceLabel.setText("Configuration settings");
topPanel.add(stateDeviceLabel);
topLayout.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0,
SpringLayout.SOUTH, cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0,
SpringLayout.NORTH, cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150,
SpringLayout.WEST, configPad_);
topLayout.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0,
SpringLayout.WEST, configPad_);
final JButton buttonAcqSetup = new JButton();
buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2));
buttonAcqSetup.setIconTextGap(1);
buttonAcqSetup.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/film.png"));
buttonAcqSetup.setToolTipText("Open multi-dimensional acquisition window");
buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAcqSetup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
buttonAcqSetup.setText("Multi-D Acq.");
topPanel.add(buttonAcqSetup);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7,
SpringLayout.WEST, topPanel);
autoShutterCheckBox_ = new JCheckBox();
autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
autoShutterCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.setAutoShutter(autoShutterCheckBox_.isSelected());
if (shutterLabel_.length() > 0) {
try {
setShutterButton(core_.getShutterOpen());
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
if (autoShutterCheckBox_.isSelected()) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
}
});
autoShutterCheckBox_.setIconTextGap(6);
autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);
autoShutterCheckBox_.setText("Auto shutter");
topPanel.add(autoShutterCheckBox_);
topLayout.putConstraint(SpringLayout.EAST, autoShutterCheckBox_,
202 - 3, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, autoShutterCheckBox_,
110 - 3, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_,
141 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_,
118 - 22, SpringLayout.NORTH, topPanel);
final JButton refreshButton = new JButton();
refreshButton.setMargin(new Insets(2, 2, 2, 2));
refreshButton.setIconTextGap(1);
refreshButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_refresh.png"));
refreshButton.setFont(new Font("Arial", Font.PLAIN, 10));
refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware");
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.updateSystemStateCache();
updateGUI(true);
}
});
refreshButton.setText("Refresh");
topPanel.add(refreshButton);
topLayout.putConstraint(SpringLayout.SOUTH, refreshButton, 113,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, refreshButton, 92,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, refreshButton, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, refreshButton, 7,
SpringLayout.WEST, topPanel);
JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>");
topPanel.add(citePleaLabel);
citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11));
topLayout.putConstraint(SpringLayout.SOUTH, citePleaLabel, 139,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, citePleaLabel, 119,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, citePleaLabel, 270,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, citePleaLabel, 7,
SpringLayout.WEST, topPanel);
class Pleader extends Thread{
Pleader(){
super("pleader");
}
@Override
public void run(){
try {
ij.plugin.BrowserLauncher.openURL("https://valelab.ucsf.edu/~MM/MMwiki/index.php/Citing_Micro-Manager");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
}
citePleaLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Pleader p = new Pleader();
p.start();
}
});
// add window listeners
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeSequence();
running_ = false;
}
@Override
public void windowOpened(WindowEvent e) {
// -------------------
// initialize hardware
// -------------------
try {
core_ = new CMMCore();
} catch(UnsatisfiedLinkError ex) {
ReportingUtils.showError(ex, "Failed to open libMMCoreJ_wrap.jnilib");
return;
}
ReportingUtils.setCore(core_);
//core_.setDeviceDiscoveryEnabled(options_.enableDeviceDiscovery_);
core_.enableDebugLog(options_.debugLogEnabled_);
core_.logMessage("MM Studio version: " + getVersion());
core_.logMessage(core_.getVersionInfo());
core_.logMessage(core_.getAPIVersionInfo());
core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
cameraLabel_ = "";
shutterLabel_ = "";
zStageLabel_ = "";
xyStageLabel_ = "";
engine_ = new AcquisitionWrapperEngine();
// register callback for MMCore notifications, this is a global
// to avoid garbage collection
cb_ = new CoreEventCallback();
core_.registerCallback(cb_);
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception e2) {
ReportingUtils.showError(e2);
}
MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow();
if (parent != null) {
engine_.setParentGUI(parent);
}
loadMRUConfigFiles();
initializePlugins();
toFront();
if (!options_.doNotAskForConfigFile_) {
MMIntroDlg introDlg = new MMIntroDlg(VERSION, MRUConfigFiles_);
introDlg.setConfigFile(sysConfigFile_);
introDlg.setBackground(guiColors_.background.get((options_.displayBackground_)));
introDlg.setVisible(true);
sysConfigFile_ = introDlg.getConfigFile();
}
saveMRUConfigFiles();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
paint(MMStudioMainFrame.this.getGraphics());
engine_.setCore(core_, afMgr_);
posList_ = new PositionList();
engine_.setPositionList(posList_);
// load (but do no show) the scriptPanel
createScriptPanel();
// Create an instance of HotKeys so that they can be read in from prefs
hotKeys_ = new org.micromanager.utils.HotKeys();
hotKeys_.loadSettings();
// if an error occurred during config loading,
// do not display more errors than needed
if (!loadSystemConfiguration())
ReportingUtils.showErrorOn(false);
executeStartupScript();
// Create Multi-D window here but do not show it.
// This window needs to be created in order to properly set the "ChannelGroup"
// based on the Multi-D parameters
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this);
addMMBackgroundListener(acqControlWin_);
configPad_.setCore(core_);
if (parent != null) {
configPad_.setParentGUI(parent);
}
configPadButtonPanel_.setCore(core_);
// initialize controls
// initializeGUI(); Not needed since it is already called in loadSystemConfiguration
initializeHelpMenu();
String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, "");
if (afMgr_.hasDevice(afDevice)) {
try {
afMgr_.selectDevice(afDevice);
} catch (MMException e1) {
// this error should never happen
ReportingUtils.showError(e1);
}
}
// switch error reporting back on
ReportingUtils.showErrorOn(true);
}
private void initializePlugins() {
pluginMenu_ = new JMenu();
pluginMenu_.setText("Plugins");
menuBar_.add(pluginMenu_);
new Thread("Plugin loading") {
@Override
public void run() {
// Needed for loading clojure-based jars:
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
loadPlugins();
}
}.run();
}
});
final JButton setRoiButton = new JButton();
setRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/shape_handles.png"));
setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle");
setRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setROI();
}
});
topPanel.add(setRoiButton);
topLayout.putConstraint(SpringLayout.EAST, setRoiButton, 37,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, setRoiButton, 7,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, setRoiButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, setRoiButton, 154,
SpringLayout.NORTH, topPanel);
final JButton clearRoiButton = new JButton();
clearRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_out.png"));
clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
clearRoiButton.setToolTipText("Reset Region of Interest to full frame");
clearRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearROI();
}
});
topPanel.add(clearRoiButton);
topLayout.putConstraint(SpringLayout.EAST, clearRoiButton, 70,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, clearRoiButton, 40,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, clearRoiButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, clearRoiButton, 154,
SpringLayout.NORTH, topPanel);
final JLabel regionOfInterestLabel = new JLabel();
regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel.setText("ROI");
topPanel.add(regionOfInterestLabel);
topLayout.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel,
154, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, regionOfInterestLabel,
140, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel,
71, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel,
8, SpringLayout.WEST, topPanel);
contrastPanel_ = new ContrastPanel();
contrastPanel_.setFont(new Font("", Font.PLAIN, 10));
contrastPanel_.setContrastStretch(stretch);
contrastPanel_.setRejectOutliers(reject);
contrastPanel_.setFractionToReject(rejectFract);
contrastPanel_.setBorder(BorderFactory.createEmptyBorder());
bottomPanel.add(contrastPanel_);
topLayout.putConstraint(SpringLayout.SOUTH, contrastPanel_, -20,
SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, contrastPanel_, 0,
SpringLayout.NORTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, contrastPanel_, 0,
SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, contrastPanel_, 0,
SpringLayout.WEST, bottomPanel);
metadataPanel_ = new MetadataPanel();
metadataPanel_.setVisible(false);
bottomPanel.add(metadataPanel_);
topLayout.putConstraint(SpringLayout.SOUTH, metadataPanel_, -20,
SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, metadataPanel_, 0,
SpringLayout.NORTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, metadataPanel_, 0,
SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, metadataPanel_, 0,
SpringLayout.WEST, bottomPanel);
metadataPanel_.setBorder(BorderFactory.createEmptyBorder());
GUIUtils.registerImageFocusListener(new ImageFocusListener() {
public void focusReceived(ImageWindow focusedWindow) {
if (focusedWindow == null) {
contrastPanel_.setVisible(true);
metadataPanel_.setVisible(false);
} else if (focusedWindow instanceof MMImageWindow) {
contrastPanel_.setVisible(true);
metadataPanel_.setVisible(false);
} else if (focusedWindow.getImagePlus().getStack() instanceof AcquisitionVirtualStack) {
contrastPanel_.setVisible(false);
metadataPanel_.setVisible(true);
}
}
});
final JLabel regionOfInterestLabel_1 = new JLabel();
regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel_1.setText("Zoom");
topPanel.add(regionOfInterestLabel_1);
topLayout.putConstraint(SpringLayout.SOUTH,
regionOfInterestLabel_1, 154, SpringLayout.NORTH,
topPanel);
topLayout.putConstraint(SpringLayout.NORTH,
regionOfInterestLabel_1, 140, SpringLayout.NORTH,
topPanel);
topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1,
139, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1,
81, SpringLayout.WEST, topPanel);
final JButton zoomInButton = new JButton();
zoomInButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomIn();
}
});
zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_in.png"));
zoomInButton.setToolTipText("Zoom in");
zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(zoomInButton);
topLayout.putConstraint(SpringLayout.SOUTH, zoomInButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, zoomInButton, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, zoomInButton, 110,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, zoomInButton, 80,
SpringLayout.WEST, topPanel);
final JButton zoomOutButton = new JButton();
zoomOutButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomOut();
}
});
zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_out.png"));
zoomOutButton.setToolTipText("Zoom out");
zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(zoomOutButton);
topLayout.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, zoomOutButton, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, zoomOutButton, 143,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, zoomOutButton, 113,
SpringLayout.WEST, topPanel);
// Profile
// -------
final JLabel profileLabel_ = new JLabel();
profileLabel_.setFont(new Font("Arial", Font.BOLD, 11));
profileLabel_.setText("Profile");
topPanel.add(profileLabel_);
topLayout.putConstraint(SpringLayout.SOUTH, profileLabel_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, profileLabel_, 140,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, profileLabel_, 217,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, profileLabel_, 154,
SpringLayout.WEST, topPanel);
final JButton buttonProf = new JButton();
buttonProf.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/chart_curve.png"));
buttonProf.setFont(new Font("Arial", Font.PLAIN, 10));
buttonProf.setToolTipText("Open line profile window (requires line selection)");
buttonProf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openLineProfileWindow();
}
});
// buttonProf.setText("Profile");
topPanel.add(buttonProf);
topLayout.putConstraint(SpringLayout.SOUTH, buttonProf, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonProf, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonProf, 183,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonProf, 153,
SpringLayout.WEST, topPanel);
// Autofocus
// -------
final JLabel autofocusLabel_ = new JLabel();
autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11));
autofocusLabel_.setText("Autofocus");
topPanel.add(autofocusLabel_);
topLayout.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, autofocusLabel_, 274,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, autofocusLabel_, 194,
SpringLayout.WEST, topPanel);
buttonAutofocus_ = new JButton();
buttonAutofocus_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/find.png"));
buttonAutofocus_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocus_.setToolTipText("Autofocus now");
buttonAutofocus_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (afMgr_.getDevice() != null) {
new Thread() {
@Override
public void run() {
try {
boolean lmo = isLiveModeOn();
if(lmo)
enableLiveMode(false);
afMgr_.getDevice().fullFocus();
if(lmo)
enableLiveMode(true);
} catch (MMException ex) {
ReportingUtils.logError(ex);
}
}
}.start(); // or any other method from Autofocus.java API
}
}
});
topPanel.add(buttonAutofocus_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAutofocus_, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAutofocus_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAutofocus_, 223,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAutofocus_, 193,
SpringLayout.WEST, topPanel);
buttonAutofocusTools_ = new JButton();
buttonAutofocusTools_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/wrench_orange.png"));
buttonAutofocusTools_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocusTools_.setToolTipText("Set autofocus options");
buttonAutofocusTools_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAutofocusDialog();
}
});
topPanel.add(buttonAutofocusTools_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAutofocusTools_, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAutofocusTools_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAutofocusTools_, 256,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAutofocusTools_, 226,
SpringLayout.WEST, topPanel);
saveConfigButton_ = new JButton();
saveConfigButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
}
});
saveConfigButton_.setToolTipText("Save current presets to the configuration file");
saveConfigButton_.setText("Save");
saveConfigButton_.setEnabled(false);
topPanel.add(saveConfigButton_);
topLayout.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, saveConfigButton_, -5,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, saveConfigButton_, -80,
SpringLayout.EAST, topPanel);
// Add our own keyboard manager that handles Micro-Manager shortcuts
MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD);
}
private void handleException(Exception e, String msg) {
String errText = "Exception occurred: ";
if (msg.length() > 0) {
errText += msg + " -- ";
}
if (options_.debugLogEnabled_) {
errText += e.getMessage();
} else {
errText += e.toString() + "\n";
ReportingUtils.showError(e);
}
handleError(errText);
}
private void handleException(Exception e) {
handleException(e, "");
}
private void handleError(String message) {
if (isLiveModeOn()) {
// Should we always stop live mode on any error?
enableLiveMode(false);
}
JOptionPane.showMessageDialog(this, message);
core_.logMessage(message);
}
public void makeActive() {
toFront();
}
private void setExposure() {
try {
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
// Display the new exposure time
double exposure = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
// Interval for Live Mode changes as well
setLiveModeInterval();
} catch (Exception exp) {
// Do nothing.
}
}
public boolean getConserveRamOption() {
return options_.conserveRam_;
}
public boolean getAutoreloadOption() {
return options_.autoreloadDevices_;
}
private void updateTitle() {
this.setTitle("System: " + sysConfigFile_);
}
private void updateLineProfile() {
if (!isImageWindowOpen() || profileWin_ == null
|| !profileWin_.isShowing()) {
return;
}
calculateLineProfileData(imageWin_.getImagePlus());
profileWin_.setData(lineProfileData_);
}
private void openLineProfileWindow() {
if (imageWin_ == null || imageWin_.isClosed()) {
return;
}
calculateLineProfileData(imageWin_.getImagePlus());
if (lineProfileData_ == null) {
return;
}
profileWin_ = new GraphFrame();
profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
profileWin_.setData(lineProfileData_);
profileWin_.setAutoScale();
profileWin_.setTitle("Live line profile");
profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(profileWin_);
profileWin_.setVisible(true);
}
public Rectangle getROI() throws MMScriptException {
// ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++):
int[][] a = new int[4][1];
try {
core_.getROI(a[0], a[1], a[2], a[3]);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
// Return as a single array with x,y,w,h:
return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);
}
private void calculateLineProfileData(ImagePlus imp) {
// generate line profile
Roi roi = imp.getRoi();
if (roi == null || !roi.isLine()) {
// if there is no line ROI, create one
Rectangle r = imp.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI
+ iWidth / 4, iYROI + iHeight / 4);
imp.setRoi(roi);
roi = imp.getRoi();
}
ImageProcessor ip = imp.getProcessor();
ip.setInterpolate(true);
Line line = (Line) roi;
if (lineProfileData_ == null) {
lineProfileData_ = new GraphData();
}
lineProfileData_.setData(line.getPixels());
}
public void setROI(Rectangle r) throws MMScriptException {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
try {
core_.setROI(r.x, r.y, r.width, r.height);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
}
private void setROI() {
ImagePlus curImage = WindowManager.getCurrentImage();
if (curImage == null) {
return;
}
Roi roi = curImage.getRoi();
try {
if (roi == null) {
// if there is no ROI, create one
Rectangle r = curImage.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iWidth /= 2;
iHeight /= 2;
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
curImage.setRoi(iXROI, iYROI, iWidth, iHeight);
roi = curImage.getRoi();
}
if (roi.getType() != Roi.RECTANGLE) {
handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI.");
return;
}
Rectangle r = roi.getBoundingRect();
// if we already had an ROI defined, correct for the offsets
Rectangle cameraR = getROI();
r.x += cameraR.x;
r.y += cameraR.y;
// Stop (and restart) live mode if it is running
setROI(r);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void clearROI() {
try {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
core_.clearROI();
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private BooleanLock creatingImageWindow_ = new BooleanLock(false);
private static long waitForCreateImageWindowTimeout_ = 5000;
private MMImageWindow createImageWindow() {
if (creatingImageWindow_.isTrue()) {
try {
creatingImageWindow_.waitToSetFalse(waitForCreateImageWindowTimeout_);
} catch (Exception e) {
ReportingUtils.showError(e);
}
return imageWin_;
}
creatingImageWindow_.setValue(true);
MMImageWindow win = imageWin_;
removeMMBackgroundListener(imageWin_);
imageWin_ = null;
try {
if (win != null) {
win.saveAttributes();
win.dispose();
win = null;
}
win = new MMImageWindow(core_, this);
core_.logMessage("createImageWin1");
win.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(win);
setIJCal(win);
// listeners
if (centerAndDragListener_ != null
&& centerAndDragListener_.isRunning()) {
centerAndDragListener_.attach(win.getImagePlus().getWindow());
}
if (zWheelListener_ != null && zWheelListener_.isRunning()) {
zWheelListener_.attach(win.getImagePlus().getWindow());
}
if (xyzKeyListener_ != null && xyzKeyListener_.isRunning()) {
xyzKeyListener_.attach(win.getImagePlus().getWindow());
}
win.getCanvas().requestFocus();
imageWin_ = win;
} catch (Exception e) {
if (win != null) {
win.saveAttributes();
WindowManager.removeWindow(win);
win.dispose();
}
ReportingUtils.showError(e);
}
creatingImageWindow_.setValue(false);
return imageWin_;
}
/**
* Returns instance of the core uManager object;
*/
public CMMCore getMMCore() {
return core_;
}
/**
* Returns singleton instance of MMStudioMainFrame
*/
public static MMStudioMainFrame getInstance() {
return gui_;
}
public final void setExitStrategy(boolean closeOnExit) {
if (closeOnExit)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void saveConfigPresets() {
MicroscopeModel model = new MicroscopeModel();
try {
model.loadFromFile(sysConfigFile_);
model.createSetupConfigsFromHardware(core_);
model.createResolutionsFromHardware(core_);
File f = FileDialogs.save(this, "Save the configuration file", MM_CONFIG_FILE);
if (f != null) {
model.saveToFile(f.getAbsolutePath());
sysConfigFile_ = f.getAbsolutePath();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
updateTitle();
}
} catch (MMConfigFileException e) {
ReportingUtils.showError(e);
}
}
protected void setConfigSaveButtonStatus(boolean changed) {
saveConfigButton_.setEnabled(changed);
}
public String getAcqDirectory() {
return openAcqDirectory_;
}
public void setAcqDirectory(String dir) {
openAcqDirectory_ = dir;
}
/**
* Open an existing acquisition directory and build viewer window.
*
*/
public void openAcquisitionData() {
// choose the directory
// --------------------
File f = FileDialogs.openDir(this, "Please select an image data set", MM_DATA_SET);
if (f != null) {
if (f.isDirectory()) {
openAcqDirectory_ = f.getAbsolutePath();
} else {
openAcqDirectory_ = f.getParent();
}
openAcquisitionData(openAcqDirectory_);
}
}
public void openAcquisitionData(String dir) {
String rootDir = new File(dir).getAbsolutePath();
String name = new File(dir).getName();
rootDir= rootDir.substring(0, rootDir.length() - (name.length() + 1));
try {
acqMgr_.openAcquisition(name, rootDir, true, true, true);
acqMgr_.getAcquisition(name).initialize();
acqMgr_.closeAcquisition(name);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
}
}
protected void zoomOut() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomOut(r.width / 2, r.height / 2);
}
}
protected void zoomIn() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomIn(r.width / 2, r.height / 2);
}
}
protected void changeBinning() {
try {
boolean liveRunning = false;
if (isLiveModeOn() ) {
liveRunning = true;
enableLiveMode(false);
}
if (isCameraAvailable()) {
Object item = comboBinning_.getSelectedItem();
if (item != null) {
core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString());
}
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void createPropertyEditor() {
if (propertyBrowser_ != null) {
propertyBrowser_.dispose();
}
propertyBrowser_ = new PropertyEditor();
propertyBrowser_.setGui(this);
propertyBrowser_.setVisible(true);
propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
propertyBrowser_.setCore(core_);
}
private void createCalibrationListDlg() {
if (calibrationListDlg_ != null) {
calibrationListDlg_.dispose();
}
calibrationListDlg_ = new CalibrationListDlg(core_);
calibrationListDlg_.setVisible(true);
calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
calibrationListDlg_.setParentGUI(this);
}
public CalibrationListDlg getCalibrationListDlg() {
if (calibrationListDlg_ == null) {
createCalibrationListDlg();
}
return calibrationListDlg_;
}
private void createScriptPanel() {
if (scriptPanel_ == null) {
scriptPanel_ = new ScriptPanel(core_, options_, this);
scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);
scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);
scriptPanel_.setParentGUI(this);
scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(scriptPanel_);
}
}
/**
* Updates Status line in main window from cached values
*/
private void updateStaticInfoFromCache() {
String dimText = "Image size: " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X "
+ staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits";
dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix";
if (zStageLabel_.length() > 0) {
dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um";
}
if (xyStageLabel_.length() > 0) {
dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um";
}
labelImageDimensions_.setText(dimText);
}
public void updateXYPos(double x, double y) {
staticInfo_.x_ = x;
staticInfo_.y_ = y;
updateStaticInfoFromCache();
}
public void updateZPos(double z) {
staticInfo_.zPos_ = z;
updateStaticInfoFromCache();
}
public void updateXYPosRelative(double x, double y) {
staticInfo_.x_ += x;
staticInfo_.y_ += y;
updateStaticInfoFromCache();
}
public void updateZPosRelative(double z) {
staticInfo_.zPos_ += z;
updateStaticInfoFromCache();
}
public void updateXYStagePosition(){
double x[] = new double[1];
double y[] = new double[1];
try {
if (xyStageLabel_.length() > 0)
core_.getXYPosition(xyStageLabel_, x, y);
} catch (Exception e) {
ReportingUtils.showError(e);
}
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
private void updatePixSizeUm (double pixSizeUm) {
staticInfo_.pixSizeUm_ = pixSizeUm;
updateStaticInfoFromCache();
}
private void updateStaticInfo() {
double zPos = 0.0;
double x[] = new double[1];
double y[] = new double[1];
try {
if (zStageLabel_.length() > 0) {
zPos = core_.getPosition(zStageLabel_);
}
if (xyStageLabel_.length() > 0) {
core_.getXYPosition(xyStageLabel_, x, y);
}
} catch (Exception e) {
handleException(e);
}
staticInfo_.width_ = core_.getImageWidth();
staticInfo_.height_ = core_.getImageHeight();
staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel();
staticInfo_.imageBitDepth_ = core_.getImageBitDepth();
staticInfo_.pixSizeUm_ = core_.getPixelSizeUm();
staticInfo_.zPos_ = zPos;
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
public void toggleShutter() {
try {
if (!toggleButtonShutter_.isEnabled())
return;
toggleButtonShutter_.requestFocusInWindow();
if (toggleButtonShutter_.getText().equals("Open")) {
setShutterButton(true);
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(false);
setShutterButton(false);
}
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
private void setShutterButton(boolean state) {
if (state) {
toggleButtonShutter_.setSelected(true);
toggleButtonShutter_.setText("Close");
} else {
toggleButtonShutter_.setSelected(false);
toggleButtonShutter_.setText("Open");
}
}
// //////////////////////////////////////////////////////////////////////////
// public interface available for scripting access
// //////////////////////////////////////////////////////////////////////////
public void snapSingleImage() {
doSnap();
}
public Object getPixels() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getProcessor().getPixels();
}
return null;
}
public void setPixels(Object obj) {
if (imageWin_ == null) {
return;
}
imageWin_.getImagePlus().getProcessor().setPixels(obj);
}
public int getImageHeight() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getHeight();
}
return 0;
}
public int getImageWidth() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getWidth();
}
return 0;
}
public int getImageDepth() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getBitDepth();
}
return 0;
}
public ImageProcessor getImageProcessor() {
if (imageWin_ == null) {
return null;
}
return imageWin_.getImagePlus().getProcessor();
}
private boolean isCameraAvailable() {
return cameraLabel_.length() > 0;
}
/**
* Part of ScriptInterface API
* Opens the XYPositionList when it is not opened
* Adds the current position to the list (same as pressing the "Mark" button)
*/
public void markCurrentPosition() {
if (posListDlg_ == null) {
showXYPositionList();
}
if (posListDlg_ != null) {
posListDlg_.markPosition();
}
}
/**
* Implements ScriptInterface
*/
public AcqControlDlg getAcqDlg() {
return acqControlWin_;
}
/**
* Implements ScriptInterface
*/
public PositionListDlg getXYPosListDlg() {
if (posListDlg_ == null)
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
return posListDlg_;
}
/**
* Implements ScriptInterface
*/
public boolean isAcquisitionRunning() {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
/**
* Implements ScriptInterface
*/
public boolean versionLessThan(String version) throws MMScriptException {
try {
String[] v = VERSION.split(" ", 2);
String[] m = v[0].split("\\.", 3);
String[] v2 = version.split(" ", 2);
String[] m2 = v2[0].split("\\.", 3);
for (int i=0; i < 3; i++) {
if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) {
return false;
}
}
if (v2.length < 2 || v2[1].equals("") )
return false;
if (v.length < 2 ) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return false;
}
return true;
} catch (Exception ex) {
throw new MMScriptException ("Format of version String should be \"a.b.c\"");
}
}
public boolean isImageWindowOpen() {
boolean ret = imageWin_ != null;
ret = ret && !imageWin_.isClosed();
if (ret) {
try {
Graphics g = imageWin_.getGraphics();
if (null != g) {
int ww = imageWin_.getWidth();
g.clearRect(0, 0, ww, 40);
imageWin_.drawInfo(g);
} else {
// explicitly clean up if Graphics is null, rather
// than cleaning up in the exception handler below..
WindowManager.removeWindow(imageWin_);
imageWin_.saveAttributes();
imageWin_.dispose();
imageWin_ = null;
ret = false;
}
} catch (Exception e) {
WindowManager.removeWindow(imageWin_);
imageWin_.saveAttributes();
imageWin_.dispose();
imageWin_ = null;
ReportingUtils.showError(e);
ret = false;
}
}
return ret;
}
public boolean isLiveModeOn() {
return liveModeTimer_ != null && liveModeTimer_.isRunning();
}
public void enableLiveMode(boolean enable) {
if (core_ == null)
return;
if (enable == isLiveModeOn() )
return;
if (core_.getNumberOfComponents() == 1) { //monochrome or multi camera
multiChannelCameraNrCh_ = core_.getNumberOfCameraChannels();
if (multiChannelCameraNrCh_ > 1) {
multiChannelCamera_ = true;
enableMultiCameraLiveMode(enable);
} else
enableMonochromeLiveMode(enable);
} else
enableRGBLiveMode(enable);
updateButtonsForLiveMode();
}
private void enableLiveModeListeners(boolean enable) {
if (enable) {
// attach mouse wheel listener to control focus:
if (zWheelListener_ == null) {
zWheelListener_ = new ZWheelListener(core_, this);
}
zWheelListener_.start(imageWin_);
// attach key listener to control the stage and focus:
if (xyzKeyListener_ == null) {
xyzKeyListener_ = new XYZKeyListener(core_, this);
}
xyzKeyListener_.start(imageWin_);
} else {
if (zWheelListener_ != null) {
zWheelListener_.stop();
}
if (xyzKeyListener_ != null) {
xyzKeyListener_.stop();
}
}
}
private void enableMultiCameraLiveMode(boolean enable) {
if (enable) {
try {
checkMultiChannelWindow();
getAcquisition(MULTI_CAMERA_ACQ).toFront();
// turn off auto shutter and open the shutter
autoShutterOrg_ = core_.getAutoShutter();
if (shutterLabel_.length() > 0) {
shutterOrg_ = core_.getShutterOpen();
}
core_.setAutoShutter(false);
shutterLabel_ = core_.getShutterDevice();
// only open the shutter when we have one and the Auto shutter
// checkbox was checked
if ((shutterLabel_.length() > 0) && autoShutterOrg_) {
core_.setShutterOpen(true);
}
setLiveModeInterval();
if (liveModeTimer_ == null)
liveModeTimer_ = new LiveModeTimer((int) liveModeInterval_, LiveModeTimer.MULTI_CAMERA );
else {
liveModeTimer_.setDelay((int) liveModeInterval_);
liveModeTimer_.setType(LiveModeTimer.MULTI_CAMERA);
}
liveModeTimer_.start();
getAcquisition(MULTI_CAMERA_ACQ).getAcquisitionWindow().setWindowTitle("Multi Camera Live Mode (running)");
if (autoShutterOrg_) {
toggleButtonShutter_.setEnabled(false);
}
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to enable live mode.");
}
} else {
try {
liveModeTimer_.stop();
if (acqMgr_.acquisitionExists(MULTI_CAMERA_ACQ))
getAcquisition(MULTI_CAMERA_ACQ).getAcquisitionWindow().setWindowTitle("Multi Camera Live Mode (stopped)");
enableLiveModeListeners(false);
// restore auto shutter and close the shutter
if (shutterLabel_.length() > 0)
core_.setShutterOpen(shutterOrg_);
core_.setAutoShutter(autoShutterOrg_);
if (autoShutterOrg_)
toggleButtonShutter_.setEnabled(false);
else
toggleButtonShutter_.setEnabled(true);
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to disable live mode.");
}
}
}
private void enableMonochromeLiveMode(boolean enable) {
if (enable) {
try {
if (!isImageWindowOpen() && creatingImageWindow_.isFalse()) {
imageWin_ = createImageWindow();
}
imageWin_.drawInfo(imageWin_.getGraphics());
imageWin_.toFront();
// turn off auto shutter and open the shutter
autoShutterOrg_ = core_.getAutoShutter();
if (shutterLabel_.length() > 0) {
shutterOrg_ = core_.getShutterOpen();
}
core_.setAutoShutter(false);
shutterLabel_ = core_.getShutterDevice();
// only open the shutter when we have one and the Auto shutter
// checkbox was checked
if ((shutterLabel_.length() > 0) && autoShutterOrg_) {
core_.setShutterOpen(true);
}
enableLiveModeListeners(enable);
setLiveModeInterval();
if (liveModeTimer_ == null)
liveModeTimer_ = new LiveModeTimer((int) liveModeInterval_,LiveModeTimer.MONOCHROME);
else {
liveModeTimer_.setDelay((int) liveModeInterval_);
liveModeTimer_.setType(LiveModeTimer.MONOCHROME);
}
liveModeTimer_.start();
if (autoShutterOrg_) {
toggleButtonShutter_.setEnabled(false);
}
imageWin_.setSubTitle("Live (running)");
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to enable live mode.");
if (imageWin_ != null) {
imageWin_.saveAttributes();
WindowManager.removeWindow(imageWin_);
imageWin_.dispose();
imageWin_ = null;
}
}
} else {
try {
liveModeTimer_.stop();
enableLiveModeListeners(enable);
// restore auto shutter and close the shutter
if (shutterLabel_.length() > 0)
core_.setShutterOpen(shutterOrg_);
core_.setAutoShutter(autoShutterOrg_);
if (autoShutterOrg_)
toggleButtonShutter_.setEnabled(false);
else
toggleButtonShutter_.setEnabled(true);
imageWin_.setSubTitle("Live (stopped)");
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to disable live mode.");
if (imageWin_ != null) {
WindowManager.removeWindow(imageWin_);
imageWin_.dispose();
imageWin_ = null;
}
}
}
}
private void enableRGBLiveMode(boolean enable) {
if (enable) {
setLiveModeInterval();
if (liveModeTimer_ == null) {
liveModeTimer_ = new LiveModeTimer((int) liveModeInterval_, LiveModeTimer.RGB);
} else {
liveModeTimer_.setDelay((int) liveModeInterval_);
liveModeTimer_.setType(LiveModeTimer.RGB);
}
checkRGBAcquisition();
liveModeTimer_.start();
try {
getAcquisition(RGB_ACQ).getAcquisitionWindow().setWindowTitle("RGB Live Mode (running)");
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
}
} else {
liveModeTimer_.stop();
try {
if (acqMgr_.acquisitionExists(RGB_ACQ))
getAcquisition(RGB_ACQ).getAcquisitionWindow().setWindowTitle("RGB Live Mode (stopped)");
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
}
}
}
public void updateButtonsForLiveMode() {
boolean liveRunning = isLiveModeOn();
autoShutterCheckBox_.setEnabled(!liveRunning);
buttonSnap_.setEnabled(!liveRunning);
toggleButtonLive_.setIcon(liveRunning ? SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setSelected(liveRunning);
toggleButtonLive_.setText(liveRunning ? "Stop Live" : "Live");
}
public boolean getLiveMode() {
return isLiveModeOn();
}
public boolean updateImage() {
try {
if (isLiveModeOn()) {
enableLiveMode(false);
return true; // nothing to do, just show the last image
}
if (!isImageWindowOpen()) {
createImageWindow();
}
core_.snapImage();
Object img;
img = core_.getImage();
if (imageWin_.windowNeedsResizing()) {
createImageWindow();
}
if (!isCurrentImageFormatSupported()) {
return false;
}
imageWin_.newImage(img);
updateLineProfile();
} catch (Exception e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public boolean displayImage(final Object pixels) {
return displayImage(pixels, true);
}
public boolean displayImage(final Object pixels, boolean wait) {
try {
if (core_.getNumberOfCameraChannels() > 1)
checkMultiChannelWindow();
else {
if (!isImageWindowOpen() || imageWin_.windowNeedsResizing()
&& creatingImageWindow_.isFalse()) {
createImageWindow();
}
Runnable displayRunnable = new Runnable() {
public void run() {
imageWin_.newImage(pixels);
updateLineProfile();
}
};
if (SwingUtilities.isEventDispatchThread()) {
displayRunnable.run();
} else {
if (wait) {
SwingUtilities.invokeAndWait(displayRunnable);
} else {
SwingUtilities.invokeLater(displayRunnable);
}
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
return false;
}
return true;
}
public boolean displayImageWithStatusLine(Object pixels, String statusLine) {
try {
if (!isImageWindowOpen() || imageWin_.windowNeedsResizing()
&& creatingImageWindow_.isFalse()) {
createImageWindow();
}
imageWin_.newImageWithStatusLine(pixels, statusLine);
updateLineProfile();
} catch (Exception e) {
ReportingUtils.logError(e);
return false;
}
return true;
}
public void displayStatusLine(String statusLine) {
try {
if (isImageWindowOpen()) {
imageWin_.displayStatusLine(statusLine);
}
} catch (Exception e) {
ReportingUtils.logError(e);
return;
}
}
private boolean isCurrentImageFormatSupported() {
boolean ret = false;
long channels = core_.getNumberOfComponents();
long bpp = core_.getBytesPerPixel();
if (channels > 1 && channels != 4 && bpp != 1) {
handleError("Unsupported image format.");
} else {
ret = true;
}
return ret;
}
private void doSnap() {
if (core_.getNumberOfComponents() == 1) {
if(4 == core_.getBytesPerPixel()) {
doSnapFloat();
} else {
if (core_.getNumberOfCameraChannels() > 1)
{
doSnapMultiCamera();
} else {
doSnapMonochrome();
}
}
} else {
doSnapColor();
}
}
public void initializeGUI() {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
engine_.setZStageDevice(zStageLabel_);
if (cameraLabel_.length() > 0) {
ActionListener[] listeners;
// binning combo
if (comboBinning_.getItemCount() > 0) {
comboBinning_.removeAllItems();
}
StrVector binSizes = core_.getAllowedPropertyValues(
cameraLabel_, MMCoreJ.getG_Keyword_Binning());
listeners = comboBinning_.getActionListeners();
for (int i = 0; i < listeners.length; i++) {
comboBinning_.removeActionListener(listeners[i]);
}
for (int i = 0; i < binSizes.size(); i++) {
comboBinning_.addItem(binSizes.get(i));
}
comboBinning_.setMaximumRowCount((int) binSizes.size());
if (binSizes.size() == 0) {
comboBinning_.setEditable(true);
} else {
comboBinning_.setEditable(false);
}
for (int i = 0; i < listeners.length; i++) {
comboBinning_.addActionListener(listeners[i]);
}
}
// active shutter combo
try {
shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);
} catch (Exception e) {
ReportingUtils.logError(e);
}
if (shutters_ != null) {
String items[] = new String[(int) shutters_.size()];
for (int i = 0; i < shutters_.size(); i++) {
items[i] = shutters_.get(i);
}
GUIUtils.replaceComboContents(shutterComboBox_, items);
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// Autofocus
buttonAutofocusTools_.setEnabled(afMgr_.getDevice() != null);
buttonAutofocus_.setEnabled(afMgr_.getDevice() != null);
// Rebuild stage list in XY PositinList
if (posListDlg_ != null) {
posListDlg_.rebuildAxisList();
}
// Mouse moves stage
centerAndDragListener_ = new CenterAndDragListener(core_, gui_);
if (centerAndDragMenuItem_.isSelected()) {
centerAndDragListener_.start();
}
updateGUI(true);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getVersion() {
return VERSION;
}
private void addPluginToMenu(final PluginItem plugin, Class<?> cl) {
// add plugin menu items
final JMenuItem newMenuItem = new JMenuItem();
newMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
ReportingUtils.logMessage("Plugin command: "
+ e.getActionCommand());
plugin.instantiate();
plugin.plugin.show();
}
});
newMenuItem.setText(plugin.menuItem);
String toolTipDescription = "";
try {
// Get this static field from the class implementing MMPlugin.
toolTipDescription = (String) cl.getDeclaredField("tooltipDescription").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
toolTipDescription = "Description not available";
} catch (NoSuchFieldException e) {
toolTipDescription = "Description not available";
ReportingUtils.logError(cl.getName() + " fails to implement static String tooltipDescription.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
String mrjProp = System.getProperty("mrj.version");
if (mrjProp != null && !mrjProp.equals(null)) // running on a mac
newMenuItem.setToolTipText(toolTipDescription);
else
newMenuItem.setToolTipText( TooltipTextMaker.addHTMLBreaksForTooltip(toolTipDescription) );
pluginMenu_.add(newMenuItem);
pluginMenu_.validate();
menuBar_.validate();
}
public void updateGUI(boolean updateConfigPadStructure) {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
afMgr_.refresh();
// camera settings
if (isCameraAvailable()) {
double exp = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp));
String binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning());
GUIUtils.setComboSelection(comboBinning_, binSize);
long bitDepth = 8;
if (imageWin_ != null) {
long hsz = imageWin_.getRawHistogramSize();
bitDepth = (long) Math.log(hsz);
}
bitDepth = core_.getImageBitDepth();
contrastPanel_.setPixelBitDepth((int) bitDepth, false);
}
if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) {
autoShutterCheckBox_.setSelected(core_.getAutoShutter());
boolean shutterOpen = core_.getShutterOpen();
setShutterButton(shutterOpen);
if (autoShutterCheckBox_.isSelected()) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
autoShutterOrg_ = core_.getAutoShutter();
}
// active shutter combo
if (shutters_ != null) {
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// state devices
if (updateConfigPadStructure && (configPad_ != null)) {
configPad_.refreshStructure();
// Needed to update read-only properties. May slow things down...
core_.updateSystemStateCache();
}
// update Channel menus in Multi-dimensional acquisition dialog
updateChannelCombos();
} catch (Exception e) {
ReportingUtils.logError(e);
}
updateStaticInfo();
updateTitle();
}
public boolean okToAcquire() {
return !isLiveModeOn();
}
public void stopAllActivity() {
enableLiveMode(false);
}
public void refreshImage() {
if (imageWin_ != null) {
imageWin_.getImagePlus().updateAndDraw();
}
}
private void cleanupOnClose() {
// NS: Save config presets if they were changed.
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
}
if (liveModeTimer_ != null)
liveModeTimer_.stop();
try{
if (imageWin_ != null) {
if (!imageWin_.isClosed())
imageWin_.close();
imageWin_.dispose();
imageWin_ = null;
}
}
catch( Throwable t){
ReportingUtils.logError(t, "closing ImageWin_");
}
if (profileWin_ != null) {
removeMMBackgroundListener(profileWin_);
profileWin_.dispose();
}
if (scriptPanel_ != null) {
removeMMBackgroundListener(scriptPanel_);
scriptPanel_.closePanel();
}
if (propertyBrowser_ != null) {
removeMMBackgroundListener(propertyBrowser_);
propertyBrowser_.dispose();
}
if (acqControlWin_ != null) {
removeMMBackgroundListener(acqControlWin_);
acqControlWin_.close();
}
if (engine_ != null) {
engine_.shutdown();
}
if (afMgr_ != null) {
afMgr_.closeOptionsDialog();
}
// dispose plugins
for (int i = 0; i < plugins_.size(); i++) {
MMPlugin plugin = (MMPlugin) plugins_.get(i).plugin;
if (plugin != null) {
plugin.dispose();
}
}
synchronized (shutdownLock_) {
try {
if (core_ != null){
core_.delete();
core_ = null;
}
} catch (Exception err) {
ReportingUtils.showError(err);
}
}
}
private void saveSettings() {
Rectangle r = this.getBounds();
mainPrefs_.putInt(MAIN_FRAME_X, r.x);
mainPrefs_.putInt(MAIN_FRAME_Y, r.y);
mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width);
mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height);
mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation());
mainPrefs_.putBoolean(MAIN_STRETCH_CONTRAST, contrastPanel_.isContrastStretch());
mainPrefs_.putBoolean(MAIN_REJECT_OUTLIERS, contrastPanel_.isRejectOutliers());
mainPrefs_.putDouble(MAIN_REJECT_FRACTION, contrastPanel_.getFractionToReject());
mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);
// save field values from the main window
// NOTE: automatically restoring these values on startup may cause
// problems
mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText());
// NOTE: do not save auto shutter state
if (afMgr_ != null && afMgr_.getDevice() != null) {
mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());
}
}
private void loadConfiguration() {
File f = FileDialogs.openFile(this, "Load a config file",MM_CONFIG_FILE);
if (f != null) {
sysConfigFile_ = f.getAbsolutePath();
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
}
}
private void loadSystemState() {
File f = FileDialogs.openFile(this, "Load a system state file", MM_CONFIG_FILE);
if (f != null) {
sysStateFile_ = f.getAbsolutePath();
try {
// WaitDialog waitDlg = new
// WaitDialog("Loading saved state, please wait...");
// waitDlg.showDialog();
core_.loadSystemState(sysStateFile_);
GUIUtils.preventDisplayAdapterChangeExceptions();
// waitDlg.closeDialog();
initializeGUI();
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
private void saveSystemState() {
File f = FileDialogs.save(this,
"Save the system state to a config file", MM_CONFIG_FILE);
if (f != null) {
sysStateFile_ = f.getAbsolutePath();
try {
core_.saveSystemState(sysStateFile_);
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
public void closeSequence() {
if (!this.isRunning())
return;
if (engine_ != null && engine_.isAcquisitionRunning()) {
int result = JOptionPane.showConfirmDialog(
this,
"Acquisition in progress. Are you sure you want to exit and discard all data?",
"Micro-Manager", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
return;
}
}
stopAllActivity();
cleanupOnClose();
saveSettings();
try {
configPad_.saveSettings();
options_.saveSettings();
hotKeys_.saveSettings();
} catch (NullPointerException e) {
if (core_ != null)
this.logError(e);
}
this.dispose();
if (options_.closeOnExit_) {
if (!runsAsPlugin_) {
System.exit(0);
} else {
ImageJ ij = IJ.getInstance();
if (ij != null) {
ij.quit();
}
}
}
}
public void applyContrastSettings(ContrastSettings contrast8,
ContrastSettings contrast16) {
contrastPanel_.applyContrastSettings(contrast8, contrast16);
}
public ContrastSettings getContrastSettings() {
return contrastPanel_.getContrastSettings();
}
public boolean is16bit() {
if (isImageWindowOpen()
&& imageWin_.getImagePlus().getProcessor() instanceof ShortProcessor) {
return true;
}
return false;
}
public boolean isRunning() {
return running_;
}
/**
* Executes the beanShell script. This script instance only supports
* commands directed to the core object.
*/
private void executeStartupScript() {
// execute startup script
File f = new File(startupScriptFile_);
if (startupScriptFile_.length() > 0 && f.exists()) {
WaitDialog waitDlg = new WaitDialog(
"Executing startup script, please wait...");
waitDlg.showDialog();
Interpreter interp = new Interpreter();
try {
// insert core object only
interp.set(SCRIPT_CORE_OBJECT, core_);
interp.set(SCRIPT_ACQENG_OBJECT, engine_);
interp.set(SCRIPT_GUI_OBJECT, this);
// read text file and evaluate
interp.eval(TextUtils.readTextFile(startupScriptFile_));
} catch (IOException exc) {
ReportingUtils.showError(exc, "Unable to read the startup script (" + startupScriptFile_ + ").");
} catch (EvalError exc) {
ReportingUtils.showError(exc);
} finally {
waitDlg.closeDialog();
}
} else {
if (startupScriptFile_.length() > 0)
ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present.");
}
}
/**
* Loads system configuration from the cfg file.
*/
private boolean loadSystemConfiguration() {
boolean result = true;
saveMRUConfigFiles();
final WaitDialog waitDlg = new WaitDialog(
"Loading system configuration, please wait...");
waitDlg.setAlwaysOnTop(true);
waitDlg.showDialog();
this.setEnabled(false);
try {
if (sysConfigFile_.length() > 0) {
GUIUtils.preventDisplayAdapterChangeExceptions();
core_.waitForSystem();
ignorePropertyChanges_ = true;
core_.loadSystemConfiguration(sysConfigFile_);
ignorePropertyChanges_ = false;
GUIUtils.preventDisplayAdapterChangeExceptions();
}
} catch (final Exception err) {
GUIUtils.preventDisplayAdapterChangeExceptions();
ReportingUtils.showError(err);
result = false;
} finally {
waitDlg.closeDialog();
}
setEnabled(true);
initializeGUI();
updateSwitchConfigurationMenu();
FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_));
return result;
}
private void saveMRUConfigFiles() {
if (0 < sysConfigFile_.length()) {
if (MRUConfigFiles_.contains(sysConfigFile_)) {
MRUConfigFiles_.remove(sysConfigFile_);
}
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
// save the MRU list to the preferences
for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {
String value = "";
if (null != MRUConfigFiles_.get(icfg)) {
value = MRUConfigFiles_.get(icfg).toString();
}
mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);
}
}
}
private void loadMRUConfigFiles() {
sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_);
// startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE,
// startupScriptFile_);
MRUConfigFiles_ = new ArrayList<String>();
for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {
String value = "";
value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);
if (0 < value.length()) {
File ruFile = new File(value);
if (ruFile.exists()) {
if (!MRUConfigFiles_.contains(value)) {
MRUConfigFiles_.add(value);
}
}
}
}
// initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE
if (0 < sysConfigFile_.length()) {
if (!MRUConfigFiles_.contains(sysConfigFile_)) {
// in case persistant data is inconsistent
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
}
}
}
/**
* Opens Acquisition dialog.
*/
private void openAcqControlDialog() {
try {
if (acqControlWin_ == null) {
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this);
}
if (acqControlWin_.isActive()) {
acqControlWin_.setTopPosition();
}
acqControlWin_.setVisible(true);
acqControlWin_.repaint();
// TODO: this call causes a strange exception the first time the
// dialog is created
// something to do with the order in which combo box creation is
// performed
// acqControlWin_.updateGroupsCombo();
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nAcquistion window failed to open due to invalid or corrupted settings.\n"
+ "Try resetting registry settings to factory defaults (Menu Tools|Options).");
}
}
/**
* /** Opens a dialog to record stage positions
*/
@Override
public void showXYPositionList() {
if (posListDlg_ == null) {
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
}
posListDlg_.setVisible(true);
}
private void updateChannelCombos() {
if (this.acqControlWin_ != null) {
this.acqControlWin_.updateChannelAndGroupCombo();
}
}
@Override
public void setConfigChanged(boolean status) {
configChanged_ = status;
setConfigSaveButtonStatus(configChanged_);
}
/**
* Returns the current background color
* @return
*/
@Override
public Color getBackgroundColor() {
return guiColors_.background.get((options_.displayBackground_));
}
/*
* Changes background color of this window and all other MM windows
*/
@Override
public void setBackgroundStyle(String backgroundType) {
setBackground(guiColors_.background.get((backgroundType)));
paint(MMStudioMainFrame.this.getGraphics());
// sets background of all registered Components
for (Component comp:MMFrames_) {
if (comp != null)
comp.setBackground(guiColors_.background.get(backgroundType));
}
}
@Override
public String getBackgroundStyle() {
return options_.displayBackground_;
}
// Set ImageJ pixel calibration
private void setIJCal(MMImageWindow imageWin) {
if (imageWin != null) {
imageWin.setIJCal();
}
}
// //////////////////////////////////////////////////////////////////////////
// Scripting interface
// //////////////////////////////////////////////////////////////////////////
private class ExecuteAcq implements Runnable {
public ExecuteAcq() {
}
@Override
public void run() {
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
}
}
}
private class LoadAcq implements Runnable {
private String filePath_;
public LoadAcq(String path) {
filePath_ = path;
}
@Override
public void run() {
// stop current acquisition if any
engine_.shutdown();
// load protocol
if (acqControlWin_ != null) {
acqControlWin_.loadAcqSettingsFromFile(filePath_);
}
}
}
private void testForAbortRequests() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
}
}
@Override
public void startAcquisition() throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new ExecuteAcq());
}
@Override
public void runAcquisition() throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(50);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
} else {
throw new MMScriptException(
"Acquisition window must be open for this command to work.");
}
}
@Override
public void runAcquisition(String name, String root)
throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition(name, root);
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(100);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
} else {
throw new MMScriptException(
"Acquisition window must be open for this command to work.");
}
}
@Override
public void runAcqusition(String name, String root) throws MMScriptException {
runAcquisition(name, root);
}
@Override
public void loadAcquisition(String path) throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new LoadAcq(path));
}
@Override
public void setPositionList(PositionList pl) throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
posList_ = pl; // PositionList.newInstance(pl);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (posListDlg_ != null) {
posListDlg_.setPositionList(posList_);
engine_.setPositionList(posList_);
}
}
});
}
@Override
public PositionList getPositionList() throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
return posList_; //PositionList.newInstance(posList_);
}
@Override
public void sleep(long ms) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.sleep(ms);
}
}
@Override
public String getUniqueAcquisitionName(String stub) {
return acqMgr_.getUniqueAcquisitionName(stub);
}
// TODO:
@Override
public MMAcquisition getCurrentAcquisition() {
return null; // if none available
}
public void openAcquisition(String name, String rootDir) throws MMScriptException {
openAcquisition(name, rootDir, true);
}
public void openAcquisition(String name, String rootDir, boolean show) throws MMScriptException {
//acqMgr_.openAcquisition(name, rootDir, show);
TaggedImageStorage imageFileManager = new TaggedImageStorageDiskDefault((new File(rootDir, name)).getAbsolutePath());
MMImageCache cache = new MMImageCache(imageFileManager);
VirtualAcquisitionDisplay display = new VirtualAcquisitionDisplay(cache, null);
display.show();
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions) throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,
nrPositions, true, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices) throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show, boolean virtual)
throws MMScriptException {
acqMgr_.openAcquisition(name, rootDir, show, virtual);
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show, boolean virtual)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual);
}
private void openAcquisitionSnap(String name, String rootDir, boolean show)
throws MMScriptException {
/*
MMAcquisition acq = acqMgr_.openAcquisitionSnap(name, rootDir, this,
show);
acq.setDimensions(0, 1, 1, 1);
try {
// acq.getAcqData().setPixelSizeUm(core_.getPixelSizeUm());
acq.setProperty(SummaryKeys.IMAGE_PIXEL_SIZE_UM, String.valueOf(core_.getPixelSizeUm()));
} catch (Exception e) {
ReportingUtils.showError(e);
}
*
*/
}
@Override
public void initializeAcquisition(String name, int width, int height,
int depth) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setImagePhysicalDimensions(width, height, depth);
acq.initialize();
}
@Override
public int getAcquisitionImageWidth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getWidth();
}
@Override
public int getAcquisitionImageHeight(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getHeight();
}
@Override
public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getDepth();
}
@Override
public Boolean acquisitionExists(String name) {
return acqMgr_.acquisitionExists(name);
}
@Override
public void closeAcquisition(String name) throws MMScriptException {
acqMgr_.closeAcquisition(name);
}
@Override
public void closeAcquisitionImage5D(String title) throws MMScriptException {
acqMgr_.closeImage5D(title);
}
/**
* Since Burst and normal acquisition are now carried out by the same engine,
* loadBurstAcquistion simply calls loadAcquisition
* t
* @param path - path to file specifying acquisition settings
*/
@Override
public void loadBurstAcquisition(String path) throws MMScriptException {
this.loadAcquisition(path);
}
@Override
public void refreshGUI() {
updateGUI(true);
}
public void setAcquisitionProperty(String acqName, String propertyName,
String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(propertyName, value);
}
public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSystemState(md);
}
public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSummaryProperties(md);
}
public void setImageProperty(String acqName, int frame, int channel,
int slice, String propName, String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(frame, channel, slice, propName, value);
}
public void snapAndAddImage(String name, int frame, int channel, int slice)
throws MMScriptException {
snapAndAddImage(name, frame, channel, slice, 0);
}
public void snapAndAddImage(String name, int frame, int channel, int slice, int position)
throws MMScriptException {
Metadata md = new Metadata();
try {
Object img;
if (core_.isSequenceRunning()) {
img = core_.getLastImage();
core_.getLastImageMD(0, 0, md);
} else {
core_.snapImage();
img = core_.getImage();
}
MMAcquisition acq = acqMgr_.getAcquisition(name);
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
if (!acq.isInitialized()) {
acq.setImagePhysicalDimensions((int) width, (int) height,
(int) depth);
acq.initialize();
}
acq.insertImage(img, frame, channel, slice, position);
// Insert exposure in metadata
// acq.setProperty(frame, channel, slice, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
/*
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
acq.setProperty(frame, channel, slice, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
acq.setProperty(frame, channel, slice, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
acq.setSystemState(frame, channel, slice, state);
*/
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public void addToSnapSeries(Object img, String acqName) {
try {
acqMgr_.getCurrentAlbum();
if (acqName == null) {
acqName = "Snap" + snapCount_;
}
Boolean newSnap = false;
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
//MMAcquisitionSnap acq = null;
if (! acqMgr_.hasActiveImage5D(acqName)) {
newSnap = true;
}
if (newSnap) {
snapCount_++;
acqName = "Snap" + snapCount_;
this.openAcquisitionSnap(acqName, null, true); // (dir=null) ->
// keep in
// memory; don't
// save to file.
initializeAcquisition(acqName, (int) width, (int) height,
(int) depth);
}
setChannelColor(acqName, 0, Color.WHITE);
setChannelName(acqName, 0, "Snap");
// acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName);
// acq.appendImage(img);
// add exposure to metadata
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
// JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
// acq.setSystemState(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, state);
// closeAcquisition(acqName);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getCurrentAlbum() {
return acqMgr_.getCurrentAlbum();
}
public String createNewAlbum() {
return acqMgr_.createNewAlbum();
}
public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
int f = 1 + acq.getLastAcquiredFrame();
try {
MDUtils.setFrameIndex(taggedImg.tags, f);
} catch (JSONException e) {
throw new MMScriptException("Unable to set the frame index.");
}
acq.insertTaggedImage(taggedImg, f, 0, 0);
}
public void addToAlbum(TaggedImage taggedImg) throws MMScriptException {
acqMgr_.addToAlbum(taggedImg);
}
public void addImage(String name, Object img, int frame, int channel,
int slice) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.insertImage(img, frame, channel, slice);
}
public void addImage(String name, TaggedImage taggedImg) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg);
}
public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay);
}
public void addImage(String name, TaggedImage taggedImg,
boolean updateDisplay,
boolean waitForDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay);
}
public void addImage(String name, TaggedImage taggedImg,
boolean updateDisplay,
boolean waitForDisplay,
boolean allowContrastToChange) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay, allowContrastToChange);
}
public void closeAllAcquisitions() {
acqMgr_.closeAll();
}
public String[] getAcquisitionNames()
{
return acqMgr_.getAcqusitionNames();
}
public MMAcquisition getAcquisition(String name) throws MMScriptException {
return acqMgr_.getAcquisition(name);
}
private class ScriptConsoleMessage implements Runnable {
String msg_;
public ScriptConsoleMessage(String text) {
msg_ = text;
}
public void run() {
if (scriptPanel_ != null)
scriptPanel_.message(msg_);
}
}
public void message(String text) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
SwingUtilities.invokeLater(new ScriptConsoleMessage(text));
}
}
public void clearMessageWindow() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.clearOutput();
}
}
public void clearOutput() throws MMScriptException {
clearMessageWindow();
}
public void clear() throws MMScriptException {
clearMessageWindow();
}
public void setChannelContrast(String title, int channel, int min, int max)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelContrast(channel, min, max);
}
public void setChannelName(String title, int channel, String name)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelName(channel, name);
}
public void setChannelColor(String title, int channel, Color color)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelColor(channel, color.getRGB());
}
public void setContrastBasedOnFrame(String title, int frame, int slice)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setContrastBasedOnFrame(frame, slice);
}
public void setStagePosition(double z) throws MMScriptException {
try {
core_.setPosition(core_.getFocusDevice(),z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setRelativeStagePosition(double z) throws MMScriptException {
try {
core_.setRelativePosition(core_.getFocusDevice(), z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setRelativeXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public Point2D.Double getXYStagePosition() throws MMScriptException {
String stage = core_.getXYStageDevice();
if (stage.length() == 0) {
throw new MMScriptException("XY Stage device is not available");
}
double x[] = new double[1];
double y[] = new double[1];
try {
core_.getXYPosition(stage, x, y);
Point2D.Double pt = new Point2D.Double(x[0], y[0]);
return pt;
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public String getXYStageName() {
return core_.getXYStageDevice();
}
public void setXYOrigin(double x, double y) throws MMScriptException {
String xyStage = core_.getXYStageDevice();
try {
core_.setAdapterOriginXY(xyStage, x, y);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
public AcquisitionEngine getAcquisitionEngine() {
return engine_;
}
public String installPlugin(Class<?> cl) {
String className = cl.getSimpleName();
String msg = className + " module loaded.";
try {
for (PluginItem plugin : plugins_) {
if (plugin.className.contentEquals(className)) {
return className + " already loaded.";
}
}
PluginItem pi = new PluginItem();
pi.className = className;
try {
// Get this static field from the class implementing MMPlugin.
pi.menuItem = (String) cl.getDeclaredField("menuName").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
pi.menuItem = className;
} catch (NoSuchFieldException e) {
pi.menuItem = className;
ReportingUtils.logError(className + " fails to implement static String menuName.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
if (pi.menuItem == null) {
pi.menuItem = className;
//core_.logMessage(className + " fails to implement static String menuName.");
}
pi.menuItem = pi.menuItem.replace("_", " ");
pi.pluginClass = cl;
plugins_.add(pi);
final PluginItem pi2 = pi;
final Class<?> cl2 = cl;
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
addPluginToMenu(pi2, cl2);
}
});
} catch (NoClassDefFoundError e) {
msg = className + " class definition not found.";
ReportingUtils.logError(e, msg);
}
return msg;
}
public String installPlugin(String className, String menuName) {
String msg = "installPlugin(String className, String menuName) is deprecated. Use installPlugin(String className) instead.";
core_.logMessage(msg);
installPlugin(className);
return msg;
}
public String installPlugin(String className) {
String msg = "";
try {
Class clazz = Class.forName(className);
return installPlugin(clazz);
} catch (ClassNotFoundException e) {
msg = className + " plugin not found.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(String className) {
try {
return installAutofocusPlugin(Class.forName(className));
} catch (ClassNotFoundException e) {
String msg = "Internal error: AF manager not instantiated.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(Class<?> autofocus) {
String msg = autofocus.getSimpleName() + " module loaded.";
if (afMgr_ != null) {
try {
afMgr_.refresh();
} catch (MMException e) {
msg = e.getMessage();
ReportingUtils.logError(e);
}
afMgr_.setAFPluginClassName(autofocus.getSimpleName());
} else {
msg = "Internal error: AF manager not instantiated.";
}
return msg;
}
public CMMCore getCore() {
return core_;
}
public Pipeline getPipeline() {
try {
pipelineClassLoadingThread_.join();
if (acquirePipeline_ == null) {
acquirePipeline_ = (Pipeline) pipelineClass_.newInstance();
}
return acquirePipeline_;
} catch (Exception e) {
ReportingUtils.logError(e);
return null;
}
}
public void snapAndAddToImage5D() {
try {
getPipeline().acquireSingle();
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public void setAcquisitionEngine(AcquisitionEngine eng) {
engine_ = eng;
}
public void suspendLiveMode() {
liveModeSuspended_ = isLiveModeOn();
enableLiveMode(false);
}
public void resumeLiveMode() {
if (liveModeSuspended_) {
enableLiveMode(true);
}
}
public Autofocus getAutofocus() {
return afMgr_.getDevice();
}
public void showAutofocusDialog() {
if (afMgr_.getDevice() != null) {
afMgr_.showOptionsDialog();
}
}
public AutofocusManager getAutofocusManager() {
return afMgr_;
}
public void selectConfigGroup(String groupName) {
configPad_.setGroup(groupName);
}
public String regenerateDeviceList() {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(resultFile, core_);
//MicroscopeModel.generateDeviceListFile();
setCursor(oldc);
return resultFile.toString();
}
private void loadPlugins() {
afMgr_ = new AutofocusManager(this);
ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>();
ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>();
List<Class<?>> classes;
try {
long t1 = System.currentTimeMillis();
classes = JavaUtils.findClasses(new File("mmplugins"), 2);
//System.out.println("findClasses: " + (System.currentTimeMillis() - t1));
//System.out.println(classes.size());
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == MMPlugin.class) {
pluginClasses.add(clazz);
}
}
}
classes = JavaUtils.findClasses(new File("mmautofocus"), 2);
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == Autofocus.class) {
autofocusClasses.add(clazz);
}
}
}
} catch (ClassNotFoundException e1) {
ReportingUtils.logError(e1);
}
for (Class<?> plugin : pluginClasses) {
try {
ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName());
installPlugin(plugin);
} catch (Exception e) {
ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin .");
}
}
for (Class<?> autofocus : autofocusClasses) {
try {
ReportingUtils.logMessage("Attempting to install autofocus plugin " + autofocus.getName());
installAutofocusPlugin(autofocus.getName());
} catch (Exception e) {
ReportingUtils.logError("Failed to install the \"" + autofocus.getName() + "\" autofocus plugin.");
}
}
}
/**
*
*/
private void setLiveModeInterval() {
double interval = 33.0;
try {
if (core_.getExposure() > 33.0) {
interval = core_.getExposure();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
liveModeInterval_ = interval;
}
public void logMessage(String msg) {
ReportingUtils.logMessage(msg);
}
public void showMessage(String msg) {
ReportingUtils.showMessage(msg);
}
public void logError(Exception e, String msg) {
ReportingUtils.logError(e, msg);
}
public void logError(Exception e) {
ReportingUtils.logError(e);
}
public void logError(String msg) {
ReportingUtils.logError(msg);
}
public void showError(Exception e, String msg) {
ReportingUtils.showError(e, msg);
}
public void showError(Exception e) {
ReportingUtils.showError(e);
}
public void showError(String msg) {
ReportingUtils.showError(msg);
}
private void runHardwareWizard(boolean v2) {
try {
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
configChanged_ = false;
}
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
// unload all devices before starting configurator
core_.reset();
GUIUtils.preventDisplayAdapterChangeExceptions();
// run Configurator
if (v2) {
ConfiguratorDlg2 cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_);
cfg2.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = cfg2.getFileName();
} else {
ConfiguratorDlg configurator = new ConfiguratorDlg(core_, sysConfigFile_);
configurator.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = configurator.getFileName();
}
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
GUIUtils.preventDisplayAdapterChangeExceptions();
if (liveRunning) {
enableLiveMode(liveRunning);
}
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
class BooleanLock extends Object {
private boolean value;
public BooleanLock(boolean initialValue) {
value = initialValue;
}
public BooleanLock() {
this(false);
}
public synchronized void setValue(boolean newValue) {
if (newValue != value) {
value = newValue;
notifyAll();
}
}
public synchronized boolean waitToSetTrue(long msTimeout)
throws InterruptedException {
boolean success = waitUntilFalse(msTimeout);
if (success) {
setValue(true);
}
return success;
}
public synchronized boolean waitToSetFalse(long msTimeout)
throws InterruptedException {
boolean success = waitUntilTrue(msTimeout);
if (success) {
setValue(false);
}
return success;
}
public synchronized boolean isTrue() {
return value;
}
public synchronized boolean isFalse() {
return !value;
}
public synchronized boolean waitUntilTrue(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(true, msTimeout);
}
public synchronized boolean waitUntilFalse(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(false, msTimeout);
}
public synchronized boolean waitUntilStateIs(
boolean state,
long msTimeout) throws InterruptedException {
if (msTimeout == 0L) {
while (value != state) {
wait();
}
return true;
}
long endTime = System.currentTimeMillis() + msTimeout;
long msRemaining = msTimeout;
while ((value != state) && (msRemaining > 0L)) {
wait(msRemaining);
msRemaining = endTime - System.currentTimeMillis();
}
return (value == state);
}
}
| Fixed autoshutter checkbox bug
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@8235 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
| mmstudio/src/org/micromanager/MMStudioMainFrame.java | Fixed autoshutter checkbox bug | <ide><path>mstudio/src/org/micromanager/MMStudioMainFrame.java
<ide> private JLabel labelImageDimensions_;
<ide> private JToggleButton toggleButtonLive_;
<ide> private JCheckBox autoShutterCheckBox_;
<del> private boolean autoShutterOrg_;
<del> private boolean shutterOrg_;
<add> private boolean shutterOriginalState_;
<ide> private MMOptions options_;
<ide> private boolean runsAsPlugin_;
<ide> private JCheckBoxMenuItem centerAndDragMenuItem_;
<ide> autoShutterCheckBox_ = new JCheckBox();
<ide> autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
<ide> autoShutterCheckBox_.addActionListener(new ActionListener() {
<del>
<ide> public void actionPerformed(ActionEvent e) {
<del> core_.setAutoShutter(autoShutterCheckBox_.isSelected());
<del> if (shutterLabel_.length() > 0) {
<add> shutterLabel_ = core_.getShutterDevice();
<add> if (shutterLabel_.length() == 0) {
<add> toggleButtonShutter_.setEnabled(false);
<add> return;
<add> }
<add> if (autoShutterCheckBox_.isSelected()) {
<ide> try {
<del> setShutterButton(core_.getShutterOpen());
<del> } catch (Exception e1) {
<del> ReportingUtils.showError(e1);
<add> core_.setAutoShutter(true);
<add> core_.setShutterOpen(false);
<add> toggleButtonShutter_.setSelected(false);
<add> toggleButtonShutter_.setText("Open");
<add> toggleButtonShutter_.setEnabled(false);
<add> } catch (Exception e2) {
<add> ReportingUtils.logError(e2);
<ide> }
<del> }
<del> if (autoShutterCheckBox_.isSelected()) {
<del> toggleButtonShutter_.setEnabled(false);
<ide> } else {
<add> try {
<add> core_.setAutoShutter(false);
<add> core_.setShutterOpen(false);
<ide> toggleButtonShutter_.setEnabled(true);
<del> }
<add> toggleButtonShutter_.setText("Open");
<add> } catch (Exception exc) {
<add> ReportingUtils.logError(exc);
<add> }
<add> }
<add>
<ide> }
<ide> });
<ide> autoShutterCheckBox_.setIconTextGap(6);
<ide>
<ide> private void setShutterButton(boolean state) {
<ide> if (state) {
<del> toggleButtonShutter_.setSelected(true);
<add>// toggleButtonShutter_.setSelected(true);
<ide> toggleButtonShutter_.setText("Close");
<ide> } else {
<del> toggleButtonShutter_.setSelected(false);
<add>// toggleButtonShutter_.setSelected(false);
<ide> toggleButtonShutter_.setText("Open");
<ide> }
<ide> }
<ide> return;
<ide> if (enable == isLiveModeOn() )
<ide> return;
<add> setLiveModeInterval();
<ide> if (core_.getNumberOfComponents() == 1) { //monochrome or multi camera
<ide> multiChannelCameraNrCh_ = core_.getNumberOfCameraChannels();
<ide> if (multiChannelCameraNrCh_ > 1) {
<ide> enableMonochromeLiveMode(enable);
<ide> } else
<ide> enableRGBLiveMode(enable);
<del> updateButtonsForLiveMode();
<add> updateButtonsForLiveMode(enable);
<ide> }
<ide>
<add> private void manageShutterLiveMode(boolean enable) throws Exception {
<add> shutterLabel_ = core_.getShutterDevice();
<add> if (shutterLabel_.length() > 0) {
<add> if (enable) {
<add> shutterOriginalState_ = core_.getShutterOpen();
<add> core_.setShutterOpen(true);
<add> } else {
<add> core_.setShutterOpen(shutterOriginalState_);
<add> }
<add> }
<add> }
<add>
<add> public void updateButtonsForLiveMode(boolean enable) {
<add> toggleButtonShutter_.setEnabled(!enable);
<add> autoShutterCheckBox_.setEnabled(!enable);
<add> buttonSnap_.setEnabled(!enable);
<add> toggleButtonLive_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class,
<add> "/org/micromanager/icons/cancel.png")
<add> : SwingResourceManager.getIcon(MMStudioMainFrame.class,
<add> "/org/micromanager/icons/camera_go.png"));
<add> toggleButtonLive_.setSelected(enable);
<add> toggleButtonLive_.setText(enable ? "Stop Live" : "Live");
<add> }
<add>
<ide> private void enableLiveModeListeners(boolean enable) {
<ide> if (enable) {
<ide> // attach mouse wheel listener to control focus:
<ide> try {
<ide> checkMultiChannelWindow();
<ide> getAcquisition(MULTI_CAMERA_ACQ).toFront();
<del>
<del> // turn off auto shutter and open the shutter
<del> autoShutterOrg_ = core_.getAutoShutter();
<del> if (shutterLabel_.length() > 0) {
<del> shutterOrg_ = core_.getShutterOpen();
<del> }
<del> core_.setAutoShutter(false);
<del>
<del> shutterLabel_ = core_.getShutterDevice();
<del> // only open the shutter when we have one and the Auto shutter
<del> // checkbox was checked
<del> if ((shutterLabel_.length() > 0) && autoShutterOrg_) {
<del> core_.setShutterOpen(true);
<del> }
<del>
<add>
<ide> setLiveModeInterval();
<ide> if (liveModeTimer_ == null)
<ide> liveModeTimer_ = new LiveModeTimer((int) liveModeInterval_, LiveModeTimer.MULTI_CAMERA );
<ide> liveModeTimer_.setDelay((int) liveModeInterval_);
<ide> liveModeTimer_.setType(LiveModeTimer.MULTI_CAMERA);
<ide> }
<del> liveModeTimer_.start();
<del>
<add> manageShutterLiveMode(enable);
<add> liveModeTimer_.start();
<ide> getAcquisition(MULTI_CAMERA_ACQ).getAcquisitionWindow().setWindowTitle("Multi Camera Live Mode (running)");
<del>
<del> if (autoShutterOrg_) {
<del> toggleButtonShutter_.setEnabled(false);
<del> }
<del>
<add>
<ide> } catch (Exception err) {
<ide> ReportingUtils.showError(err, "Failed to enable live mode.");
<ide> }
<ide> liveModeTimer_.stop();
<ide> if (acqMgr_.acquisitionExists(MULTI_CAMERA_ACQ))
<ide> getAcquisition(MULTI_CAMERA_ACQ).getAcquisitionWindow().setWindowTitle("Multi Camera Live Mode (stopped)");
<del>
<del> enableLiveModeListeners(false);
<del>
<del> // restore auto shutter and close the shutter
<del> if (shutterLabel_.length() > 0)
<del> core_.setShutterOpen(shutterOrg_);
<del> core_.setAutoShutter(autoShutterOrg_);
<del> if (autoShutterOrg_)
<del> toggleButtonShutter_.setEnabled(false);
<del> else
<del> toggleButtonShutter_.setEnabled(true);
<del>
<add> manageShutterLiveMode(enable);
<add> enableLiveModeListeners(false);
<ide> } catch (Exception err) {
<ide> ReportingUtils.showError(err, "Failed to disable live mode.");
<ide> }
<ide> }
<ide> }
<del>
<add>
<ide> private void enableMonochromeLiveMode(boolean enable) {
<ide> if (enable) {
<ide> try {
<ide> imageWin_.drawInfo(imageWin_.getGraphics());
<ide> imageWin_.toFront();
<ide>
<del>
<del> // turn off auto shutter and open the shutter
<del> autoShutterOrg_ = core_.getAutoShutter();
<del> if (shutterLabel_.length() > 0) {
<del> shutterOrg_ = core_.getShutterOpen();
<del> }
<del> core_.setAutoShutter(false);
<del>
<del> shutterLabel_ = core_.getShutterDevice();
<del> // only open the shutter when we have one and the Auto shutter
<del> // checkbox was checked
<del> if ((shutterLabel_.length() > 0) && autoShutterOrg_) {
<del> core_.setShutterOpen(true);
<del> }
<del>
<ide> enableLiveModeListeners(enable);
<del>
<del> setLiveModeInterval();
<ide> if (liveModeTimer_ == null)
<ide> liveModeTimer_ = new LiveModeTimer((int) liveModeInterval_,LiveModeTimer.MONOCHROME);
<ide> else {
<ide> liveModeTimer_.setDelay((int) liveModeInterval_);
<ide> liveModeTimer_.setType(LiveModeTimer.MONOCHROME);
<del> }
<del>
<add> }
<add> manageShutterLiveMode(enable);
<ide> liveModeTimer_.start();
<del>
<del>
<del> if (autoShutterOrg_) {
<del> toggleButtonShutter_.setEnabled(false);
<del> }
<add>
<ide> imageWin_.setSubTitle("Live (running)");
<ide> } catch (Exception err) {
<ide> ReportingUtils.showError(err, "Failed to enable live mode.");
<del>
<ide> if (imageWin_ != null) {
<ide> imageWin_.saveAttributes();
<ide> WindowManager.removeWindow(imageWin_);
<ide> }
<ide> } else {
<ide> try {
<del> liveModeTimer_.stop();
<del>
<del> enableLiveModeListeners(enable);
<del>
<del> // restore auto shutter and close the shutter
<del> if (shutterLabel_.length() > 0)
<del> core_.setShutterOpen(shutterOrg_);
<del> core_.setAutoShutter(autoShutterOrg_);
<del> if (autoShutterOrg_)
<del> toggleButtonShutter_.setEnabled(false);
<del> else
<del> toggleButtonShutter_.setEnabled(true);
<del>
<add> liveModeTimer_.stop();
<add> manageShutterLiveMode(enable);
<add> enableLiveModeListeners(enable);
<add>
<ide> imageWin_.setSubTitle("Live (stopped)");
<ide> } catch (Exception err) {
<ide> ReportingUtils.showError(err, "Failed to disable live mode.");
<ide> liveModeTimer_.setType(LiveModeTimer.RGB);
<ide> }
<ide> checkRGBAcquisition();
<del> liveModeTimer_.start();
<ide> try {
<add> manageShutterLiveMode(enable);
<add> liveModeTimer_.start();
<ide> getAcquisition(RGB_ACQ).getAcquisitionWindow().setWindowTitle("RGB Live Mode (running)");
<del> } catch (MMScriptException ex) {
<add> } catch (Exception ex) {
<ide> ReportingUtils.logError(ex);
<ide> }
<ide> } else {
<del> liveModeTimer_.stop();
<ide> try {
<add> liveModeTimer_.stop();
<add> manageShutterLiveMode(enable);
<ide> if (acqMgr_.acquisitionExists(RGB_ACQ))
<ide> getAcquisition(RGB_ACQ).getAcquisitionWindow().setWindowTitle("RGB Live Mode (stopped)");
<del> } catch (MMScriptException ex) {
<add> } catch (Exception ex) {
<ide> ReportingUtils.logError(ex);
<ide> }
<ide> }
<ide>
<del> }
<del>
<del> public void updateButtonsForLiveMode() {
<del> boolean liveRunning = isLiveModeOn();
<del> autoShutterCheckBox_.setEnabled(!liveRunning);
<del> buttonSnap_.setEnabled(!liveRunning);
<del> toggleButtonLive_.setIcon(liveRunning ? SwingResourceManager.getIcon(MMStudioMainFrame.class,
<del> "/org/micromanager/icons/cancel.png")
<del> : SwingResourceManager.getIcon(MMStudioMainFrame.class,
<del> "/org/micromanager/icons/camera_go.png"));
<del> toggleButtonLive_.setSelected(liveRunning);
<del> toggleButtonLive_.setText(liveRunning ? "Stop Live" : "Live");
<ide> }
<ide>
<ide> public boolean getLiveMode() {
<ide> } else {
<ide> toggleButtonShutter_.setEnabled(true);
<ide> }
<del>
<del> autoShutterOrg_ = core_.getAutoShutter();
<ide> }
<ide>
<ide> // active shutter combo |
|
Java | lgpl-2.1 | 06b31c421e5bd57c25c2d87e50d3ffb0830ea3ec | 0 | sewe/spotbugs,sewe/spotbugs,sewe/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,sewe/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2003-2008 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package sfBugs;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import edu.umd.cs.findbugs.annotations.Confidence;
import edu.umd.cs.findbugs.annotations.DesireWarning;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
/**
* @author pugh
*/
public class Bug3104124 {
@DesireWarning(value="OS_OPEN_STREAM_EXCEPTION_PATH", confidence=Confidence.MEDIUM)
@ExpectWarning(value="OS_OPEN_STREAM_EXCEPTION_PATH", confidence=Confidence.LOW)
public static String fileToString(String fileName) {
StringBuffer output = new StringBuffer();
try {
String line;
BufferedReader br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine()) != null) {
output.append(line).append("\n");
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return output.toString();
}
}
| findbugsTestCases/src/java/sfBugs/Bug3104124.java | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2003-2008 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package sfBugs;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import edu.umd.cs.findbugs.annotations.DesireWarning;
import edu.umd.cs.findbugs.annotations.Confidence;
/**
* @author pugh
*/
public class Bug3104124 {
@DesireWarning(value="OS_OPEN_STREAM_EXCEPTION_PATH", confidence=Confidence.MEDIUM)
public static String fileToString(String fileName) {
StringBuffer output = new StringBuffer();
try {
String line;
BufferedReader br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine()) != null) {
output.append(line).append("\n");
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return output.toString();
}
}
| more notes about expected warnings
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@13966 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
| findbugsTestCases/src/java/sfBugs/Bug3104124.java | more notes about expected warnings | <ide><path>indbugsTestCases/src/java/sfBugs/Bug3104124.java
<ide> import java.io.FileReader;
<ide> import java.io.IOException;
<ide>
<add>import edu.umd.cs.findbugs.annotations.Confidence;
<ide> import edu.umd.cs.findbugs.annotations.DesireWarning;
<del>import edu.umd.cs.findbugs.annotations.Confidence;
<add>import edu.umd.cs.findbugs.annotations.ExpectWarning;
<ide>
<ide> /**
<ide> * @author pugh
<ide>
<ide>
<ide> @DesireWarning(value="OS_OPEN_STREAM_EXCEPTION_PATH", confidence=Confidence.MEDIUM)
<add> @ExpectWarning(value="OS_OPEN_STREAM_EXCEPTION_PATH", confidence=Confidence.LOW)
<ide> public static String fileToString(String fileName) {
<ide> StringBuffer output = new StringBuffer();
<ide> try { |
|
JavaScript | mit | d1c4052a9a1ea922c205c5963c25fbd9597a17c7 | 0 | ArnaudBuchholz/bubu-timer | "use strict";
/*eslint-disable no-alert*/
require("./compatibility");
const
TOTAL_OUTER = 0.98,
TOTAL_INNER = 0.88,
STEP_OUTER = 0.83,
STEP_INNER = 0.73,
browser = require("./browser"),
dom = require("./dom"),
svg = require("./svg"),
colors = require("./colors"),
gradients = require("./gradients"),
sequenceSerializer = require("./sequence-serializer"),
tickGenerator = require("./tick-generator"),
tickConverter = require("./tick-converter"),
tickFormatter = require("./tick-formatter"),
sounds = require("./sounds"),
defaultRequestAnimFrame = callback => setTimeout(callback, 1000 / 60),
requestAnimFrame = window.requestAnimationFrame
|| window.webkitRequestAnimationFrame // Chrome & Safari
|| window.mozRequestAnimationFrame // Firefox
|| window.oRequestAnimationFrame // Opera
|| window.msRequestAnimationFrame // Internet Explorer
|| defaultRequestAnimFrame,
sequence = sequenceSerializer.read(location.search.substr(1)),
sequenceTotal = sequence.reduce((total, tick) => total + tick, 0),
ticker = tickGenerator.allocate(),
ratio2Coords = (ratio, radius = 1, precision = 10000) => {
let radian = ratio * 2 * Math.PI,
x = Math.floor(radius * precision * Math.sin(radian)) / precision,
y = Math.floor(-radius * precision * Math.cos(radian)) / precision;
return {x, y};
},
getCirclePath = (ratio, outerRadius, innerRadius) => {
let
outer = ratio2Coords(ratio, outerRadius),
inner = ratio2Coords(ratio, innerRadius),
path = [
`M 0 -${outerRadius}`
];
if (ratio > 0.5) {
path.push(`A ${outerRadius} ${outerRadius} 0 0 1 0 ${outerRadius}`,
`A ${outerRadius} ${outerRadius} 0 0 1 ${outer.x} ${outer.y}`,
`L ${inner.x} ${inner.y}`,
`A ${innerRadius} ${innerRadius} 0 0 0 0 ${innerRadius}`,
`A ${innerRadius} ${innerRadius} 0 0 0 0 -${innerRadius}`
);
} else {
path.push(`A ${outerRadius} ${outerRadius} 0 0 1 ${outer.x} ${outer.y}`,
`L ${inner.x} ${inner.y}`,
`A ${innerRadius} ${innerRadius} 0 0 0 0 -${innerRadius}`
);
}
path.push(`L 0 -${outerRadius}`);
return path.join(" ");
},
pulse = () => {
const
circle = document.getElementById("pulse"),
updates = [0.1, 0.08, 0.06, 0.03, 0],
update = (index = 0) => {
circle.setAttribute("r", updates[index]);
++index;
if (index < updates.length) {
setTimeout(() => {
update(index);
}, 100);
}
};
update();
sounds.tick();
},
done = () => {
document.getElementById("total").setAttribute("d", getCirclePath(0, TOTAL_OUTER, TOTAL_INNER));
document.getElementById("step").setAttribute("d", getCirclePath(0, STEP_OUTER, STEP_INNER));
dom.setText("stepOn", "done.");
sounds.end();
},
onTick = tick => {
const
convertedTick = tickConverter(tick.elapsed, sequence),
currentDuration = sequence[convertedTick.step % sequence.length],
total = tick.elapsed / sequenceTotal % 1,
step = 1 - convertedTick.remaining / currentDuration,
formattedRemaining = tickFormatter(convertedTick.remaining),
second = Math.floor(tick.elapsed / 1000);
if (onTick.lastSecond !== second) {
onTick.lastSecond = second;
if (convertedTick.remaining <= 5000 && convertedTick.step < sequence.length) {
pulse();
} else {
sounds.blank();
}
}
dom.setText("time", formattedRemaining.time);
dom.setText("ms", `.${formattedRemaining.ms}`);
if (convertedTick.step < sequence.length) {
document.getElementById("total").setAttribute("d", getCirclePath(total, TOTAL_OUTER, TOTAL_INNER));
document.getElementById("step").setAttribute("d", getCirclePath(step, STEP_OUTER, STEP_INNER));
dom.setText("stepOn", `${convertedTick.step + 1} / ${sequence.length}`);
requestAnimFrame(ticker.tick.bind(ticker));
} else {
done();
}
},
progressContainer = ({outerRadius, innerRadius, id, color}) => {
return [
svg.circle({cx: 0, cy: 0, r: outerRadius, stroke: "url(#outerBorder)", "stroke-width": 0.01,
fill: colors.circle.background}),
svg.circle({cx: 0, cy: 0, r: innerRadius, stroke: "url(#innerBorder)", "stroke-width": 0.01,
fill: colors.background}),
svg.path({id: id,
d: `M 0 -${outerRadius} A ${outerRadius} ${outerRadius} 0 0 1 ${outerRadius} 0
L ${innerRadius} 0 A ${innerRadius} ${innerRadius} 0 0 0 0 -${innerRadius} L 0 -${outerRadius}`,
fill: color, stroke: color, "stroke-opacity": 0.2, "stroke-width": 0.01})
];
},
setup = () => {
if (0 === sequence.length) {
alert("No sequence to play");
return {};
}
document.body.appendChild(svg({
width: "100%",
height: "100%",
viewBox: "-1 -1 2 2",
style: `background-color: ${colors.background};`
}, [gradients()]
.concat(progressContainer({
outerRadius: TOTAL_OUTER,
innerRadius: TOTAL_INNER,
id: "total",
color: colors.progress.total
}))
.concat(progressContainer({
outerRadius: STEP_OUTER,
innerRadius: STEP_INNER,
id: "step",
color: colors.progress.step
}))
.concat([
svg.circle({id: "edit", r: 0.15, cx: 0, cy: -0.4,
fill: colors.circle.light, stroke: "url(#innerBorder)", "stroke-width": 0.01}),
svg.text({x: 0, y: -0.34, "font-family": "Arial", "font-size": 0.2, "text-anchor": "middle",
fill: colors.text.step, stroke: "url(#outerBorder)", "stroke-opacity": 0.2,
"stroke-width": 0.001}, "?"),
svg.text({id: "time",
"font-family": "Arial", "font-size": 0.3, x: 0, y: 0.1, "text-anchor": "middle",
fill: colors.text.time,
stroke: "url(#innerBorder)", "stroke-opacity": 0.2, "stroke-width": 0.01}, "00:00"),
svg.text({id: "ms",
"font-family": "Arial", "font-size": 0.1, x: 0.60, y: 0.1, "text-anchor": "end",
fill: colors.text.ms,
stroke: "url(#innerBorder)", "stroke-opacity": 0.2, "stroke-width": 0.001}, ".123"),
svg.text({id: "stepOn",
"font-family": "Arial", "font-size": 0.1, x: 0, y: 0.3, "text-anchor": "middle",
fill: colors.text.step,
stroke: "url(#outerBorder)", "stroke-opacity": 0.2, "stroke-width": 0.01}, "1 / 2"),
svg.circle({id: "pulse", cx: 0, cy: 0.85, r: 0, "stroke-width": 0, fill: "red", opacity: 0.5})
])
));
ticker.on(onTick);
return {
"edit": () => {
let initialSequence = sequenceSerializer.read(location.search.substr(1));
location = "edit.html#" + sequenceSerializer.write(initialSequence);
},
"undefined": () => {
if (ticker.isPaused()) {
sounds.play();
ticker.resume();
} else {
ticker.pause();
sounds.pause();
}
}
};
};
browser(setup);
| src/run.js | "use strict";
/*eslint-disable no-alert*/
require("./compatibility");
const
TOTAL_OUTER = 0.98,
TOTAL_INNER = 0.88,
STEP_OUTER = 0.83,
STEP_INNER = 0.73,
browser = require("./browser"),
dom = require("./dom"),
svg = require("./svg"),
colors = require("./colors"),
gradients = require("./gradients"),
sequenceSerializer = require("./sequence-serializer"),
tickGenerator = require("./tick-generator"),
tickConverter = require("./tick-converter"),
tickFormatter = require("./tick-formatter"),
sounds = require("./sounds"),
defaultRequestAnimFrame = callback => setTimeout(callback, 1000 / 60),
requestAnimFrame = window.requestAnimationFrame
|| window.webkitRequestAnimationFrame // Chrome & Safari
|| window.mozRequestAnimationFrame // Firefox
|| window.oRequestAnimationFrame // Opera
|| window.msRequestAnimationFrame // Internet Explorer
|| defaultRequestAnimFrame,
sequence = sequenceSerializer.read(location.search.substr(1)),
sequenceTotal = sequence.reduce((total, tick) => total + tick, 0),
ticker = tickGenerator.allocate(),
ratio2Coords = (ratio, radius = 1, precision = 10000) => {
let radian = ratio * 2 * Math.PI,
x = Math.floor(radius * precision * Math.sin(radian)) / precision,
y = Math.floor(-radius * precision * Math.cos(radian)) / precision;
return {x, y};
},
getCirclePath = (ratio, outerRadius, innerRadius) => {
let
outer = ratio2Coords(ratio, outerRadius),
inner = ratio2Coords(ratio, innerRadius),
path = [
`M 0 -${outerRadius}`
];
if (ratio > 0.5) {
path.push(`A ${outerRadius} ${outerRadius} 0 0 1 0 ${outerRadius}`,
`A ${outerRadius} ${outerRadius} 0 0 1 ${outer.x} ${outer.y}`,
`L ${inner.x} ${inner.y}`,
`A ${innerRadius} ${innerRadius} 0 0 0 0 ${innerRadius}`,
`A ${innerRadius} ${innerRadius} 0 0 0 0 -${innerRadius}`
);
} else {
path.push(`A ${outerRadius} ${outerRadius} 0 0 1 ${outer.x} ${outer.y}`,
`L ${inner.x} ${inner.y}`,
`A ${innerRadius} ${innerRadius} 0 0 0 0 -${innerRadius}`
);
}
path.push(`L 0 -${outerRadius}`);
return path.join(" ");
},
pulse = () => {
const
circle = document.getElementById("pulse"),
updates = [0.1, 0.08, 0.06, 0.03, 0],
update = (index = 0) => {
circle.setAttribute("r", updates[index]);
++index;
if (index < updates.length) {
setTimeout(() => {
update(index);
}, 100);
}
};
update();
sounds.tick();
},
done = () => {
document.getElementById("total").setAttribute("d", getCirclePath(0, TOTAL_OUTER, TOTAL_INNER));
document.getElementById("step").setAttribute("d", getCirclePath(0, STEP_OUTER, STEP_INNER));
dom.setText("stepOn", "done.");
sounds.end();
},
onTick = tick => {
const
convertedTick = tickConverter(tick.elapsed, sequence),
currentDuration = sequence[convertedTick.step % sequence.length],
total = tick.elapsed / sequenceTotal % 1,
step = 1 - convertedTick.remaining / currentDuration,
formattedRemaining = tickFormatter(convertedTick.remaining),
second = Math.floor(tick.elapsed / 1000);
if (onTick.lastSecond !== second) {
onTick.lastSecond = second;
if (convertedTick.remaining <= 5000 && convertedTick.step < sequence.length) {
pulse();
} else {
sounds.blank();
}
}
dom.setText("time", formattedRemaining.time);
dom.setText("ms", `.${formattedRemaining.ms}`);
if (convertedTick.step < sequence.length) {
document.getElementById("total").setAttribute("d", getCirclePath(total, TOTAL_OUTER, TOTAL_INNER));
document.getElementById("step").setAttribute("d", getCirclePath(step, STEP_OUTER, STEP_INNER));
dom.setText("stepOn", `${convertedTick.step + 1} / ${sequence.length}`);
requestAnimFrame(ticker.tick.bind(ticker));
} else {
done();
}
},
progressContainer = ({outerRadius, innerRadius, id, color}) => {
return [
svg.circle({cx: 0, cy: 0, r: outerRadius, stroke: "url(#outerBorder)", "stroke-width": 0.01,
fill: colors.circle.background}),
svg.circle({cx: 0, cy: 0, r: innerRadius, stroke: "url(#innerBorder)", "stroke-width": 0.01,
fill: colors.background}),
svg.path({id: id,
d: `M 0 -${outerRadius} A ${outerRadius} ${outerRadius} 0 0 1 ${outerRadius} 0
L ${innerRadius} 0 A ${innerRadius} ${innerRadius} 0 0 0 0 -${innerRadius} L 0 -${outerRadius}`,
fill: color, stroke: color, "stroke-opacity": 0.2, "stroke-width": 0.01})
];
},
setup = () => {
if (0 === sequence.length) {
alert("No sequence to play");
return {};
}
document.body.appendChild(svg({
width: "100%",
height: "100%",
viewBox: "-1 -1 2 2",
style: `background-color: ${colors.background};`
}, [gradients()]
.concat(progressContainer({
outerRadius: TOTAL_OUTER,
innerRadius: TOTAL_INNER,
id: "total",
color: colors.progress.total
}))
.concat(progressContainer({
outerRadius: STEP_OUTER,
innerRadius: STEP_INNER,
id: "step",
color: colors.progress.step
}))
.concat([
svg.text({id: "time",
"font-family": "Arial", "font-size": 0.3, x: 0, y: 0.1, "text-anchor": "middle",
fill: colors.text.time,
stroke: "url(#innerBorder)", "stroke-opacity": 0.2, "stroke-width": 0.01}, "00:00"),
svg.text({id: "ms",
"font-family": "Arial", "font-size": 0.1, x: 0.60, y: 0.1, "text-anchor": "end",
fill: colors.text.ms,
stroke: "url(#innerBorder)", "stroke-opacity": 0.2, "stroke-width": 0.001}, ".123"),
svg.text({id: "stepOn",
"font-family": "Arial", "font-size": 0.1, x: 0, y: 0.3, "text-anchor": "middle",
fill: colors.text.step,
stroke: "url(#outerBorder)", "stroke-opacity": 0.2, "stroke-width": 0.01}, "1 / 2"),
svg.circle({id: "pulse", cx: 0, cy: 0.85, r: 0, "stroke-width": 0, fill: "red", opacity: 0.5})
])
));
ticker.on(onTick);
return {
"undefined": () => {
if (ticker.isPaused()) {
sounds.play();
ticker.resume();
} else {
ticker.pause();
sounds.pause();
}
}
};
};
browser(setup);
| Adds an edit button to go back to edit
| src/run.js | Adds an edit button to go back to edit | <ide><path>rc/run.js
<ide> color: colors.progress.step
<ide> }))
<ide> .concat([
<add> svg.circle({id: "edit", r: 0.15, cx: 0, cy: -0.4,
<add> fill: colors.circle.light, stroke: "url(#innerBorder)", "stroke-width": 0.01}),
<add> svg.text({x: 0, y: -0.34, "font-family": "Arial", "font-size": 0.2, "text-anchor": "middle",
<add> fill: colors.text.step, stroke: "url(#outerBorder)", "stroke-opacity": 0.2,
<add> "stroke-width": 0.001}, "?"),
<ide> svg.text({id: "time",
<ide> "font-family": "Arial", "font-size": 0.3, x: 0, y: 0.1, "text-anchor": "middle",
<ide> fill: colors.text.time,
<ide> ));
<ide> ticker.on(onTick);
<ide> return {
<add> "edit": () => {
<add> let initialSequence = sequenceSerializer.read(location.search.substr(1));
<add> location = "edit.html#" + sequenceSerializer.write(initialSequence);
<add> },
<ide> "undefined": () => {
<ide> if (ticker.isPaused()) {
<ide> sounds.play(); |
|
Java | apache-2.0 | 91177cdca42fa81f6970d28ae8e402217419342e | 0 | indigo-dc/orchestrator,indigo-dc/orchestrator | /*
* Copyright © 2015-2017 Santer Reply S.p.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.reply.orchestrator.service;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import alien4cloud.component.repository.exception.CSARVersionAlreadyExistsException;
import alien4cloud.exception.InvalidArgumentException;
import alien4cloud.model.components.AbstractPropertyValue;
import alien4cloud.model.components.ComplexPropertyValue;
import alien4cloud.model.components.Csar;
import alien4cloud.model.components.DeploymentArtifact;
import alien4cloud.model.components.ListPropertyValue;
import alien4cloud.model.components.PropertyDefinition;
import alien4cloud.model.components.ScalarPropertyValue;
import alien4cloud.model.topology.Capability;
import alien4cloud.model.topology.NodeTemplate;
import alien4cloud.model.topology.RelationshipTemplate;
import alien4cloud.model.topology.Topology;
import alien4cloud.security.model.Role;
import alien4cloud.tosca.ArchiveParser;
import alien4cloud.tosca.ArchiveUploadService;
import alien4cloud.tosca.model.ArchiveRoot;
import alien4cloud.tosca.normative.IPropertyType;
import alien4cloud.tosca.normative.InvalidPropertyValueException;
import alien4cloud.tosca.parser.ParsingContext;
import alien4cloud.tosca.parser.ParsingError;
import alien4cloud.tosca.parser.ParsingErrorLevel;
import alien4cloud.tosca.parser.ParsingException;
import alien4cloud.tosca.parser.ParsingResult;
import alien4cloud.tosca.serializer.VelocityUtil;
import alien4cloud.utils.FileUtil;
import it.reply.orchestrator.config.properties.OidcProperties.OidcClientProperties;
import it.reply.orchestrator.config.properties.OrchestratorProperties;
import it.reply.orchestrator.dal.entity.Resource;
import it.reply.orchestrator.dto.CloudProvider;
import it.reply.orchestrator.dto.cmdb.CloudService;
import it.reply.orchestrator.dto.cmdb.ImageData;
import it.reply.orchestrator.dto.cmdb.Type;
import it.reply.orchestrator.dto.deployment.PlacementPolicy;
import it.reply.orchestrator.dto.onedata.OneData;
import it.reply.orchestrator.enums.DeploymentProvider;
import it.reply.orchestrator.exception.OrchestratorException;
import it.reply.orchestrator.exception.service.DeploymentException;
import it.reply.orchestrator.exception.service.ToscaException;
import it.reply.orchestrator.service.security.OAuth2TokenService;
import it.reply.orchestrator.utils.CommonUtils;
import it.reply.orchestrator.utils.ToscaConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jgrapht.alg.CycleDetector;
import org.jgrapht.graph.DirectedMultigraph;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Service;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.PostConstruct;
import javax.validation.ValidationException;
@Service
@Slf4j
public class ToscaServiceImpl implements ToscaService {
public static final String REMOVAL_LIST_PROPERTY_NAME = "removal_list";
public static final String SCALABLE_CAPABILITY_NAME = "scalable";
public static final String OS_CAPABILITY_NAME = "os";
@Autowired
private ApplicationContext ctx;
@Autowired
private ArchiveParser parser;
@Autowired
private ArchiveUploadService archiveUploadService;
@Autowired
private IndigoInputsPreProcessorService indigoInputsPreProcessorService;
@Autowired
private OAuth2TokenService oauth2tokenService;
@Value("${directories.alien}/${directories.csar_repository}")
private String alienRepoDir;
@Value("${tosca.definitions.normative}")
private String normativeLocalName;
@Value("${tosca.definitions.indigo}")
private String indigoLocalName;
@Autowired
private OrchestratorProperties orchestratorProperties;
/**
* Load normative and non-normative types.
*
*/
@PostConstruct
public void init() throws IOException, CSARVersionAlreadyExistsException, ParsingException {
if (Paths.get(alienRepoDir).toFile().exists()) {
FileUtil.delete(Paths.get(alienRepoDir));
}
// set requiredAuth to upload TOSCA types
Optional<Authentication> oldAuth = setAutenticationForToscaImport();
try (InputStream is = ctx.getResource(normativeLocalName).getInputStream()) {
Path zipFile = File.createTempFile(normativeLocalName, ".zip").toPath();
zip(is, zipFile);
ParsingResult<Csar> result = archiveUploadService.upload(zipFile);
if (!result.getContext().getParsingErrors().isEmpty()) {
LOG.warn("Error parsing definition {}:\n{}", normativeLocalName,
Arrays.toString(result.getContext().getParsingErrors().toArray()));
}
}
try (InputStream is = ctx.getResource(indigoLocalName).getInputStream()) {
Path zipFile = File.createTempFile(indigoLocalName, ".zip").toPath();
zip(is, zipFile);
ParsingResult<Csar> result = archiveUploadService.upload(zipFile);
if (!result.getContext().getParsingErrors().isEmpty()) {
LOG.warn("Error parsing definition {}:\n{}", indigoLocalName,
Arrays.toString(result.getContext().getParsingErrors().toArray()));
}
}
// restore old auth if present
oldAuth.ifPresent(SecurityContextHolder.getContext()::setAuthentication);
}
/**
* Utility to zip an inputStream.
*
*/
public static void zip(InputStream fileStream, Path outputPath) throws IOException {
FileUtil.touch(outputPath);
try (ZipOutputStream zipOutputStream =
new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(outputPath)))) {
zipOutputStream.putNextEntry(new ZipEntry("definition.yml"));
ByteStreams.copy(fileStream, zipOutputStream);
zipOutputStream.closeEntry();
zipOutputStream.flush();
}
}
@Override
public ParsingResult<ArchiveRoot> getArchiveRootFromTemplate(String toscaTemplate)
throws ParsingException {
try (ByteArrayInputStream is = new ByteArrayInputStream(toscaTemplate.getBytes());) {
Path zipPath = Files.createTempFile("csar", ".zip");
zip(is, zipPath);
ParsingResult<ArchiveRoot> result = parser.parse(zipPath);
try {
Files.delete(zipPath);
} catch (Exception ioe) {
LOG.warn("Error deleting tmp csar {} from FS", zipPath, ioe);
}
return result;
} catch (InvalidArgumentException iae) {
// FIXME NOTE that InvalidArgumentException should not be thrown by the parse method, but it
// is...
// throw new ParsingException("DUMMY", new ParsingError(ErrorCode.INVALID_YAML, ));
throw iae;
} catch (IOException ex) {
throw new OrchestratorException("Error Parsing TOSCA Template", ex);
}
}
@Override
public String getTemplateFromTopology(ArchiveRoot archiveRoot) {
Map<String, Object> velocityCtx = new HashMap<>();
velocityCtx.put("tosca_definitions_version",
archiveRoot.getArchive().getToscaDefinitionsVersion());
velocityCtx.put("description", archiveRoot.getArchive().getDescription());
velocityCtx.put("template_name", archiveRoot.getArchive().getName());
velocityCtx.put("template_version", archiveRoot.getArchive().getVersion());
velocityCtx.put("template_author", archiveRoot.getArchive().getTemplateAuthor());
velocityCtx.put("repositories", archiveRoot.getArchive().getRepositories());
velocityCtx.put("topology", archiveRoot.getTopology());
StringWriter writer = new StringWriter();
try {
VelocityUtil.generate("templates/topology-1_0_0_INDIGO.yml.vm", writer, velocityCtx);
} catch (IOException ex) {
throw new OrchestratorException("Error serializing TOSCA template", ex);
}
String template = writer.toString();
// Log the warning because Alien4Cloud uses an hard-coded Velocity template to encode the string
// and some information might be missing!!
LOG.warn("TOSCA template conversion from in-memory: "
+ "WARNING: Some nodes or properties might be missing!! Use at your own risk!");
LOG.debug(template);
return template;
}
@Override
public void replaceInputFunctions(ArchiveRoot archiveRoot, Map<String, Object> inputs) {
indigoInputsPreProcessorService.processGetInput(archiveRoot, inputs);
}
@Override
public ArchiveRoot parseAndValidateTemplate(String toscaTemplate, Map<String, Object> inputs) {
ArchiveRoot ar = parseTemplate(toscaTemplate);
Optional.ofNullable(ar.getTopology()).map(topology -> topology.getInputs()).ifPresent(
topologyInputs -> validateUserInputs(topologyInputs, inputs));
return ar;
}
@Override
public ArchiveRoot prepareTemplate(String toscaTemplate, Map<String, Object> inputs) {
ArchiveRoot ar = parseAndValidateTemplate(toscaTemplate, inputs);
replaceInputFunctions(ar, inputs);
return ar;
}
@Override
public void validateUserInputs(Map<String, PropertyDefinition> templateInputs,
Map<String, Object> inputs) {
// Check if every required input has been given by the user or has a default value
templateInputs.forEach((inputName, inputDefinition) -> {
if (inputDefinition.isRequired()
&& inputs.getOrDefault(inputName, inputDefinition.getDefault()) == null) {
// Input required and no value to replace -> error
throw new ToscaException(
String.format("Input <%s> is required and is not present in the user's input list,"
+ " nor has a default value", inputName));
}
});
// Reference:
// http://docs.oasis-open.org/tosca/TOSCA-Simple-Profile-YAML/v1.0/csprd02/TOSCA-Simple-Profile-YAML-v1.0-csprd02.html#TYPE_YAML_STRING
// FIXME Check input type compatibility ?
// templateInput.getValue().getType()
}
@Override
public ArchiveRoot parseTemplate(String toscaTemplate) {
try {
ParsingResult<ArchiveRoot> result = getArchiveRootFromTemplate(toscaTemplate);
Optional<ToscaException> exception = checkParsingErrors(
Optional.ofNullable(result.getContext()).map(ParsingContext::getParsingErrors));
if (exception.isPresent()) {
throw exception.get();
}
return result.getResult();
} catch (ParsingException ex) {
Optional<ToscaException> exception =
checkParsingErrors(Optional.ofNullable(ex.getParsingErrors()));
if (exception.isPresent()) {
throw exception.get();
} else {
throw new ToscaException("Failed to parse template, ex");
}
}
}
@Override
public String updateTemplate(String template) {
ArchiveRoot parsedTempalte = parseTemplate(template);
removeRemovalList(parsedTempalte);
return getTemplateFromTopology(parsedTempalte);
}
private Optional<ToscaException> checkParsingErrors(Optional<List<ParsingError>> errorList) {
return filterNullAndInfoErrorFromParsingError(errorList)
.map(list -> list.stream().map(Object::toString).collect(Collectors.joining("; ")))
.map(ToscaException::new);
}
private Optional<List<ParsingError>> filterNullAndInfoErrorFromParsingError(
Optional<List<ParsingError>> listToFilter) {
return listToFilter.map(list -> list.stream()
.filter(Objects::nonNull)
.filter(error -> !ParsingErrorLevel.INFO.equals(error.getErrorLevel()))
.collect(Collectors.toList())).filter(list -> !list.isEmpty());
}
@Override
public void contextualizeAndReplaceImages(ArchiveRoot parsingResult, CloudProvider cloudProvider,
String cloudServiceId, DeploymentProvider deploymentProvider) {
Map<Boolean, Map<NodeTemplate, ImageData>> contextualizedImages =
contextualizeImages(parsingResult, cloudProvider, cloudServiceId);
Preconditions.checkState(contextualizedImages.get(Boolean.FALSE).isEmpty(),
"Error contextualizing images; images for nodes %s couldn't be contextualized",
contextualizedImages
.get(Boolean.FALSE)
.keySet()
.stream()
.map(NodeTemplate::getName)
.collect(Collectors.toList()));
replaceImage(contextualizedImages.get(Boolean.TRUE), cloudProvider, deploymentProvider);
}
@Override
public Map<NodeTemplate, ImageData> extractImageRequirements(ArchiveRoot parsingResult) {
// Only indigo.Compute nodes are relevant
return getNodesOfType(parsingResult, ToscaConstants.Nodes.COMPUTE).stream().map(node -> {
ImageData imageMetadata = new ImageData();
Optional.ofNullable(node.getCapabilities())
.map(capabilities -> capabilities.get(OS_CAPABILITY_NAME))
.ifPresent(osCapability -> {
// We've got an OS capability -> Check the attributes to find best match for the image
this.<ScalarPropertyValue>getTypedCapabilityPropertyByName(osCapability, "image")
.ifPresent(property -> imageMetadata.setImageName(property.getValue()));
this.<ScalarPropertyValue>getTypedCapabilityPropertyByName(osCapability, "architecture")
.ifPresent(property -> imageMetadata.setArchitecture(property.getValue()));
this.<ScalarPropertyValue>getTypedCapabilityPropertyByName(osCapability, "type")
.ifPresent(property -> imageMetadata.setType(property.getValue()));
this.<ScalarPropertyValue>getTypedCapabilityPropertyByName(osCapability, "distribution")
.ifPresent(property -> imageMetadata.setDistribution(property.getValue()));
this.<ScalarPropertyValue>getTypedCapabilityPropertyByName(osCapability, "version")
.ifPresent(property -> imageMetadata.setVersion(property.getValue()));
});
return new SimpleEntry<>(node, imageMetadata);
}).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
@Override
public Map<Boolean, Map<NodeTemplate, ImageData>> contextualizeImages(ArchiveRoot parsingResult,
CloudProvider cloudProvider, String cloudServiceId) {
try {
return extractImageRequirements(parsingResult).entrySet().stream().map(entry -> {
NodeTemplate node = entry.getKey();
ImageData imageMetadata = entry.getValue();
final Optional<ImageData> image;
// TODO FILTER ON DEPLOYMENT PROVIDER?
if (isImImageUri(imageMetadata.getImageName())) {
image = Optional.of(imageMetadata);
} else {
List<ImageData> images = cloudProvider.getCmdbProviderImages()
.getOrDefault(cloudServiceId, Collections.emptyList());
image = getBestImageForCloudProvider(imageMetadata, images);
}
if (image.isPresent()) {
// Found a good image -> replace the image attribute with the provider-specific ID
LOG.debug(
"Found image match in <{}> for image metadata <{}>"
+ ", provider-specific image id <{}>",
cloudProvider.getId(), imageMetadata, image.get().getImageId());
} else {
// No image match found -> throw error
LOG.debug("Failed to found a match in provider <{}> for image metadata <{}>",
cloudProvider.getId(), imageMetadata);
}
return new SimpleEntry<>(node, image);
}).collect(Collectors.partitioningBy(entry -> entry.getValue().isPresent(),
// do not use the Collectors.toMap() because it doesn't play nice with null values
// https://bugs.openjdk.java.net/browse/JDK-8148463
CommonUtils.toMap(Entry::getKey, entry -> entry.getValue().orElse(null))));
} catch (Exception ex) {
throw new RuntimeException("Failed to contextualize images", ex);
}
}
private void replaceImage(Map<NodeTemplate, ImageData> contextualizedImages,
CloudProvider cloudProvider, DeploymentProvider deploymentProvider) {
contextualizedImages.forEach((node, image) -> {
Map<String, Capability> capabilities =
Optional.ofNullable(node.getCapabilities()).orElseGet(() -> {
node.setCapabilities(new HashMap<>());
return node.getCapabilities();
});
// The node doesn't have an OS Capability -> need to add a dummy one to hold a
// random image for underlying deployment systems
Capability osCapability = capabilities.computeIfAbsent(OS_CAPABILITY_NAME, key -> {
LOG.debug("Generating default OperatingSystem capability for node <{}>", node.getName());
Capability capability = new Capability();
capability.setType("tosca.capabilities.indigo.OperatingSystem");
return capability;
});
String imageId = image.getImageId();
if (deploymentProvider == DeploymentProvider.IM) {
if (isImImageUri(image.getImageName())) {
imageId = image.getImageName();
} else {
imageId = generateImImageUri(cloudProvider, image);
}
}
ScalarPropertyValue scalarPropertyValue = createScalarPropertyValue(imageId);
osCapability.getProperties().put("image", scalarPropertyValue);
if (StringUtils.isNotBlank(image.getUserName())) {
Map<String, Object> credential = new HashMap<>();
ComplexPropertyValue credentialProperty = new ComplexPropertyValue(credential);
credentialProperty.setPrintable(true);
osCapability.getProperties().put("credential", credentialProperty);
scalarPropertyValue = createScalarPropertyValue(image.getUserName());
credential.put("user", scalarPropertyValue);
scalarPropertyValue = createScalarPropertyValue("");
credential.put("token", scalarPropertyValue);
}
});
}
@Deprecated
private boolean isImImageUri(String imageName) {
try {
List<String> schemes = ImmutableList.of("ost", "one", "aws", "azr");
return schemes.contains(URI.create(imageName).getScheme().trim());
} catch (RuntimeException ex) {
return false;
}
}
@Deprecated
private String generateImImageUri(CloudProvider cloudProvider, ImageData image) {
try {
CloudService cs;
if (image.getService() != null
&& cloudProvider.getCmdbProviderServices().get(image.getService()) != null) {
cs = cloudProvider.getCmdbProviderServices().get(image.getService());
} else {
if (cloudProvider.getCmbdProviderServicesByType(Type.COMPUTE).isEmpty()) {
throw new DeploymentException(
"No compute service available fo cloud provider " + cloudProvider.getId());
} else {
cs = cloudProvider.getCmbdProviderServicesByType(Type.COMPUTE).get(0);
}
}
StringBuilder sb = new StringBuilder();
if (cs.isOpenStackComputeProviderService() || cs.isOtcComputeProviderService()) {
sb
.append("ost")
.append("://")
.append(new URL(cs.getData().getEndpoint()).getHost())
.append("/");
} else if (cs.isOpenNebulaComputeProviderService() || cs.isOpenNebulaToscaProviderService()) {
sb
.append("one")
.append("://")
.append(new URL(cs.getData().getEndpoint()).getHost())
.append("/");
} else if (cs.isOcciComputeProviderService()) {
// DO NOTHING ??
} else if (cs.isAwsComputeProviderService()) {
sb
.append("aws")
.append("://");
} else if (cs.isAzureComputeProviderService()) {
sb
.append("azr")
.append("://");
} else {
throw new DeploymentException("Unknown IaaSType of cloud provider " + cloudProvider);
}
sb.append(image.getImageId());
return sb.toString();
} catch (Exception ex) {
LOG.error("Cannot retrieve Compute service host for IM image id generation", ex);
return image.getImageId();
}
}
protected Optional<ImageData> getBestImageForCloudProvider(ImageData imageMetadata,
Collection<ImageData> images) {
// Match image name first (for INDIGO specific use case, if the image cannot be found with the
// specified name it means that a base image + Ansible configuration have to be used -> the
// base image will be chosen with the other filters and image metadata - architecture, type,
// distro, version)
if (imageMetadata.getImageName() != null) {
Optional<ImageData> imageWithName =
findImageWithNameOnCloudProvider(imageMetadata.getImageName(), images);
if (imageWithName.isPresent()) {
LOG.debug("Image <{}> found with name <{}>", imageWithName.get().getImageId(),
imageMetadata.getImageName());
return imageWithName;
} else {
if (imageMetadata.getType() == null && imageMetadata.getArchitecture() == null
&& imageMetadata.getDistribution() == null && imageMetadata.getVersion() == null) {
return Optional.empty();
}
LOG.debug("Image not found with name <{}>, trying with other fields: <{}>",
imageMetadata.getImageName(), imageMetadata);
}
}
for (ImageData image : images) {
// Match or skip image based on each additional optional attribute
if (imageMetadata.getType() != null) {
if (!imageMetadata.getType().equalsIgnoreCase(image.getType())) {
continue;
}
}
if (imageMetadata.getArchitecture() != null) {
if (!imageMetadata.getArchitecture().equalsIgnoreCase(image.getArchitecture())) {
continue;
}
}
if (imageMetadata.getDistribution() != null) {
if (!imageMetadata.getDistribution().equalsIgnoreCase(image.getDistribution())) {
continue;
}
}
if (imageMetadata.getVersion() != null) {
if (!imageMetadata.getVersion().equalsIgnoreCase(image.getVersion())) {
continue;
}
}
LOG.debug("Image <{}> found with fields: <{}>", imageMetadata.getImageId(), imageMetadata);
return Optional.of(image);
}
return Optional.empty();
}
protected Optional<ImageData> findImageWithNameOnCloudProvider(String requiredImageName,
Collection<ImageData> images) {
return images.stream()
.filter(image -> matchImageNameAndTag(requiredImageName, image.getImageName()))
.findFirst();
}
protected boolean matchImageNameAndTag(String requiredImageName, String availableImageName) {
// Extract Docker tag if available
String[] requiredImageNameSplit = requiredImageName.split(":");
String requiredImageBaseName = requiredImageNameSplit[0];
String requiredImageTag =
(requiredImageNameSplit.length > 1 ? requiredImageNameSplit[1] : null);
String[] availableImageNameSplit = availableImageName.split(":");
String availableImageBaseName = availableImageNameSplit[0];
String availableImageTag =
(availableImageNameSplit.length > 1 ? availableImageNameSplit[1] : null);
// Match name
boolean nameMatch = requiredImageBaseName.equals(availableImageBaseName);
// Match tag (if not given the match is true)
boolean tagMatch =
(requiredImageTag != null ? requiredImageTag.equals(availableImageTag) : true);
return nameMatch && tagMatch;
}
private Collection<NodeTemplate> getNodesFromArchiveRoot(ArchiveRoot archiveRoot) {
return Optional.ofNullable(archiveRoot.getTopology())
.map(this::getNodesFromTopology)
.orElseGet(ArrayList::new);
}
private Collection<NodeTemplate> getNodesFromTopology(Topology topology) {
return Optional.ofNullable(topology.getNodeTemplates())
.map(Map::values)
.map(nodes -> nodes.stream().filter(Objects::nonNull).collect(Collectors.toList()))
.orElseGet(ArrayList::new);
}
@Override
public Collection<NodeTemplate> getNodesOfType(ArchiveRoot archiveRoot, String type) {
Preconditions.checkNotNull(type);
return getNodesFromArchiveRoot(archiveRoot).stream()
.filter(node -> isOfToscaType(node, type))
.collect(Collectors.toList());
}
@Override
public boolean isOfToscaType(NodeTemplate node, String nodeType) {
return isSubTypeOf(Preconditions.checkNotNull(node).getType(), nodeType);
}
@Override
public boolean isOfToscaType(Resource resource, String nodeType) {
return isSubTypeOf(Preconditions.checkNotNull(resource).getToscaNodeType(), nodeType);
}
private boolean isSubTypeOf(@Nullable String optionalNodeType, String superNodeType) {
return Optional
.ofNullable(optionalNodeType)
// FIXME: Check inheritance
.filter(nodeType -> CommonUtils
.checkNotNull(nodeType)
.equals(Preconditions.checkNotNull(superNodeType)))
.isPresent();
}
@Override
public boolean isHybridDeployment(ArchiveRoot archiveRoot) {
// check if there is a "hybrid" ScalarPropertyValue with "true" as value
return getNodesOfType(archiveRoot, ToscaConstants.Nodes.ELASTIC_CLUSTER).stream()
.anyMatch(node -> getNodePropertyByName(node, "hybrid")
.filter(ScalarPropertyValue.class::isInstance)
.map(ScalarPropertyValue.class::cast)
.map(ScalarPropertyValue::getValue)
.filter(Boolean::valueOf)
.isPresent());
}
@Override
public void addElasticClusterParameters(ArchiveRoot archiveRoot, String deploymentId,
@Nullable String oauthToken) {
getNodesOfType(archiveRoot, ToscaConstants.Nodes.ELASTIC_CLUSTER).forEach(node -> {
// create properties Map if null
Map<String, AbstractPropertyValue> properties =
Optional.ofNullable(node.getProperties()).orElseGet(() -> {
node.setProperties(new HashMap<>());
return node.getProperties();
});
// Create new property with the deploymentId and set as printable
properties.put("deployment_id", createScalarPropertyValue(deploymentId));
// Create new property with the orchestrator_url and set as printable
properties.put("orchestrator_url",
createScalarPropertyValue(orchestratorProperties.getUrl().toString()));
if (oauthToken != null) {
// Create new property with the iam_access_token and set as printable
properties.put("iam_access_token", createScalarPropertyValue(oauthToken));
Optional<OidcClientProperties> cluesInfo = oauth2tokenService.getCluesInfo(oauthToken);
cluesInfo.ifPresent(info -> {
// Create new property with the iam_clues_client_id and set as printable
properties.put("iam_clues_client_id", createScalarPropertyValue(info.getClientId()));
// Create new property with the iam_clues_client_secret and set as printable
properties.put("iam_clues_client_secret",
createScalarPropertyValue(info.getClientSecret()));
});
}
});
}
private static ScalarPropertyValue createScalarPropertyValue(String value) {
ScalarPropertyValue scalarPropertyValue = new ScalarPropertyValue(value);
scalarPropertyValue.setPrintable(true);
return scalarPropertyValue;
}
public void removeRemovalList(ArchiveRoot archiveRoot) {
getNodesFromArchiveRoot(archiveRoot)
.forEach(this::removeRemovalList);
}
@Override
public void removeRemovalList(NodeTemplate node) {
getNodeCapabilityByName(node, SCALABLE_CAPABILITY_NAME)
.ifPresent(scalable -> CommonUtils
.removeFromOptionalMap(scalable.getProperties(), REMOVAL_LIST_PROPERTY_NAME));
}
private static Optional<Authentication> setAutenticationForToscaImport() {
Authentication oldAuth = SecurityContextHolder.getContext().getAuthentication();
Authentication newAuth = new PreAuthenticatedAuthenticationToken(
Role.ADMIN.name().toLowerCase(), "", AuthorityUtils.createAuthorityList(Role.ADMIN.name()));
SecurityContextHolder.getContext().setAuthentication(newAuth);
return Optional.ofNullable(oldAuth);
}
@Override
public Optional<Capability> getNodeCapabilityByName(NodeTemplate node, String capabilityName) {
return CommonUtils.getFromOptionalMap(node.getCapabilities(), capabilityName);
}
@Override
public Optional<AbstractPropertyValue> getNodePropertyByName(NodeTemplate node,
String propertyName) {
return CommonUtils.getFromOptionalMap(node.getProperties(), propertyName);
}
@Override
public <T extends AbstractPropertyValue> Optional<T> getTypedNodePropertyByName(NodeTemplate node,
String propertyName) {
return CommonUtils.optionalCast(getNodePropertyByName(node, propertyName));
}
@Override
public Optional<AbstractPropertyValue> getCapabilityPropertyByName(Capability capability,
String propertyName) {
return CommonUtils.getFromOptionalMap(capability.getProperties(), propertyName);
}
@Override
public <T extends AbstractPropertyValue> Optional<T> getTypedCapabilityPropertyByName(
Capability capability, String propertyName) {
return CommonUtils.optionalCast(getCapabilityPropertyByName(capability, propertyName));
}
@Override
public Optional<DeploymentArtifact> getNodeArtifactByName(NodeTemplate node,
String artifactName) {
return CommonUtils.getFromOptionalMap(node.getArtifacts(), artifactName);
}
@Override
public Map<String, NodeTemplate> getAssociatedNodesByCapability(Map<String, NodeTemplate> nodes,
NodeTemplate nodeTemplate, String capabilityName) {
return getRelationshipTemplatesByCapabilityName(nodeTemplate.getRelationships(), capabilityName)
.stream().map(relationship -> relationship.getTarget()).collect(
Collectors.toMap(associatedNodeName -> associatedNodeName,
associatedNodeName -> nodes.get(associatedNodeName)));
}
@Override
public List<RelationshipTemplate> getRelationshipTemplatesByCapabilityName(
Map<String, RelationshipTemplate> relationships, String capabilityName) {
List<RelationshipTemplate> relationshipTemplates = new ArrayList<>();
if (relationships == null) {
return relationshipTemplates;
}
for (Map.Entry<String, RelationshipTemplate> relationship : relationships.entrySet()) {
if (relationship.getValue().getTargetedCapabilityName().equals(capabilityName)) {
relationshipTemplates.add(relationship.getValue());
}
}
return relationshipTemplates;
}
@Override
public Optional<Integer> getCount(NodeTemplate nodeTemplate) {
return getNodeCapabilityByName(nodeTemplate, SCALABLE_CAPABILITY_NAME)
.flatMap(capability -> this
.<ScalarPropertyValue>getTypedCapabilityPropertyByName(capability, "count"))
.map(property -> property.getValue())
.map(value -> Integer.parseInt(value));
}
@Override
public boolean isScalable(NodeTemplate nodeTemplate) {
return getCount(nodeTemplate).isPresent();
}
@Override
public Collection<NodeTemplate> getScalableNodes(ArchiveRoot archiveRoot) {
return getNodesFromArchiveRoot(archiveRoot)
.stream()
.filter(this::isScalable)
.collect(Collectors.toList());
}
@Override
public List<String> getRemovalList(NodeTemplate nodeTemplate) {
Optional<ListPropertyValue> listPropertyValue =
getNodeCapabilityByName(nodeTemplate, SCALABLE_CAPABILITY_NAME)
.flatMap(capability -> getTypedCapabilityPropertyByName(capability,
REMOVAL_LIST_PROPERTY_NAME));
List<Object> items =
listPropertyValue.map(property -> property.getValue()).orElseGet(Collections::emptyList);
List<String> removalList = new ArrayList<>();
for (Object item : items) {
if (item instanceof ScalarPropertyValue) {
removalList.add(((ScalarPropertyValue) item).getValue());
} else if (item instanceof String) {
removalList.add((String) item);
} else {
LOG.warn("Skipped unsupported value <{}> in {} of node {}", item,
REMOVAL_LIST_PROPERTY_NAME, nodeTemplate.getName());
}
}
return removalList;
}
@Override
public Map<String, OneData> extractOneDataRequirements(ArchiveRoot archiveRoot,
Map<String, Object> inputs) {
try {
// FIXME: Remove hard-coded input extraction and search on OneData nodes instead
/*
* By now, OneData requirements are in user's input fields: input_onedata_space,
* output_onedata_space, [input_onedata_providers, output_onedata_providers]
*/
Map<String, OneData> result = new HashMap<>();
OneData oneDataInput = null;
if (inputs.get("input_onedata_space") != null) {
oneDataInput = OneData.builder()
.token((String) inputs.get("input_onedata_token"))
.space((String) inputs.get("input_onedata_space"))
.path((String) inputs.get("input_path"))
.providers((String) inputs.get("input_onedata_providers"))
.zone((String) inputs.get("input_onedata_zone"))
.build();
if (oneDataInput.getProviders().isEmpty()) {
oneDataInput.setSmartScheduling(true);
}
result.put("input", oneDataInput);
LOG.debug("Extracted OneData requirement for node <{}>: <{}>", "input", oneDataInput);
}
if (inputs.get("output_onedata_space") != null) {
OneData oneDataOutput = OneData.builder()
.token((String) inputs.get("output_onedata_token"))
.space((String) inputs.get("output_onedata_space"))
.path((String) inputs.get("output_path"))
.providers((String) inputs.get("output_onedata_providers"))
.zone((String) inputs.get("output_onedata_zone"))
.build();
if (oneDataOutput.getProviders().isEmpty()) {
if (oneDataInput != null) {
oneDataOutput.setProviders(oneDataInput.getProviders());
oneDataOutput.setSmartScheduling(oneDataInput.isSmartScheduling());
} else {
oneDataOutput.setSmartScheduling(true);
}
}
result.put("output", oneDataOutput);
LOG.debug("Extracted OneData requirement for node <{}>: <{}>", "output", oneDataOutput);
}
if (result.size() == 0) {
LOG.debug("No OneData requirements to extract");
}
return result;
} catch (Exception ex) {
throw new RuntimeException("Failed to extract OneData requirements: " + ex.getMessage(), ex);
}
}
@Override
public List<PlacementPolicy> extractPlacementPolicies(ArchiveRoot archiveRoot) {
List<PlacementPolicy> placementPolicies = new ArrayList<>();
Optional.ofNullable(archiveRoot.getTopology())
.map(topology -> topology.getPolicies())
.orElseGet(Collections::emptyList)
.forEach(policy -> {
if (policy instanceof alien4cloud.model.topology.PlacementPolicy) {
PlacementPolicy placementPolicy =
PlacementPolicy.fromToscaType((alien4cloud.model.topology.PlacementPolicy) policy);
placementPolicies.add(placementPolicy);
} else {
LOG.warn("Skipping unsupported Policy {}", policy);
}
});
return placementPolicies;
}
@Override
public DirectedMultigraph<NodeTemplate, RelationshipTemplate> buildNodeGraph(
Map<String, NodeTemplate> nodes, boolean checkForCycles) {
DirectedMultigraph<NodeTemplate, RelationshipTemplate> graph =
new DirectedMultigraph<>(RelationshipTemplate.class);
nodes.entrySet().forEach(nodeEntry -> {
NodeTemplate toNode = nodeEntry.getValue();
graph.addVertex(toNode);
Map<String, RelationshipTemplate> relationships =
Optional.ofNullable(toNode.getRelationships()).orElseGet(HashMap::new);
relationships.values().forEach(relationship -> {
NodeTemplate fromNode = nodes.get(relationship.getTarget());
graph.addVertex(fromNode);
graph.addEdge(fromNode, toNode, relationship);
});
});
if (checkForCycles) {
CycleDetector<NodeTemplate, RelationshipTemplate> cycleDetector = new CycleDetector<>(graph);
Set<NodeTemplate> cyclyingNodes = cycleDetector.findCycles();
if (!cyclyingNodes.isEmpty()) {
String message = "Found node depencency loop in TOSCA topology; involved nodes: "
+ Arrays.toString(cyclyingNodes.stream().map(NodeTemplate::getName).toArray());
LOG.error(message);
throw new ValidationException(message);
}
}
return graph;
}
@Override
public <T extends IPropertyType<V>, V> V parseScalarPropertyValue(ScalarPropertyValue value,
Class<T> clazz) {
T propertyParser = BeanUtils.instantiate(clazz);
try {
return propertyParser.parse(value.getValue());
} catch (InvalidPropertyValueException ex) {
throw new ToscaException(String.format("Error parsing scalar value <%s> as <%s>",
value.getValue(), propertyParser.getTypeName()), ex);
}
}
@Override
public <V> List<V> parseListPropertyValue(ListPropertyValue value, Function<Object, V> mapper) {
return Optional.ofNullable(value.getValue())
.orElseGet(Collections::emptyList)
.stream()
.filter(item -> item != null)
.map(mapper)
.collect(Collectors.toList());
}
@Override
public <V> Map<String, V> parseComplexPropertyValue(ComplexPropertyValue value,
Function<Object, V> mapper) {
return Optional.ofNullable(value.getValue())
.orElseGet(Collections::emptyMap)
.entrySet()
.stream()
.filter(entry -> entry.getValue() != null)
.collect(Collectors.toMap(Entry::getKey, mapper.compose(Entry::getValue)));
}
}
| src/main/java/it/reply/orchestrator/service/ToscaServiceImpl.java | /*
* Copyright © 2015-2017 Santer Reply S.p.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.reply.orchestrator.service;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import alien4cloud.component.repository.exception.CSARVersionAlreadyExistsException;
import alien4cloud.exception.InvalidArgumentException;
import alien4cloud.model.components.AbstractPropertyValue;
import alien4cloud.model.components.ComplexPropertyValue;
import alien4cloud.model.components.Csar;
import alien4cloud.model.components.DeploymentArtifact;
import alien4cloud.model.components.ListPropertyValue;
import alien4cloud.model.components.PropertyDefinition;
import alien4cloud.model.components.ScalarPropertyValue;
import alien4cloud.model.topology.Capability;
import alien4cloud.model.topology.NodeTemplate;
import alien4cloud.model.topology.RelationshipTemplate;
import alien4cloud.model.topology.Topology;
import alien4cloud.security.model.Role;
import alien4cloud.tosca.ArchiveParser;
import alien4cloud.tosca.ArchiveUploadService;
import alien4cloud.tosca.model.ArchiveRoot;
import alien4cloud.tosca.normative.IPropertyType;
import alien4cloud.tosca.normative.InvalidPropertyValueException;
import alien4cloud.tosca.parser.ParsingContext;
import alien4cloud.tosca.parser.ParsingError;
import alien4cloud.tosca.parser.ParsingErrorLevel;
import alien4cloud.tosca.parser.ParsingException;
import alien4cloud.tosca.parser.ParsingResult;
import alien4cloud.tosca.serializer.VelocityUtil;
import alien4cloud.utils.FileUtil;
import it.reply.orchestrator.config.properties.OidcProperties.OidcClientProperties;
import it.reply.orchestrator.config.properties.OrchestratorProperties;
import it.reply.orchestrator.dal.entity.Resource;
import it.reply.orchestrator.dto.CloudProvider;
import it.reply.orchestrator.dto.cmdb.CloudService;
import it.reply.orchestrator.dto.cmdb.ImageData;
import it.reply.orchestrator.dto.cmdb.Type;
import it.reply.orchestrator.dto.deployment.PlacementPolicy;
import it.reply.orchestrator.dto.onedata.OneData;
import it.reply.orchestrator.enums.DeploymentProvider;
import it.reply.orchestrator.exception.OrchestratorException;
import it.reply.orchestrator.exception.service.DeploymentException;
import it.reply.orchestrator.exception.service.ToscaException;
import it.reply.orchestrator.service.security.OAuth2TokenService;
import it.reply.orchestrator.utils.CommonUtils;
import it.reply.orchestrator.utils.ToscaConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jgrapht.alg.CycleDetector;
import org.jgrapht.graph.DirectedMultigraph;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Service;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.PostConstruct;
import javax.validation.ValidationException;
@Service
@Slf4j
public class ToscaServiceImpl implements ToscaService {
public static final String REMOVAL_LIST_PROPERTY_NAME = "removal_list";
public static final String SCALABLE_CAPABILITY_NAME = "scalable";
public static final String OS_CAPABILITY_NAME = "os";
@Autowired
private ApplicationContext ctx;
@Autowired
private ArchiveParser parser;
@Autowired
private ArchiveUploadService archiveUploadService;
@Autowired
private IndigoInputsPreProcessorService indigoInputsPreProcessorService;
@Autowired
private OAuth2TokenService oauth2tokenService;
@Value("${directories.alien}/${directories.csar_repository}")
private String alienRepoDir;
@Value("${tosca.definitions.normative}")
private String normativeLocalName;
@Value("${tosca.definitions.indigo}")
private String indigoLocalName;
@Autowired
private OrchestratorProperties orchestratorProperties;
/**
* Load normative and non-normative types.
*
*/
@PostConstruct
public void init() throws IOException, CSARVersionAlreadyExistsException, ParsingException {
if (Paths.get(alienRepoDir).toFile().exists()) {
FileUtil.delete(Paths.get(alienRepoDir));
}
// set requiredAuth to upload TOSCA types
Optional<Authentication> oldAuth = setAutenticationForToscaImport();
try (InputStream is = ctx.getResource(normativeLocalName).getInputStream()) {
Path zipFile = File.createTempFile(normativeLocalName, ".zip").toPath();
zip(is, zipFile);
ParsingResult<Csar> result = archiveUploadService.upload(zipFile);
if (!result.getContext().getParsingErrors().isEmpty()) {
LOG.warn("Error parsing definition {}:\n{}", normativeLocalName,
Arrays.toString(result.getContext().getParsingErrors().toArray()));
}
}
try (InputStream is = ctx.getResource(indigoLocalName).getInputStream()) {
Path zipFile = File.createTempFile(indigoLocalName, ".zip").toPath();
zip(is, zipFile);
ParsingResult<Csar> result = archiveUploadService.upload(zipFile);
if (!result.getContext().getParsingErrors().isEmpty()) {
LOG.warn("Error parsing definition {}:\n{}", indigoLocalName,
Arrays.toString(result.getContext().getParsingErrors().toArray()));
}
}
// restore old auth if present
oldAuth.ifPresent(SecurityContextHolder.getContext()::setAuthentication);
}
/**
* Utility to zip an inputStream.
*
*/
public static void zip(InputStream fileStream, Path outputPath) throws IOException {
FileUtil.touch(outputPath);
try (ZipOutputStream zipOutputStream =
new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(outputPath)))) {
zipOutputStream.putNextEntry(new ZipEntry("definition.yml"));
ByteStreams.copy(fileStream, zipOutputStream);
zipOutputStream.closeEntry();
zipOutputStream.flush();
}
}
@Override
public ParsingResult<ArchiveRoot> getArchiveRootFromTemplate(String toscaTemplate)
throws ParsingException {
try (ByteArrayInputStream is = new ByteArrayInputStream(toscaTemplate.getBytes());) {
Path zipPath = Files.createTempFile("csar", ".zip");
zip(is, zipPath);
return parser.parse(zipPath);
} catch (InvalidArgumentException iae) {
// FIXME NOTE that InvalidArgumentException should not be thrown by the parse method, but it
// is...
// throw new ParsingException("DUMMY", new ParsingError(ErrorCode.INVALID_YAML, ));
throw iae;
} catch (IOException ex) {
throw new OrchestratorException("Error Parsing TOSCA Template", ex);
}
}
@Override
public String getTemplateFromTopology(ArchiveRoot archiveRoot) {
Map<String, Object> velocityCtx = new HashMap<>();
velocityCtx.put("tosca_definitions_version",
archiveRoot.getArchive().getToscaDefinitionsVersion());
velocityCtx.put("description", archiveRoot.getArchive().getDescription());
velocityCtx.put("template_name", archiveRoot.getArchive().getName());
velocityCtx.put("template_version", archiveRoot.getArchive().getVersion());
velocityCtx.put("template_author", archiveRoot.getArchive().getTemplateAuthor());
velocityCtx.put("repositories", archiveRoot.getArchive().getRepositories());
velocityCtx.put("topology", archiveRoot.getTopology());
StringWriter writer = new StringWriter();
try {
VelocityUtil.generate("templates/topology-1_0_0_INDIGO.yml.vm", writer, velocityCtx);
} catch (IOException ex) {
throw new OrchestratorException("Error serializing TOSCA template", ex);
}
String template = writer.toString();
// Log the warning because Alien4Cloud uses an hard-coded Velocity template to encode the string
// and some information might be missing!!
LOG.warn("TOSCA template conversion from in-memory: "
+ "WARNING: Some nodes or properties might be missing!! Use at your own risk!");
LOG.debug(template);
return template;
}
@Override
public void replaceInputFunctions(ArchiveRoot archiveRoot, Map<String, Object> inputs) {
indigoInputsPreProcessorService.processGetInput(archiveRoot, inputs);
}
@Override
public ArchiveRoot parseAndValidateTemplate(String toscaTemplate, Map<String, Object> inputs) {
ArchiveRoot ar = parseTemplate(toscaTemplate);
Optional.ofNullable(ar.getTopology()).map(topology -> topology.getInputs()).ifPresent(
topologyInputs -> validateUserInputs(topologyInputs, inputs));
return ar;
}
@Override
public ArchiveRoot prepareTemplate(String toscaTemplate, Map<String, Object> inputs) {
ArchiveRoot ar = parseAndValidateTemplate(toscaTemplate, inputs);
replaceInputFunctions(ar, inputs);
return ar;
}
@Override
public void validateUserInputs(Map<String, PropertyDefinition> templateInputs,
Map<String, Object> inputs) {
// Check if every required input has been given by the user or has a default value
templateInputs.forEach((inputName, inputDefinition) -> {
if (inputDefinition.isRequired()
&& inputs.getOrDefault(inputName, inputDefinition.getDefault()) == null) {
// Input required and no value to replace -> error
throw new ToscaException(
String.format("Input <%s> is required and is not present in the user's input list,"
+ " nor has a default value", inputName));
}
});
// Reference:
// http://docs.oasis-open.org/tosca/TOSCA-Simple-Profile-YAML/v1.0/csprd02/TOSCA-Simple-Profile-YAML-v1.0-csprd02.html#TYPE_YAML_STRING
// FIXME Check input type compatibility ?
// templateInput.getValue().getType()
}
@Override
public ArchiveRoot parseTemplate(String toscaTemplate) {
try {
ParsingResult<ArchiveRoot> result = getArchiveRootFromTemplate(toscaTemplate);
Optional<ToscaException> exception = checkParsingErrors(
Optional.ofNullable(result.getContext()).map(ParsingContext::getParsingErrors));
if (exception.isPresent()) {
throw exception.get();
}
return result.getResult();
} catch (ParsingException ex) {
Optional<ToscaException> exception =
checkParsingErrors(Optional.ofNullable(ex.getParsingErrors()));
if (exception.isPresent()) {
throw exception.get();
} else {
throw new ToscaException("Failed to parse template, ex");
}
}
}
@Override
public String updateTemplate(String template) {
ArchiveRoot parsedTempalte = parseTemplate(template);
removeRemovalList(parsedTempalte);
return getTemplateFromTopology(parsedTempalte);
}
private Optional<ToscaException> checkParsingErrors(Optional<List<ParsingError>> errorList) {
return filterNullAndInfoErrorFromParsingError(errorList)
.map(list -> list.stream().map(Object::toString).collect(Collectors.joining("; ")))
.map(ToscaException::new);
}
private Optional<List<ParsingError>> filterNullAndInfoErrorFromParsingError(
Optional<List<ParsingError>> listToFilter) {
return listToFilter.map(list -> list.stream()
.filter(Objects::nonNull)
.filter(error -> !ParsingErrorLevel.INFO.equals(error.getErrorLevel()))
.collect(Collectors.toList())).filter(list -> !list.isEmpty());
}
@Override
public void contextualizeAndReplaceImages(ArchiveRoot parsingResult, CloudProvider cloudProvider,
String cloudServiceId, DeploymentProvider deploymentProvider) {
Map<Boolean, Map<NodeTemplate, ImageData>> contextualizedImages =
contextualizeImages(parsingResult, cloudProvider, cloudServiceId);
Preconditions.checkState(contextualizedImages.get(Boolean.FALSE).isEmpty(),
"Error contextualizing images; images for nodes %s couldn't be contextualized",
contextualizedImages
.get(Boolean.FALSE)
.keySet()
.stream()
.map(NodeTemplate::getName)
.collect(Collectors.toList()));
replaceImage(contextualizedImages.get(Boolean.TRUE), cloudProvider, deploymentProvider);
}
@Override
public Map<NodeTemplate, ImageData> extractImageRequirements(ArchiveRoot parsingResult) {
// Only indigo.Compute nodes are relevant
return getNodesOfType(parsingResult, ToscaConstants.Nodes.COMPUTE).stream().map(node -> {
ImageData imageMetadata = new ImageData();
Optional.ofNullable(node.getCapabilities())
.map(capabilities -> capabilities.get(OS_CAPABILITY_NAME))
.ifPresent(osCapability -> {
// We've got an OS capability -> Check the attributes to find best match for the image
this.<ScalarPropertyValue>getTypedCapabilityPropertyByName(osCapability, "image")
.ifPresent(property -> imageMetadata.setImageName(property.getValue()));
this.<ScalarPropertyValue>getTypedCapabilityPropertyByName(osCapability, "architecture")
.ifPresent(property -> imageMetadata.setArchitecture(property.getValue()));
this.<ScalarPropertyValue>getTypedCapabilityPropertyByName(osCapability, "type")
.ifPresent(property -> imageMetadata.setType(property.getValue()));
this.<ScalarPropertyValue>getTypedCapabilityPropertyByName(osCapability, "distribution")
.ifPresent(property -> imageMetadata.setDistribution(property.getValue()));
this.<ScalarPropertyValue>getTypedCapabilityPropertyByName(osCapability, "version")
.ifPresent(property -> imageMetadata.setVersion(property.getValue()));
});
return new SimpleEntry<>(node, imageMetadata);
}).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
@Override
public Map<Boolean, Map<NodeTemplate, ImageData>> contextualizeImages(ArchiveRoot parsingResult,
CloudProvider cloudProvider, String cloudServiceId) {
try {
return extractImageRequirements(parsingResult).entrySet().stream().map(entry -> {
NodeTemplate node = entry.getKey();
ImageData imageMetadata = entry.getValue();
final Optional<ImageData> image;
// TODO FILTER ON DEPLOYMENT PROVIDER?
if (isImImageUri(imageMetadata.getImageName())) {
image = Optional.of(imageMetadata);
} else {
List<ImageData> images = cloudProvider.getCmdbProviderImages()
.getOrDefault(cloudServiceId, Collections.emptyList());
image = getBestImageForCloudProvider(imageMetadata, images);
}
if (image.isPresent()) {
// Found a good image -> replace the image attribute with the provider-specific ID
LOG.debug(
"Found image match in <{}> for image metadata <{}>"
+ ", provider-specific image id <{}>",
cloudProvider.getId(), imageMetadata, image.get().getImageId());
} else {
// No image match found -> throw error
LOG.debug("Failed to found a match in provider <{}> for image metadata <{}>",
cloudProvider.getId(), imageMetadata);
}
return new SimpleEntry<>(node, image);
}).collect(Collectors.partitioningBy(entry -> entry.getValue().isPresent(),
// do not use the Collectors.toMap() because it doesn't play nice with null values
// https://bugs.openjdk.java.net/browse/JDK-8148463
CommonUtils.toMap(Entry::getKey, entry -> entry.getValue().orElse(null))));
} catch (Exception ex) {
throw new RuntimeException("Failed to contextualize images", ex);
}
}
private void replaceImage(Map<NodeTemplate, ImageData> contextualizedImages,
CloudProvider cloudProvider, DeploymentProvider deploymentProvider) {
contextualizedImages.forEach((node, image) -> {
Map<String, Capability> capabilities =
Optional.ofNullable(node.getCapabilities()).orElseGet(() -> {
node.setCapabilities(new HashMap<>());
return node.getCapabilities();
});
// The node doesn't have an OS Capability -> need to add a dummy one to hold a
// random image for underlying deployment systems
Capability osCapability = capabilities.computeIfAbsent(OS_CAPABILITY_NAME, key -> {
LOG.debug("Generating default OperatingSystem capability for node <{}>", node.getName());
Capability capability = new Capability();
capability.setType("tosca.capabilities.indigo.OperatingSystem");
return capability;
});
String imageId = image.getImageId();
if (deploymentProvider == DeploymentProvider.IM) {
if (isImImageUri(image.getImageName())) {
imageId = image.getImageName();
} else {
imageId = generateImImageUri(cloudProvider, image);
}
}
ScalarPropertyValue scalarPropertyValue = createScalarPropertyValue(imageId);
osCapability.getProperties().put("image", scalarPropertyValue);
if (StringUtils.isNotBlank(image.getUserName())) {
Map<String, Object> credential = new HashMap<>();
ComplexPropertyValue credentialProperty = new ComplexPropertyValue(credential);
credentialProperty.setPrintable(true);
osCapability.getProperties().put("credential", credentialProperty);
scalarPropertyValue = createScalarPropertyValue(image.getUserName());
credential.put("user", scalarPropertyValue);
scalarPropertyValue = createScalarPropertyValue("");
credential.put("token", scalarPropertyValue);
}
});
}
@Deprecated
private boolean isImImageUri(String imageName) {
try {
List<String> schemes = ImmutableList.of("ost", "one", "aws", "azr");
return schemes.contains(URI.create(imageName).getScheme().trim());
} catch (RuntimeException ex) {
return false;
}
}
@Deprecated
private String generateImImageUri(CloudProvider cloudProvider, ImageData image) {
try {
CloudService cs;
if (image.getService() != null
&& cloudProvider.getCmdbProviderServices().get(image.getService()) != null) {
cs = cloudProvider.getCmdbProviderServices().get(image.getService());
} else {
if (cloudProvider.getCmbdProviderServicesByType(Type.COMPUTE).isEmpty()) {
throw new DeploymentException(
"No compute service available fo cloud provider " + cloudProvider.getId());
} else {
cs = cloudProvider.getCmbdProviderServicesByType(Type.COMPUTE).get(0);
}
}
StringBuilder sb = new StringBuilder();
if (cs.isOpenStackComputeProviderService() || cs.isOtcComputeProviderService()) {
sb
.append("ost")
.append("://")
.append(new URL(cs.getData().getEndpoint()).getHost())
.append("/");
} else if (cs.isOpenNebulaComputeProviderService() || cs.isOpenNebulaToscaProviderService()) {
sb
.append("one")
.append("://")
.append(new URL(cs.getData().getEndpoint()).getHost())
.append("/");
} else if (cs.isOcciComputeProviderService()) {
// DO NOTHING ??
} else if (cs.isAwsComputeProviderService()) {
sb
.append("aws")
.append("://");
} else if (cs.isAzureComputeProviderService()) {
sb
.append("azr")
.append("://");
} else {
throw new DeploymentException("Unknown IaaSType of cloud provider " + cloudProvider);
}
sb.append(image.getImageId());
return sb.toString();
} catch (Exception ex) {
LOG.error("Cannot retrieve Compute service host for IM image id generation", ex);
return image.getImageId();
}
}
protected Optional<ImageData> getBestImageForCloudProvider(ImageData imageMetadata,
Collection<ImageData> images) {
// Match image name first (for INDIGO specific use case, if the image cannot be found with the
// specified name it means that a base image + Ansible configuration have to be used -> the
// base image will be chosen with the other filters and image metadata - architecture, type,
// distro, version)
if (imageMetadata.getImageName() != null) {
Optional<ImageData> imageWithName =
findImageWithNameOnCloudProvider(imageMetadata.getImageName(), images);
if (imageWithName.isPresent()) {
LOG.debug("Image <{}> found with name <{}>", imageWithName.get().getImageId(),
imageMetadata.getImageName());
return imageWithName;
} else {
if (imageMetadata.getType() == null && imageMetadata.getArchitecture() == null
&& imageMetadata.getDistribution() == null && imageMetadata.getVersion() == null) {
return Optional.empty();
}
LOG.debug("Image not found with name <{}>, trying with other fields: <{}>",
imageMetadata.getImageName(), imageMetadata);
}
}
for (ImageData image : images) {
// Match or skip image based on each additional optional attribute
if (imageMetadata.getType() != null) {
if (!imageMetadata.getType().equalsIgnoreCase(image.getType())) {
continue;
}
}
if (imageMetadata.getArchitecture() != null) {
if (!imageMetadata.getArchitecture().equalsIgnoreCase(image.getArchitecture())) {
continue;
}
}
if (imageMetadata.getDistribution() != null) {
if (!imageMetadata.getDistribution().equalsIgnoreCase(image.getDistribution())) {
continue;
}
}
if (imageMetadata.getVersion() != null) {
if (!imageMetadata.getVersion().equalsIgnoreCase(image.getVersion())) {
continue;
}
}
LOG.debug("Image <{}> found with fields: <{}>", imageMetadata.getImageId(), imageMetadata);
return Optional.of(image);
}
return Optional.empty();
}
protected Optional<ImageData> findImageWithNameOnCloudProvider(String requiredImageName,
Collection<ImageData> images) {
return images.stream()
.filter(image -> matchImageNameAndTag(requiredImageName, image.getImageName()))
.findFirst();
}
protected boolean matchImageNameAndTag(String requiredImageName, String availableImageName) {
// Extract Docker tag if available
String[] requiredImageNameSplit = requiredImageName.split(":");
String requiredImageBaseName = requiredImageNameSplit[0];
String requiredImageTag =
(requiredImageNameSplit.length > 1 ? requiredImageNameSplit[1] : null);
String[] availableImageNameSplit = availableImageName.split(":");
String availableImageBaseName = availableImageNameSplit[0];
String availableImageTag =
(availableImageNameSplit.length > 1 ? availableImageNameSplit[1] : null);
// Match name
boolean nameMatch = requiredImageBaseName.equals(availableImageBaseName);
// Match tag (if not given the match is true)
boolean tagMatch =
(requiredImageTag != null ? requiredImageTag.equals(availableImageTag) : true);
return nameMatch && tagMatch;
}
private Collection<NodeTemplate> getNodesFromArchiveRoot(ArchiveRoot archiveRoot) {
return Optional.ofNullable(archiveRoot.getTopology())
.map(this::getNodesFromTopology)
.orElseGet(ArrayList::new);
}
private Collection<NodeTemplate> getNodesFromTopology(Topology topology) {
return Optional.ofNullable(topology.getNodeTemplates())
.map(Map::values)
.map(nodes -> nodes.stream().filter(Objects::nonNull).collect(Collectors.toList()))
.orElseGet(ArrayList::new);
}
@Override
public Collection<NodeTemplate> getNodesOfType(ArchiveRoot archiveRoot, String type) {
Preconditions.checkNotNull(type);
return getNodesFromArchiveRoot(archiveRoot).stream()
.filter(node -> isOfToscaType(node, type))
.collect(Collectors.toList());
}
@Override
public boolean isOfToscaType(NodeTemplate node, String nodeType) {
return isSubTypeOf(Preconditions.checkNotNull(node).getType(), nodeType);
}
@Override
public boolean isOfToscaType(Resource resource, String nodeType) {
return isSubTypeOf(Preconditions.checkNotNull(resource).getToscaNodeType(), nodeType);
}
private boolean isSubTypeOf(@Nullable String optionalNodeType, String superNodeType) {
return Optional
.ofNullable(optionalNodeType)
// FIXME: Check inheritance
.filter(nodeType -> CommonUtils
.checkNotNull(nodeType)
.equals(Preconditions.checkNotNull(superNodeType)))
.isPresent();
}
@Override
public boolean isHybridDeployment(ArchiveRoot archiveRoot) {
// check if there is a "hybrid" ScalarPropertyValue with "true" as value
return getNodesOfType(archiveRoot, ToscaConstants.Nodes.ELASTIC_CLUSTER).stream()
.anyMatch(node -> getNodePropertyByName(node, "hybrid")
.filter(ScalarPropertyValue.class::isInstance)
.map(ScalarPropertyValue.class::cast)
.map(ScalarPropertyValue::getValue)
.filter(Boolean::valueOf)
.isPresent());
}
@Override
public void addElasticClusterParameters(ArchiveRoot archiveRoot, String deploymentId,
@Nullable String oauthToken) {
getNodesOfType(archiveRoot, ToscaConstants.Nodes.ELASTIC_CLUSTER).forEach(node -> {
// create properties Map if null
Map<String, AbstractPropertyValue> properties =
Optional.ofNullable(node.getProperties()).orElseGet(() -> {
node.setProperties(new HashMap<>());
return node.getProperties();
});
// Create new property with the deploymentId and set as printable
properties.put("deployment_id", createScalarPropertyValue(deploymentId));
// Create new property with the orchestrator_url and set as printable
properties.put("orchestrator_url",
createScalarPropertyValue(orchestratorProperties.getUrl().toString()));
if (oauthToken != null) {
// Create new property with the iam_access_token and set as printable
properties.put("iam_access_token", createScalarPropertyValue(oauthToken));
Optional<OidcClientProperties> cluesInfo = oauth2tokenService.getCluesInfo(oauthToken);
cluesInfo.ifPresent(info -> {
// Create new property with the iam_clues_client_id and set as printable
properties.put("iam_clues_client_id", createScalarPropertyValue(info.getClientId()));
// Create new property with the iam_clues_client_secret and set as printable
properties.put("iam_clues_client_secret",
createScalarPropertyValue(info.getClientSecret()));
});
}
});
}
private static ScalarPropertyValue createScalarPropertyValue(String value) {
ScalarPropertyValue scalarPropertyValue = new ScalarPropertyValue(value);
scalarPropertyValue.setPrintable(true);
return scalarPropertyValue;
}
public void removeRemovalList(ArchiveRoot archiveRoot) {
getNodesFromArchiveRoot(archiveRoot)
.forEach(this::removeRemovalList);
}
@Override
public void removeRemovalList(NodeTemplate node) {
getNodeCapabilityByName(node, SCALABLE_CAPABILITY_NAME)
.ifPresent(scalable -> CommonUtils
.removeFromOptionalMap(scalable.getProperties(), REMOVAL_LIST_PROPERTY_NAME));
}
private static Optional<Authentication> setAutenticationForToscaImport() {
Authentication oldAuth = SecurityContextHolder.getContext().getAuthentication();
Authentication newAuth = new PreAuthenticatedAuthenticationToken(
Role.ADMIN.name().toLowerCase(), "", AuthorityUtils.createAuthorityList(Role.ADMIN.name()));
SecurityContextHolder.getContext().setAuthentication(newAuth);
return Optional.ofNullable(oldAuth);
}
@Override
public Optional<Capability> getNodeCapabilityByName(NodeTemplate node, String capabilityName) {
return CommonUtils.getFromOptionalMap(node.getCapabilities(), capabilityName);
}
@Override
public Optional<AbstractPropertyValue> getNodePropertyByName(NodeTemplate node,
String propertyName) {
return CommonUtils.getFromOptionalMap(node.getProperties(), propertyName);
}
@Override
public <T extends AbstractPropertyValue> Optional<T> getTypedNodePropertyByName(NodeTemplate node,
String propertyName) {
return CommonUtils.optionalCast(getNodePropertyByName(node, propertyName));
}
@Override
public Optional<AbstractPropertyValue> getCapabilityPropertyByName(Capability capability,
String propertyName) {
return CommonUtils.getFromOptionalMap(capability.getProperties(), propertyName);
}
@Override
public <T extends AbstractPropertyValue> Optional<T> getTypedCapabilityPropertyByName(
Capability capability, String propertyName) {
return CommonUtils.optionalCast(getCapabilityPropertyByName(capability, propertyName));
}
@Override
public Optional<DeploymentArtifact> getNodeArtifactByName(NodeTemplate node,
String artifactName) {
return CommonUtils.getFromOptionalMap(node.getArtifacts(), artifactName);
}
@Override
public Map<String, NodeTemplate> getAssociatedNodesByCapability(Map<String, NodeTemplate> nodes,
NodeTemplate nodeTemplate, String capabilityName) {
return getRelationshipTemplatesByCapabilityName(nodeTemplate.getRelationships(), capabilityName)
.stream().map(relationship -> relationship.getTarget()).collect(
Collectors.toMap(associatedNodeName -> associatedNodeName,
associatedNodeName -> nodes.get(associatedNodeName)));
}
@Override
public List<RelationshipTemplate> getRelationshipTemplatesByCapabilityName(
Map<String, RelationshipTemplate> relationships, String capabilityName) {
List<RelationshipTemplate> relationshipTemplates = new ArrayList<>();
if (relationships == null) {
return relationshipTemplates;
}
for (Map.Entry<String, RelationshipTemplate> relationship : relationships.entrySet()) {
if (relationship.getValue().getTargetedCapabilityName().equals(capabilityName)) {
relationshipTemplates.add(relationship.getValue());
}
}
return relationshipTemplates;
}
@Override
public Optional<Integer> getCount(NodeTemplate nodeTemplate) {
return getNodeCapabilityByName(nodeTemplate, SCALABLE_CAPABILITY_NAME)
.flatMap(capability -> this
.<ScalarPropertyValue>getTypedCapabilityPropertyByName(capability, "count"))
.map(property -> property.getValue())
.map(value -> Integer.parseInt(value));
}
@Override
public boolean isScalable(NodeTemplate nodeTemplate) {
return getCount(nodeTemplate).isPresent();
}
@Override
public Collection<NodeTemplate> getScalableNodes(ArchiveRoot archiveRoot) {
return getNodesFromArchiveRoot(archiveRoot)
.stream()
.filter(this::isScalable)
.collect(Collectors.toList());
}
@Override
public List<String> getRemovalList(NodeTemplate nodeTemplate) {
Optional<ListPropertyValue> listPropertyValue =
getNodeCapabilityByName(nodeTemplate, SCALABLE_CAPABILITY_NAME)
.flatMap(capability -> getTypedCapabilityPropertyByName(capability,
REMOVAL_LIST_PROPERTY_NAME));
List<Object> items =
listPropertyValue.map(property -> property.getValue()).orElseGet(Collections::emptyList);
List<String> removalList = new ArrayList<>();
for (Object item : items) {
if (item instanceof ScalarPropertyValue) {
removalList.add(((ScalarPropertyValue) item).getValue());
} else if (item instanceof String) {
removalList.add((String) item);
} else {
LOG.warn("Skipped unsupported value <{}> in {} of node {}", item,
REMOVAL_LIST_PROPERTY_NAME, nodeTemplate.getName());
}
}
return removalList;
}
@Override
public Map<String, OneData> extractOneDataRequirements(ArchiveRoot archiveRoot,
Map<String, Object> inputs) {
try {
// FIXME: Remove hard-coded input extraction and search on OneData nodes instead
/*
* By now, OneData requirements are in user's input fields: input_onedata_space,
* output_onedata_space, [input_onedata_providers, output_onedata_providers]
*/
Map<String, OneData> result = new HashMap<>();
OneData oneDataInput = null;
if (inputs.get("input_onedata_space") != null) {
oneDataInput = OneData.builder()
.token((String) inputs.get("input_onedata_token"))
.space((String) inputs.get("input_onedata_space"))
.path((String) inputs.get("input_path"))
.providers((String) inputs.get("input_onedata_providers"))
.zone((String) inputs.get("input_onedata_zone"))
.build();
if (oneDataInput.getProviders().isEmpty()) {
oneDataInput.setSmartScheduling(true);
}
result.put("input", oneDataInput);
LOG.debug("Extracted OneData requirement for node <{}>: <{}>", "input", oneDataInput);
}
if (inputs.get("output_onedata_space") != null) {
OneData oneDataOutput = OneData.builder()
.token((String) inputs.get("output_onedata_token"))
.space((String) inputs.get("output_onedata_space"))
.path((String) inputs.get("output_path"))
.providers((String) inputs.get("output_onedata_providers"))
.zone((String) inputs.get("output_onedata_zone"))
.build();
if (oneDataOutput.getProviders().isEmpty()) {
if (oneDataInput != null) {
oneDataOutput.setProviders(oneDataInput.getProviders());
oneDataOutput.setSmartScheduling(oneDataInput.isSmartScheduling());
} else {
oneDataOutput.setSmartScheduling(true);
}
}
result.put("output", oneDataOutput);
LOG.debug("Extracted OneData requirement for node <{}>: <{}>", "output", oneDataOutput);
}
if (result.size() == 0) {
LOG.debug("No OneData requirements to extract");
}
return result;
} catch (Exception ex) {
throw new RuntimeException("Failed to extract OneData requirements: " + ex.getMessage(), ex);
}
}
@Override
public List<PlacementPolicy> extractPlacementPolicies(ArchiveRoot archiveRoot) {
List<PlacementPolicy> placementPolicies = new ArrayList<>();
Optional.ofNullable(archiveRoot.getTopology())
.map(topology -> topology.getPolicies())
.orElseGet(Collections::emptyList)
.forEach(policy -> {
if (policy instanceof alien4cloud.model.topology.PlacementPolicy) {
PlacementPolicy placementPolicy =
PlacementPolicy.fromToscaType((alien4cloud.model.topology.PlacementPolicy) policy);
placementPolicies.add(placementPolicy);
} else {
LOG.warn("Skipping unsupported Policy {}", policy);
}
});
return placementPolicies;
}
@Override
public DirectedMultigraph<NodeTemplate, RelationshipTemplate> buildNodeGraph(
Map<String, NodeTemplate> nodes, boolean checkForCycles) {
DirectedMultigraph<NodeTemplate, RelationshipTemplate> graph =
new DirectedMultigraph<>(RelationshipTemplate.class);
nodes.entrySet().forEach(nodeEntry -> {
NodeTemplate toNode = nodeEntry.getValue();
graph.addVertex(toNode);
Map<String, RelationshipTemplate> relationships =
Optional.ofNullable(toNode.getRelationships()).orElseGet(HashMap::new);
relationships.values().forEach(relationship -> {
NodeTemplate fromNode = nodes.get(relationship.getTarget());
graph.addVertex(fromNode);
graph.addEdge(fromNode, toNode, relationship);
});
});
if (checkForCycles) {
CycleDetector<NodeTemplate, RelationshipTemplate> cycleDetector = new CycleDetector<>(graph);
Set<NodeTemplate> cyclyingNodes = cycleDetector.findCycles();
if (!cyclyingNodes.isEmpty()) {
String message = "Found node depencency loop in TOSCA topology; involved nodes: "
+ Arrays.toString(cyclyingNodes.stream().map(NodeTemplate::getName).toArray());
LOG.error(message);
throw new ValidationException(message);
}
}
return graph;
}
@Override
public <T extends IPropertyType<V>, V> V parseScalarPropertyValue(ScalarPropertyValue value,
Class<T> clazz) {
T propertyParser = BeanUtils.instantiate(clazz);
try {
return propertyParser.parse(value.getValue());
} catch (InvalidPropertyValueException ex) {
throw new ToscaException(String.format("Error parsing scalar value <%s> as <%s>",
value.getValue(), propertyParser.getTypeName()), ex);
}
}
@Override
public <V> List<V> parseListPropertyValue(ListPropertyValue value, Function<Object, V> mapper) {
return Optional.ofNullable(value.getValue())
.orElseGet(Collections::emptyList)
.stream()
.filter(item -> item != null)
.map(mapper)
.collect(Collectors.toList());
}
@Override
public <V> Map<String, V> parseComplexPropertyValue(ComplexPropertyValue value,
Function<Object, V> mapper) {
return Optional.ofNullable(value.getValue())
.orElseGet(Collections::emptyMap)
.entrySet()
.stream()
.filter(entry -> entry.getValue() != null)
.collect(Collectors.toMap(Entry::getKey, mapper.compose(Entry::getValue)));
}
}
| Remove tmp csar files after parsing | src/main/java/it/reply/orchestrator/service/ToscaServiceImpl.java | Remove tmp csar files after parsing | <ide><path>rc/main/java/it/reply/orchestrator/service/ToscaServiceImpl.java
<ide> try (ByteArrayInputStream is = new ByteArrayInputStream(toscaTemplate.getBytes());) {
<ide> Path zipPath = Files.createTempFile("csar", ".zip");
<ide> zip(is, zipPath);
<del> return parser.parse(zipPath);
<add> ParsingResult<ArchiveRoot> result = parser.parse(zipPath);
<add> try {
<add> Files.delete(zipPath);
<add> } catch (Exception ioe) {
<add> LOG.warn("Error deleting tmp csar {} from FS", zipPath, ioe);
<add> }
<add> return result;
<ide> } catch (InvalidArgumentException iae) {
<ide> // FIXME NOTE that InvalidArgumentException should not be thrown by the parse method, but it
<ide> // is... |
|
Java | epl-1.0 | ad0b4e9717a3afcd24b9f8ccbbaf583c4dcbb3b0 | 0 | junit-team/junit-lambda,sbrannen/junit-lambda | /*
* Copyright 2015-2019 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* https://www.eclipse.org/legal/epl-v20.html
*/
package example;
import static org.junit.jupiter.api.condition.JRE.JAVA_10;
import static org.junit.jupiter.api.condition.JRE.JAVA_11;
import static org.junit.jupiter.api.condition.JRE.JAVA_8;
import static org.junit.jupiter.api.condition.JRE.JAVA_9;
import static org.junit.jupiter.api.condition.OS.LINUX;
import static org.junit.jupiter.api.condition.OS.MAC;
import static org.junit.jupiter.api.condition.OS.WINDOWS;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.condition.EnabledOnJre;
import org.junit.jupiter.api.condition.EnabledOnOs;
class ConditionalTestExecutionDemo {
// tag::user_guide_os[]
@Test
@EnabledOnOs(MAC)
void onlyOnMacOs() {
// ...
}
@TestOnMac
void testOnMac() {
// ...
}
@Test
@EnabledOnOs({ LINUX, MAC })
void onLinuxOrMac() {
// ...
}
@Test
@DisabledOnOs(WINDOWS)
void notOnWindows() {
// ...
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Test
@EnabledOnOs(MAC)
@interface TestOnMac {
}
// end::user_guide_os[]
// tag::user_guide_jre[]
@Test
@EnabledOnJre(JAVA_8)
void onlyOnJava8() {
// ...
}
@Test
@EnabledOnJre({ JAVA_9, JAVA_10 })
void onJava9Or10() {
// ...
}
@Test
@EnabledForJreRange(min = JAVA_9, max = JAVA_11)
void fromJava9to11() {
// ...
}
@Test
@EnabledForJreRange(min = JAVA_9)
void fromJava9toCurrentJavaFeatureNumber() {
// ...
}
@Test
@EnabledForJreRange(max = JAVA_11)
void fromJava8To11() {
// ...
}
@Test
@DisabledOnJre(JAVA_9)
void notOnJava9() {
// ...
}
@Test
@DisabledForJreRange(min = JAVA_9, max = JAVA_11)
void notFromJava9to11() {
// ...
}
@Test
@DisabledForJreRange(min = JAVA_9)
void notFromJava9toCurrentJavaFeatureNumber() {
// ...
}
@Test
@DisabledForJreRange(max = JAVA_11)
void notFromJava8to11() {
// ...
}
// end::user_guide_jre[]
// tag::user_guide_system_property[]
@Test
@EnabledIfSystemProperty(named = "os.arch", matches = ".*64.*")
void onlyOn64BitArchitectures() {
// ...
}
@Test
@DisabledIfSystemProperty(named = "ci-server", matches = "true")
void notOnCiServer() {
// ...
}
// end::user_guide_system_property[]
// tag::user_guide_environment_variable[]
@Test
@EnabledIfEnvironmentVariable(named = "ENV", matches = "staging-server")
void onlyOnStagingServer() {
// ...
}
@Test
@DisabledIfEnvironmentVariable(named = "ENV", matches = ".*development.*")
void notOnDeveloperWorkstation() {
// ...
}
// end::user_guide_environment_variable[]
}
| documentation/src/test/java/example/ConditionalTestExecutionDemo.java | /*
* Copyright 2015-2019 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* https://www.eclipse.org/legal/epl-v20.html
*/
package example;
import static org.junit.jupiter.api.condition.JRE.JAVA_10;
import static org.junit.jupiter.api.condition.JRE.JAVA_11;
import static org.junit.jupiter.api.condition.JRE.JAVA_8;
import static org.junit.jupiter.api.condition.JRE.JAVA_9;
import static org.junit.jupiter.api.condition.OS.LINUX;
import static org.junit.jupiter.api.condition.OS.MAC;
import static org.junit.jupiter.api.condition.OS.WINDOWS;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.condition.EnabledOnJre;
import org.junit.jupiter.api.condition.EnabledOnOs;
class ConditionalTestExecutionDemo {
// tag::user_guide_os[]
@Test
@EnabledOnOs(MAC)
void onlyOnMacOs() {
// ...
}
@TestOnMac
void testOnMac() {
// ...
}
@Test
@EnabledOnOs({ LINUX, MAC })
void onLinuxOrMac() {
// ...
}
@Test
@DisabledOnOs(WINDOWS)
void notOnWindows() {
// ...
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Test
@EnabledOnOs(MAC)
@interface TestOnMac {
}
// end::user_guide_os[]
// tag::user_guide_jre[]
@Test
@EnabledOnJre(JAVA_8)
void onlyOnJava8() {
// ...
}
@Test
@EnabledOnJre({ JAVA_9, JAVA_10 })
void onJava9Or10() {
// ...
}
@Test
@EnabledForJreRange(min = JAVA_9, max = JAVA_11)
void fromJava9to11() {
// ...
}
@Test
@EnabledForJreRange(min = JAVA_9)
void fromJava9toCurrentJavaFeatureNumber() {
// ...
}
@Test
@EnabledForJreRange(max = JAVA_11)
void fromJava8To11() {
// ...
}
@Test
@DisabledOnJre(JAVA_9)
void notOnJava9() {
// ...
}
@Test
@DisabledForJreRange(min = JAVA_9, max = JAVA_11)
void notFromJava9to11() {
// ...
}
@Test
@DisabledForJreRange(min = JAVA_9)
void notFromJava9toCurrentJavaFeatureNumber()() {
// ...
}
@Test
@DisabledForJreRange(max = JAVA_11)
void notFromJava8to11() {
// ...
}
// end::user_guide_jre[]
// tag::user_guide_system_property[]
@Test
@EnabledIfSystemProperty(named = "os.arch", matches = ".*64.*")
void onlyOn64BitArchitectures() {
// ...
}
@Test
@DisabledIfSystemProperty(named = "ci-server", matches = "true")
void notOnCiServer() {
// ...
}
// end::user_guide_system_property[]
// tag::user_guide_environment_variable[]
@Test
@EnabledIfEnvironmentVariable(named = "ENV", matches = "staging-server")
void onlyOnStagingServer() {
// ...
}
@Test
@DisabledIfEnvironmentVariable(named = "ENV", matches = ".*development.*")
void notOnDeveloperWorkstation() {
// ...
}
// end::user_guide_environment_variable[]
}
| Fix typo | documentation/src/test/java/example/ConditionalTestExecutionDemo.java | Fix typo | <ide><path>ocumentation/src/test/java/example/ConditionalTestExecutionDemo.java
<ide>
<ide> @Test
<ide> @DisabledForJreRange(min = JAVA_9)
<del> void notFromJava9toCurrentJavaFeatureNumber()() {
<add> void notFromJava9toCurrentJavaFeatureNumber() {
<ide> // ...
<ide> }
<ide> |
|
Java | bsd-3-clause | error: pathspec 'src/org/team2168/utils/Util.java' did not match any file(s) known to git
| 4704b9efc079669e0fb743e43602286e66f82212 | 1 | Team2168/FRC2014_Main_Robot | package org.team2168.utils;
import java.util.Vector;
/**
* Contains basic functions that are used often.
*
* Initial revision from 254's 2013 robot code:
* https://github.com/Team254/FRC-2013/blob/master/src/com/team254/lib/util/Util.java
*
* @author [email protected] (Richard Lin)
* @author [email protected] (Brandon Gonzalez)
*/
public class Util {
// Prevent this class from being instantiated.
private Util() {
}
/**
* Limits the given input to the given magnitude.
*/
public static double limit(double v, double limit) {
return (Math.abs(v) < limit) ? v : limit * (v < 0 ? -1 : 1);
}
/**
* Returns the array of substrings obtained by dividing the given input string at each occurrence
* of the given delimiter.
*/
public static String[] split(String input, String delimiter) {
Vector node = new Vector();
int index = input.indexOf(delimiter);
while (index >= 0) {
node.addElement(input.substring(0, index));
input = input.substring(index + delimiter.length());
index = input.indexOf(delimiter);
}
node.addElement(input);
String[] retString = new String[node.size()];
for (int i = 0; i < node.size(); ++i) {
retString[i] = (String) node.elementAt(i);
}
return retString;
}
}
| src/org/team2168/utils/Util.java | Create Util.java
Initial revision. | src/org/team2168/utils/Util.java | Create Util.java | <ide><path>rc/org/team2168/utils/Util.java
<add>package org.team2168.utils;
<add>
<add>import java.util.Vector;
<add>
<add>/**
<add>* Contains basic functions that are used often.
<add>*
<add>* Initial revision from 254's 2013 robot code:
<add>* https://github.com/Team254/FRC-2013/blob/master/src/com/team254/lib/util/Util.java
<add>*
<add>* @author [email protected] (Richard Lin)
<add>* @author [email protected] (Brandon Gonzalez)
<add>*/
<add>public class Util {
<add> // Prevent this class from being instantiated.
<add> private Util() {
<add> }
<add>
<add> /**
<add>* Limits the given input to the given magnitude.
<add>*/
<add> public static double limit(double v, double limit) {
<add> return (Math.abs(v) < limit) ? v : limit * (v < 0 ? -1 : 1);
<add> }
<add>
<add> /**
<add>* Returns the array of substrings obtained by dividing the given input string at each occurrence
<add>* of the given delimiter.
<add>*/
<add> public static String[] split(String input, String delimiter) {
<add> Vector node = new Vector();
<add> int index = input.indexOf(delimiter);
<add> while (index >= 0) {
<add> node.addElement(input.substring(0, index));
<add> input = input.substring(index + delimiter.length());
<add> index = input.indexOf(delimiter);
<add> }
<add> node.addElement(input);
<add>
<add> String[] retString = new String[node.size()];
<add> for (int i = 0; i < node.size(); ++i) {
<add> retString[i] = (String) node.elementAt(i);
<add> }
<add>
<add> return retString;
<add> }
<add>} |
|
Java | apache-2.0 | 882857fa9cc058c880db3e55061e2409cf8370b3 | 0 | sebi-hgdata/camel,joakibj/camel,koscejev/camel,apache/camel,isavin/camel,bdecoste/camel,arnaud-deprez/camel,prashant2402/camel,cunningt/camel,lasombra/camel,mnki/camel,duro1/camel,JYBESSON/camel,dmvolod/camel,chirino/camel,mzapletal/camel,jpav/camel,YoshikiHigo/camel,FingolfinTEK/camel,acartapanis/camel,iweiss/camel,prashant2402/camel,CodeSmell/camel,pplatek/camel,gilfernandes/camel,stravag/camel,snadakuduru/camel,punkhorn/camel-upstream,lowwool/camel,apache/camel,grange74/camel,rmarting/camel,apache/camel,davidwilliams1978/camel,mohanaraosv/camel,alvinkwekel/camel,jollygeorge/camel,NetNow/camel,tdiesler/camel,edigrid/camel,zregvart/camel,gyc567/camel,mnki/camel,acartapanis/camel,curso007/camel,isavin/camel,borcsokj/camel,ramonmaruko/camel,brreitme/camel,tadayosi/camel,adessaigne/camel,manuelh9r/camel,jmandawg/camel,bgaudaen/camel,nikhilvibhav/camel,joakibj/camel,ekprayas/camel,duro1/camel,logzio/camel,manuelh9r/camel,kevinearls/camel,pkletsko/camel,jarst/camel,mnki/camel,NetNow/camel,Thopap/camel,dsimansk/camel,ssharma/camel,hqstevenson/camel,nikhilvibhav/camel,grgrzybek/camel,ramonmaruko/camel,ramonmaruko/camel,w4tson/camel,dpocock/camel,duro1/camel,satishgummadelli/camel,rmarting/camel,akhettar/camel,skinzer/camel,mohanaraosv/camel,ekprayas/camel,tarilabs/camel,johnpoth/camel,nboukhed/camel,gilfernandes/camel,mohanaraosv/camel,erwelch/camel,kevinearls/camel,johnpoth/camel,maschmid/camel,haku/camel,oscerd/camel,ekprayas/camel,jonmcewen/camel,yury-vashchyla/camel,bgaudaen/camel,jonmcewen/camel,mike-kukla/camel,anton-k11/camel,apache/camel,dvankleef/camel,coderczp/camel,snurmine/camel,erwelch/camel,satishgummadelli/camel,scranton/camel,sabre1041/camel,davidwilliams1978/camel,jlpedrosa/camel,MohammedHammam/camel,mzapletal/camel,skinzer/camel,mike-kukla/camel,scranton/camel,tarilabs/camel,akhettar/camel,woj-i/camel,mcollovati/camel,chanakaudaya/camel,tadayosi/camel,royopa/camel,manuelh9r/camel,trohovsky/camel,dvankleef/camel,hqstevenson/camel,jmandawg/camel,woj-i/camel,anoordover/camel,sebi-hgdata/camel,yuruki/camel,w4tson/camel,tdiesler/camel,arnaud-deprez/camel,mike-kukla/camel,noelo/camel,rparree/camel,onders86/camel,Thopap/camel,davidkarlsen/camel,lasombra/camel,jarst/camel,YoshikiHigo/camel,partis/camel,allancth/camel,jmandawg/camel,snurmine/camel,davidwilliams1978/camel,tarilabs/camel,adessaigne/camel,gnodet/camel,ssharma/camel,anoordover/camel,CandleCandle/camel,YMartsynkevych/camel,pkletsko/camel,nikhilvibhav/camel,dpocock/camel,dpocock/camel,gyc567/camel,NickCis/camel,erwelch/camel,edigrid/camel,partis/camel,lburgazzoli/apache-camel,tdiesler/camel,yogamaha/camel,RohanHart/camel,stravag/camel,skinzer/camel,anton-k11/camel,logzio/camel,tarilabs/camel,tadayosi/camel,bgaudaen/camel,Fabryprog/camel,ge0ffrey/camel,isavin/camel,atoulme/camel,RohanHart/camel,YMartsynkevych/camel,sabre1041/camel,sirlatrom/camel,royopa/camel,hqstevenson/camel,haku/camel,NickCis/camel,sebi-hgdata/camel,atoulme/camel,gautric/camel,lburgazzoli/camel,pplatek/camel,CandleCandle/camel,sirlatrom/camel,adessaigne/camel,dkhanolkar/camel,apache/camel,isururanawaka/camel,askannon/camel,sabre1041/camel,yury-vashchyla/camel,yuruki/camel,YoshikiHigo/camel,MohammedHammam/camel,prashant2402/camel,NickCis/camel,ullgren/camel,gilfernandes/camel,veithen/camel,zregvart/camel,yury-vashchyla/camel,allancth/camel,gnodet/camel,jameszkw/camel,allancth/camel,jollygeorge/camel,davidwilliams1978/camel,dsimansk/camel,mcollovati/camel,gautric/camel,Fabryprog/camel,zregvart/camel,prashant2402/camel,arnaud-deprez/camel,YMartsynkevych/camel,manuelh9r/camel,bhaveshdt/camel,jlpedrosa/camel,koscejev/camel,tlehoux/camel,gautric/camel,anoordover/camel,oalles/camel,ssharma/camel,tlehoux/camel,iweiss/camel,borcsokj/camel,yogamaha/camel,jpav/camel,arnaud-deprez/camel,snadakuduru/camel,haku/camel,logzio/camel,chirino/camel,jamesnetherton/camel,mgyongyosi/camel,objectiser/camel,dpocock/camel,neoramon/camel,jamesnetherton/camel,akhettar/camel,pmoerenhout/camel,tlehoux/camel,hqstevenson/camel,brreitme/camel,pmoerenhout/camel,snadakuduru/camel,pax95/camel,allancth/camel,CandleCandle/camel,rparree/camel,maschmid/camel,atoulme/camel,onders86/camel,ullgren/camel,davidwilliams1978/camel,isururanawaka/camel,koscejev/camel,dkhanolkar/camel,FingolfinTEK/camel,eformat/camel,drsquidop/camel,rmarting/camel,NetNow/camel,dkhanolkar/camel,CandleCandle/camel,bdecoste/camel,RohanHart/camel,cunningt/camel,sebi-hgdata/camel,nikvaessen/camel,jamesnetherton/camel,johnpoth/camel,pplatek/camel,yury-vashchyla/camel,YoshikiHigo/camel,alvinkwekel/camel,CodeSmell/camel,scranton/camel,mzapletal/camel,jollygeorge/camel,tkopczynski/camel,dpocock/camel,tkopczynski/camel,lburgazzoli/apache-camel,mzapletal/camel,logzio/camel,satishgummadelli/camel,tkopczynski/camel,oscerd/camel,snurmine/camel,pmoerenhout/camel,dsimansk/camel,ge0ffrey/camel,rmarting/camel,acartapanis/camel,nicolaferraro/camel,jameszkw/camel,lburgazzoli/apache-camel,lowwool/camel,maschmid/camel,CandleCandle/camel,pkletsko/camel,onders86/camel,logzio/camel,onders86/camel,MohammedHammam/camel,iweiss/camel,yuruki/camel,sabre1041/camel,josefkarasek/camel,mgyongyosi/camel,rparree/camel,erwelch/camel,CodeSmell/camel,jamesnetherton/camel,jlpedrosa/camel,veithen/camel,tdiesler/camel,mcollovati/camel,prashant2402/camel,coderczp/camel,yogamaha/camel,MohammedHammam/camel,MrCoder/camel,nboukhed/camel,bdecoste/camel,scranton/camel,askannon/camel,jonmcewen/camel,ge0ffrey/camel,jpav/camel,duro1/camel,davidwilliams1978/camel,sverkera/camel,tdiesler/camel,qst-jdc-labs/camel,dvankleef/camel,w4tson/camel,logzio/camel,mcollovati/camel,lburgazzoli/camel,DariusX/camel,mnki/camel,snurmine/camel,hqstevenson/camel,mohanaraosv/camel,anton-k11/camel,jkorab/camel,eformat/camel,gilfernandes/camel,isavin/camel,rparree/camel,curso007/camel,davidkarlsen/camel,nikvaessen/camel,onders86/camel,jlpedrosa/camel,satishgummadelli/camel,mnki/camel,ekprayas/camel,qst-jdc-labs/camel,pkletsko/camel,kevinearls/camel,drsquidop/camel,askannon/camel,dvankleef/camel,grange74/camel,satishgummadelli/camel,ge0ffrey/camel,anton-k11/camel,neoramon/camel,coderczp/camel,neoramon/camel,lowwool/camel,nboukhed/camel,JYBESSON/camel,yuruki/camel,ssharma/camel,gautric/camel,yogamaha/camel,veithen/camel,eformat/camel,bfitzpat/camel,allancth/camel,isavin/camel,chanakaudaya/camel,josefkarasek/camel,partis/camel,JYBESSON/camel,jonmcewen/camel,Thopap/camel,dmvolod/camel,snadakuduru/camel,ekprayas/camel,askannon/camel,manuelh9r/camel,jollygeorge/camel,lburgazzoli/camel,jarst/camel,sebi-hgdata/camel,pkletsko/camel,snurmine/camel,qst-jdc-labs/camel,pax95/camel,partis/camel,coderczp/camel,davidkarlsen/camel,stalet/camel,isururanawaka/camel,lasombra/camel,jollygeorge/camel,mike-kukla/camel,stravag/camel,nboukhed/camel,apache/camel,adessaigne/camel,jkorab/camel,royopa/camel,punkhorn/camel-upstream,royopa/camel,driseley/camel,scranton/camel,jonmcewen/camel,tkopczynski/camel,qst-jdc-labs/camel,johnpoth/camel,veithen/camel,chanakaudaya/camel,satishgummadelli/camel,josefkarasek/camel,salikjan/camel,JYBESSON/camel,nboukhed/camel,salikjan/camel,grgrzybek/camel,stravag/camel,mzapletal/camel,coderczp/camel,grgrzybek/camel,christophd/camel,neoramon/camel,yogamaha/camel,noelo/camel,erwelch/camel,isururanawaka/camel,oscerd/camel,christophd/camel,oalles/camel,woj-i/camel,ekprayas/camel,NetNow/camel,koscejev/camel,partis/camel,oalles/camel,pmoerenhout/camel,coderczp/camel,pkletsko/camel,qst-jdc-labs/camel,dvankleef/camel,bgaudaen/camel,kevinearls/camel,curso007/camel,iweiss/camel,NickCis/camel,dsimansk/camel,bfitzpat/camel,bhaveshdt/camel,dmvolod/camel,NetNow/camel,christophd/camel,mike-kukla/camel,noelo/camel,objectiser/camel,veithen/camel,mohanaraosv/camel,grange74/camel,yogamaha/camel,pax95/camel,woj-i/camel,bfitzpat/camel,bdecoste/camel,dkhanolkar/camel,oscerd/camel,jarst/camel,jmandawg/camel,rmarting/camel,anoordover/camel,jonmcewen/camel,josefkarasek/camel,maschmid/camel,jollygeorge/camel,askannon/camel,bdecoste/camel,driseley/camel,christophd/camel,joakibj/camel,prashant2402/camel,trohovsky/camel,drsquidop/camel,borcsokj/camel,lowwool/camel,lburgazzoli/camel,nboukhed/camel,Fabryprog/camel,FingolfinTEK/camel,tadayosi/camel,YoshikiHigo/camel,haku/camel,anoordover/camel,eformat/camel,bhaveshdt/camel,JYBESSON/camel,jameszkw/camel,noelo/camel,driseley/camel,lburgazzoli/camel,jarst/camel,jamesnetherton/camel,joakibj/camel,lburgazzoli/apache-camel,nicolaferraro/camel,sverkera/camel,grgrzybek/camel,pax95/camel,atoulme/camel,driseley/camel,FingolfinTEK/camel,duro1/camel,gilfernandes/camel,w4tson/camel,isururanawaka/camel,sirlatrom/camel,christophd/camel,driseley/camel,sabre1041/camel,cunningt/camel,arnaud-deprez/camel,maschmid/camel,sebi-hgdata/camel,rparree/camel,MrCoder/camel,dvankleef/camel,nicolaferraro/camel,dmvolod/camel,noelo/camel,grange74/camel,nikvaessen/camel,acartapanis/camel,gautric/camel,jameszkw/camel,nikhilvibhav/camel,kevinearls/camel,edigrid/camel,jpav/camel,stalet/camel,gilfernandes/camel,mgyongyosi/camel,ge0ffrey/camel,CandleCandle/camel,bgaudaen/camel,sirlatrom/camel,jarst/camel,gyc567/camel,w4tson/camel,haku/camel,woj-i/camel,gyc567/camel,sirlatrom/camel,skinzer/camel,gyc567/camel,trohovsky/camel,grgrzybek/camel,snadakuduru/camel,logzio/camel,neoramon/camel,pax95/camel,tlehoux/camel,jmandawg/camel,jmandawg/camel,bhaveshdt/camel,woj-i/camel,mgyongyosi/camel,pplatek/camel,hqstevenson/camel,mzapletal/camel,mohanaraosv/camel,acartapanis/camel,nikvaessen/camel,qst-jdc-labs/camel,dpocock/camel,MohammedHammam/camel,Thopap/camel,chirino/camel,tarilabs/camel,oscerd/camel,curso007/camel,yury-vashchyla/camel,skinzer/camel,atoulme/camel,jamesnetherton/camel,stalet/camel,borcsokj/camel,lasombra/camel,mgyongyosi/camel,eformat/camel,acartapanis/camel,johnpoth/camel,nicolaferraro/camel,sverkera/camel,ssharma/camel,mgyongyosi/camel,sirlatrom/camel,pplatek/camel,oscerd/camel,dkhanolkar/camel,grgrzybek/camel,tarilabs/camel,rparree/camel,FingolfinTEK/camel,akhettar/camel,christophd/camel,grange74/camel,stalet/camel,nikvaessen/camel,drsquidop/camel,trohovsky/camel,cunningt/camel,ullgren/camel,DariusX/camel,DariusX/camel,anton-k11/camel,ge0ffrey/camel,cunningt/camel,lowwool/camel,chanakaudaya/camel,CodeSmell/camel,chirino/camel,tkopczynski/camel,gyc567/camel,punkhorn/camel-upstream,royopa/camel,ramonmaruko/camel,pmoerenhout/camel,Fabryprog/camel,dmvolod/camel,koscejev/camel,noelo/camel,jlpedrosa/camel,askannon/camel,drsquidop/camel,MohammedHammam/camel,dkhanolkar/camel,pmoerenhout/camel,lburgazzoli/apache-camel,anoordover/camel,jkorab/camel,anton-k11/camel,veithen/camel,joakibj/camel,josefkarasek/camel,lasombra/camel,mnki/camel,gnodet/camel,objectiser/camel,MrCoder/camel,jkorab/camel,YMartsynkevych/camel,w4tson/camel,lburgazzoli/apache-camel,edigrid/camel,tlehoux/camel,YMartsynkevych/camel,scranton/camel,isavin/camel,tdiesler/camel,driseley/camel,bgaudaen/camel,stalet/camel,jameszkw/camel,chanakaudaya/camel,gnodet/camel,curso007/camel,josefkarasek/camel,snadakuduru/camel,akhettar/camel,arnaud-deprez/camel,jameszkw/camel,joakibj/camel,alvinkwekel/camel,RohanHart/camel,oalles/camel,bfitzpat/camel,MrCoder/camel,dmvolod/camel,bhaveshdt/camel,koscejev/camel,dsimansk/camel,duro1/camel,chirino/camel,isururanawaka/camel,lasombra/camel,onders86/camel,haku/camel,yury-vashchyla/camel,borcsokj/camel,adessaigne/camel,MrCoder/camel,Thopap/camel,punkhorn/camel-upstream,brreitme/camel,brreitme/camel,curso007/camel,bhaveshdt/camel,chanakaudaya/camel,zregvart/camel,sverkera/camel,mike-kukla/camel,DariusX/camel,oalles/camel,jkorab/camel,ssharma/camel,ramonmaruko/camel,drsquidop/camel,maschmid/camel,trohovsky/camel,jkorab/camel,yuruki/camel,cunningt/camel,skinzer/camel,trohovsky/camel,sverkera/camel,iweiss/camel,oalles/camel,dsimansk/camel,ullgren/camel,atoulme/camel,tkopczynski/camel,pax95/camel,stalet/camel,pplatek/camel,tadayosi/camel,iweiss/camel,JYBESSON/camel,eformat/camel,erwelch/camel,jpav/camel,yuruki/camel,royopa/camel,gautric/camel,NetNow/camel,brreitme/camel,stravag/camel,sabre1041/camel,bfitzpat/camel,neoramon/camel,lowwool/camel,kevinearls/camel,gnodet/camel,objectiser/camel,allancth/camel,davidkarlsen/camel,partis/camel,edigrid/camel,brreitme/camel,pplatek/camel,nikvaessen/camel,bdecoste/camel,NickCis/camel,jpav/camel,johnpoth/camel,stravag/camel,RohanHart/camel,bfitzpat/camel,tadayosi/camel,chirino/camel,adessaigne/camel,YMartsynkevych/camel,borcsokj/camel,lburgazzoli/camel,akhettar/camel,jlpedrosa/camel,tlehoux/camel,manuelh9r/camel,sverkera/camel,NickCis/camel,MrCoder/camel,RohanHart/camel,ramonmaruko/camel,FingolfinTEK/camel,YoshikiHigo/camel,edigrid/camel,alvinkwekel/camel,snurmine/camel,grange74/camel,rmarting/camel,Thopap/camel | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.impl;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.naming.Context;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Endpoint;
import org.apache.camel.ErrorHandlerFactory;
import org.apache.camel.FailedToStartRouteException;
import org.apache.camel.IsSingleton;
import org.apache.camel.MultipleConsumersSupport;
import org.apache.camel.NoFactoryAvailableException;
import org.apache.camel.NoSuchEndpointException;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.ResolveEndpointFailedException;
import org.apache.camel.Route;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.Service;
import org.apache.camel.ServiceStatus;
import org.apache.camel.ShutdownRoute;
import org.apache.camel.ShutdownRunningTask;
import org.apache.camel.StartupListener;
import org.apache.camel.StatefulService;
import org.apache.camel.SuspendableService;
import org.apache.camel.TypeConverter;
import org.apache.camel.VetoCamelContextStartException;
import org.apache.camel.builder.ErrorHandlerBuilder;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.impl.converter.BaseTypeConverterRegistry;
import org.apache.camel.impl.converter.DefaultTypeConverter;
import org.apache.camel.impl.converter.LazyLoadingTypeConverter;
import org.apache.camel.management.DefaultManagementMBeanAssembler;
import org.apache.camel.management.DefaultManagementStrategy;
import org.apache.camel.management.JmxSystemPropertyKeys;
import org.apache.camel.management.ManagementStrategyFactory;
import org.apache.camel.model.Constants;
import org.apache.camel.model.DataFormatDefinition;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.model.RouteDefinitionHelper;
import org.apache.camel.model.RoutesDefinition;
import org.apache.camel.model.rest.RestDefinition;
import org.apache.camel.processor.interceptor.BacklogDebugger;
import org.apache.camel.processor.interceptor.BacklogTracer;
import org.apache.camel.processor.interceptor.Debug;
import org.apache.camel.processor.interceptor.Delayer;
import org.apache.camel.processor.interceptor.HandleFault;
import org.apache.camel.processor.interceptor.StreamCaching;
import org.apache.camel.processor.interceptor.Tracer;
import org.apache.camel.spi.CamelContextNameStrategy;
import org.apache.camel.spi.ClassResolver;
import org.apache.camel.spi.ComponentResolver;
import org.apache.camel.spi.Container;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.DataFormatResolver;
import org.apache.camel.spi.Debugger;
import org.apache.camel.spi.EndpointStrategy;
import org.apache.camel.spi.EventNotifier;
import org.apache.camel.spi.ExecutorServiceManager;
import org.apache.camel.spi.FactoryFinder;
import org.apache.camel.spi.FactoryFinderResolver;
import org.apache.camel.spi.InflightRepository;
import org.apache.camel.spi.Injector;
import org.apache.camel.spi.InterceptStrategy;
import org.apache.camel.spi.Language;
import org.apache.camel.spi.LanguageResolver;
import org.apache.camel.spi.LifecycleStrategy;
import org.apache.camel.spi.ManagementMBeanAssembler;
import org.apache.camel.spi.ManagementNameStrategy;
import org.apache.camel.spi.ManagementStrategy;
import org.apache.camel.spi.NodeIdFactory;
import org.apache.camel.spi.PackageScanClassResolver;
import org.apache.camel.spi.ProcessorFactory;
import org.apache.camel.spi.Registry;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.RestRegistry;
import org.apache.camel.spi.RouteContext;
import org.apache.camel.spi.RoutePolicyFactory;
import org.apache.camel.spi.RouteStartupOrder;
import org.apache.camel.spi.RuntimeEndpointRegistry;
import org.apache.camel.spi.ServicePool;
import org.apache.camel.spi.ShutdownStrategy;
import org.apache.camel.spi.StreamCachingStrategy;
import org.apache.camel.spi.TypeConverterRegistry;
import org.apache.camel.spi.UnitOfWorkFactory;
import org.apache.camel.spi.UuidGenerator;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.util.CamelContextHelper;
import org.apache.camel.util.EndpointHelper;
import org.apache.camel.util.EventHelper;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.LoadPropertiesException;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ServiceHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.URISupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents the context used to configure routes and the policies to use.
*
* @version
*/
@SuppressWarnings("deprecation")
public class DefaultCamelContext extends ServiceSupport implements ModelCamelContext, SuspendableService {
private final Logger log = LoggerFactory.getLogger(getClass());
private JAXBContext jaxbContext;
private CamelContextNameStrategy nameStrategy = new DefaultCamelContextNameStrategy();
private ManagementNameStrategy managementNameStrategy = new DefaultManagementNameStrategy(this);
private String managementName;
private ClassLoader applicationContextClassLoader;
private Map<EndpointKey, Endpoint> endpoints;
private final AtomicInteger endpointKeyCounter = new AtomicInteger();
private final List<EndpointStrategy> endpointStrategies = new ArrayList<EndpointStrategy>();
private final Map<String, Component> components = new HashMap<String, Component>();
private final Set<Route> routes = new LinkedHashSet<Route>();
private final List<Service> servicesToClose = new CopyOnWriteArrayList<Service>();
private final Set<StartupListener> startupListeners = new LinkedHashSet<StartupListener>();
private TypeConverter typeConverter;
private TypeConverterRegistry typeConverterRegistry;
private Injector injector;
private ComponentResolver componentResolver;
private boolean autoCreateComponents = true;
private LanguageResolver languageResolver = new DefaultLanguageResolver();
private final Map<String, Language> languages = new HashMap<String, Language>();
private Registry registry;
private List<LifecycleStrategy> lifecycleStrategies = new CopyOnWriteArrayList<LifecycleStrategy>();
private ManagementStrategy managementStrategy;
private ManagementMBeanAssembler managementMBeanAssembler;
private final List<RouteDefinition> routeDefinitions = new ArrayList<RouteDefinition>();
private final List<RestDefinition> restDefinitions = new ArrayList<RestDefinition>();
private RestConfiguration restConfiguration = new RestConfiguration();
private RestRegistry restRegistry = new DefaultRestRegistry();
private List<InterceptStrategy> interceptStrategies = new ArrayList<InterceptStrategy>();
private List<RoutePolicyFactory> routePolicyFactories = new ArrayList<RoutePolicyFactory>();
// special flags to control the first startup which can are special
private volatile boolean firstStartDone;
private volatile boolean doNotStartRoutesOnFirstStart;
private final ThreadLocal<Boolean> isStartingRoutes = new ThreadLocal<Boolean>();
private final ThreadLocal<Boolean> isSetupRoutes = new ThreadLocal<Boolean>();
private Boolean autoStartup = Boolean.TRUE;
private Boolean trace = Boolean.FALSE;
private Boolean messageHistory = Boolean.TRUE;
private Boolean streamCache = Boolean.FALSE;
private Boolean handleFault = Boolean.FALSE;
private Boolean disableJMX = Boolean.FALSE;
private Boolean lazyLoadTypeConverters = Boolean.FALSE;
private Boolean typeConverterStatisticsEnabled = Boolean.FALSE;
private Boolean useMDCLogging = Boolean.FALSE;
private Boolean useBreadcrumb = Boolean.TRUE;
private Boolean allowUseOriginalMessage = Boolean.TRUE;
private Long delay;
private ErrorHandlerFactory errorHandlerBuilder;
private final Object errorHandlerExecutorServiceLock = new Object();
private ScheduledExecutorService errorHandlerExecutorService;
private Map<String, DataFormatDefinition> dataFormats = new HashMap<String, DataFormatDefinition>();
private DataFormatResolver dataFormatResolver = new DefaultDataFormatResolver();
private Map<String, String> properties = new HashMap<String, String>();
private FactoryFinderResolver factoryFinderResolver = new DefaultFactoryFinderResolver();
private FactoryFinder defaultFactoryFinder;
private PropertiesComponent propertiesComponent;
private StreamCachingStrategy streamCachingStrategy;
private final Map<String, FactoryFinder> factories = new HashMap<String, FactoryFinder>();
private final Map<String, RouteService> routeServices = new LinkedHashMap<String, RouteService>();
private final Map<String, RouteService> suspendedRouteServices = new LinkedHashMap<String, RouteService>();
private ClassResolver classResolver = new DefaultClassResolver();
private PackageScanClassResolver packageScanClassResolver;
// we use a capacity of 100 per endpoint, so for the same endpoint we have at most 100 producers in the pool
// so if we have 6 endpoints in the pool, we can have 6 x 100 producers in total
private ServicePool<Endpoint, Producer> producerServicePool = new SharedProducerServicePool(100);
private NodeIdFactory nodeIdFactory = new DefaultNodeIdFactory();
private ProcessorFactory processorFactory;
private InterceptStrategy defaultTracer;
private InterceptStrategy defaultBacklogTracer;
private InterceptStrategy defaultBacklogDebugger;
private InflightRepository inflightRepository = new DefaultInflightRepository();
private RuntimeEndpointRegistry runtimeEndpointRegistry = new DefaultRuntimeEndpointRegistry();
private final List<RouteStartupOrder> routeStartupOrder = new ArrayList<RouteStartupOrder>();
// start auto assigning route ids using numbering 1000 and upwards
private int defaultRouteStartupOrder = 1000;
private ShutdownStrategy shutdownStrategy = new DefaultShutdownStrategy(this);
private ShutdownRoute shutdownRoute = ShutdownRoute.Default;
private ShutdownRunningTask shutdownRunningTask = ShutdownRunningTask.CompleteCurrentTaskOnly;
private ExecutorServiceManager executorServiceManager;
private Debugger debugger;
private UuidGenerator uuidGenerator = createDefaultUuidGenerator();
private UnitOfWorkFactory unitOfWorkFactory = new DefaultUnitOfWorkFactory();
private final StopWatch stopWatch = new StopWatch(false);
private Date startDate;
/**
* Creates the {@link CamelContext} using {@link JndiRegistry} as registry,
* but will silently fallback and use {@link SimpleRegistry} if JNDI cannot be used.
* <p/>
* Use one of the other constructors to force use an explicit registry / JNDI.
*/
public DefaultCamelContext() {
this.executorServiceManager = new DefaultExecutorServiceManager(this);
// create endpoint registry at first since end users may access endpoints before CamelContext is started
this.endpoints = new EndpointRegistry(this);
// use WebSphere specific resolver if running on WebSphere
if (WebSpherePackageScanClassResolver.isWebSphereClassLoader(this.getClass().getClassLoader())) {
log.info("Using WebSphere specific PackageScanClassResolver");
packageScanClassResolver = new WebSpherePackageScanClassResolver("META-INF/services/org/apache/camel/TypeConverter");
} else {
packageScanClassResolver = new DefaultPackageScanClassResolver();
}
// setup management strategy first since end users may use it to add event notifiers
// using the management strategy before the CamelContext has been started
this.managementStrategy = createManagementStrategy();
this.managementMBeanAssembler = createManagementMBeanAssembler();
Container.Instance.manage(this);
}
/**
* Creates the {@link CamelContext} using the given JNDI context as the registry
*
* @param jndiContext the JNDI context
*/
public DefaultCamelContext(Context jndiContext) {
this();
setJndiContext(jndiContext);
}
/**
* Creates the {@link CamelContext} using the given registry
*
* @param registry the registry
*/
public DefaultCamelContext(Registry registry) {
this();
setRegistry(registry);
}
public String getName() {
return getNameStrategy().getName();
}
/**
* Sets the name of the this context.
*
* @param name the name
*/
public void setName(String name) {
// use an explicit name strategy since an explicit name was provided to be used
this.nameStrategy = new ExplicitCamelContextNameStrategy(name);
}
public CamelContextNameStrategy getNameStrategy() {
return nameStrategy;
}
public void setNameStrategy(CamelContextNameStrategy nameStrategy) {
this.nameStrategy = nameStrategy;
}
public ManagementNameStrategy getManagementNameStrategy() {
return managementNameStrategy;
}
public void setManagementNameStrategy(ManagementNameStrategy managementNameStrategy) {
this.managementNameStrategy = managementNameStrategy;
}
public String getManagementName() {
return managementName;
}
public void setManagementName(String managementName) {
this.managementName = managementName;
}
public Component hasComponent(String componentName) {
return components.get(componentName);
}
public void addComponent(String componentName, final Component component) {
ObjectHelper.notNull(component, "component");
synchronized (components) {
if (components.containsKey(componentName)) {
throw new IllegalArgumentException("Cannot add component as its already previously added: " + componentName);
}
component.setCamelContext(this);
components.put(componentName, component);
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onComponentAdd(componentName, component);
}
// keep reference to properties component up to date
if (component instanceof PropertiesComponent && "properties".equals(componentName)) {
propertiesComponent = (PropertiesComponent) component;
}
}
}
public Component getComponent(String name) {
return getComponent(name, autoCreateComponents);
}
public Component getComponent(String name, boolean autoCreateComponents) {
// synchronize the look up and auto create so that 2 threads can't
// concurrently auto create the same component.
synchronized (components) {
Component component = components.get(name);
if (component == null && autoCreateComponents) {
try {
if (log.isDebugEnabled()) {
log.debug("Using ComponentResolver: {} to resolve component with name: {}", getComponentResolver(), name);
}
component = getComponentResolver().resolveComponent(name, this);
if (component != null) {
addComponent(name, component);
if (isStarted() || isStarting()) {
// If the component is looked up after the context is started, lets start it up.
if (component instanceof Service) {
startService((Service)component);
}
}
}
} catch (Exception e) {
throw new RuntimeCamelException("Cannot auto create component: " + name, e);
}
}
log.trace("getComponent({}) -> {}", name, component);
return component;
}
}
public <T extends Component> T getComponent(String name, Class<T> componentType) {
Component component = getComponent(name);
if (componentType.isInstance(component)) {
return componentType.cast(component);
} else {
String message;
if (component == null) {
message = "Did not find component given by the name: " + name;
} else {
message = "Found component of type: " + component.getClass() + " instead of expected: " + componentType;
}
throw new IllegalArgumentException(message);
}
}
public Component removeComponent(String componentName) {
synchronized (components) {
Component oldComponent = components.remove(componentName);
if (oldComponent != null) {
try {
stopServices(oldComponent);
} catch (Exception e) {
log.warn("Error stopping component " + oldComponent + ". This exception will be ignored.", e);
}
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onComponentRemove(componentName, oldComponent);
}
}
// keep reference to properties component up to date
if (oldComponent != null && "properties".equals(componentName)) {
propertiesComponent = null;
}
return oldComponent;
}
}
// Endpoint Management Methods
// -----------------------------------------------------------------------
public Collection<Endpoint> getEndpoints() {
return new ArrayList<Endpoint>(endpoints.values());
}
public Map<String, Endpoint> getEndpointMap() {
Map<String, Endpoint> answer = new TreeMap<String, Endpoint>();
for (Map.Entry<EndpointKey, Endpoint> entry : endpoints.entrySet()) {
answer.put(entry.getKey().get(), entry.getValue());
}
return answer;
}
public Endpoint hasEndpoint(String uri) {
return endpoints.get(getEndpointKey(uri));
}
public Endpoint addEndpoint(String uri, Endpoint endpoint) throws Exception {
Endpoint oldEndpoint;
startService(endpoint);
oldEndpoint = endpoints.remove(getEndpointKey(uri));
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onEndpointAdd(endpoint);
}
addEndpointToRegistry(uri, endpoint);
if (oldEndpoint != null) {
stopServices(oldEndpoint);
}
return oldEndpoint;
}
public Collection<Endpoint> removeEndpoints(String uri) throws Exception {
Collection<Endpoint> answer = new ArrayList<Endpoint>();
Endpoint oldEndpoint = endpoints.remove(getEndpointKey(uri));
if (oldEndpoint != null) {
answer.add(oldEndpoint);
stopServices(oldEndpoint);
} else {
for (Map.Entry<EndpointKey, Endpoint> entry : endpoints.entrySet()) {
oldEndpoint = entry.getValue();
if (EndpointHelper.matchEndpoint(this, oldEndpoint.getEndpointUri(), uri)) {
try {
stopServices(oldEndpoint);
} catch (Exception e) {
log.warn("Error stopping endpoint " + oldEndpoint + ". This exception will be ignored.", e);
}
answer.add(oldEndpoint);
endpoints.remove(entry.getKey());
}
}
}
// notify lifecycle its being removed
for (Endpoint endpoint : answer) {
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onEndpointRemove(endpoint);
}
}
return answer;
}
public Endpoint getEndpoint(String uri) {
ObjectHelper.notEmpty(uri, "uri");
log.trace("Getting endpoint with uri: {}", uri);
// in case path has property placeholders then try to let property component resolve those
try {
uri = resolvePropertyPlaceholders(uri);
} catch (Exception e) {
throw new ResolveEndpointFailedException(uri, e);
}
final String rawUri = uri;
// normalize uri so we can do endpoint hits with minor mistakes and parameters is not in the same order
uri = normalizeEndpointUri(uri);
log.trace("Getting endpoint with raw uri: {}, normalized uri: {}", rawUri, uri);
Endpoint answer;
String scheme = null;
EndpointKey key = getEndpointKey(uri);
answer = endpoints.get(key);
if (answer == null) {
try {
// Use the URI prefix to find the component.
String splitURI[] = ObjectHelper.splitOnCharacter(uri, ":", 2);
if (splitURI[1] != null) {
scheme = splitURI[0];
log.trace("Endpoint uri: {} is from component with name: {}", uri, scheme);
Component component = getComponent(scheme);
// Ask the component to resolve the endpoint.
if (component != null) {
log.trace("Creating endpoint from uri: {} using component: {}", uri, component);
// Have the component create the endpoint if it can.
if (component.useRawUri()) {
answer = component.createEndpoint(rawUri);
} else {
answer = component.createEndpoint(uri);
}
if (answer != null && log.isDebugEnabled()) {
log.debug("{} converted to endpoint: {} by component: {}", new Object[]{URISupport.sanitizeUri(uri), answer, component});
}
}
}
if (answer == null) {
// no component then try in registry and elsewhere
answer = createEndpoint(uri);
log.trace("No component to create endpoint from uri: {} fallback lookup in registry -> {}", uri, answer);
}
if (answer != null) {
addService(answer);
answer = addEndpointToRegistry(uri, answer);
}
} catch (Exception e) {
throw new ResolveEndpointFailedException(uri, e);
}
}
// unknown scheme
if (answer == null && scheme != null) {
throw new ResolveEndpointFailedException(uri, "No component found with scheme: " + scheme);
}
return answer;
}
public <T extends Endpoint> T getEndpoint(String name, Class<T> endpointType) {
Endpoint endpoint = getEndpoint(name);
if (endpoint == null) {
throw new NoSuchEndpointException(name);
}
if (endpoint instanceof InterceptSendToEndpoint) {
endpoint = ((InterceptSendToEndpoint) endpoint).getDelegate();
}
if (endpointType.isInstance(endpoint)) {
return endpointType.cast(endpoint);
} else {
throw new IllegalArgumentException("The endpoint is not of type: " + endpointType
+ " but is: " + endpoint.getClass().getCanonicalName());
}
}
public void addRegisterEndpointCallback(EndpointStrategy strategy) {
if (!endpointStrategies.contains(strategy)) {
// let it be invoked for already registered endpoints so it can catch-up.
endpointStrategies.add(strategy);
for (Endpoint endpoint : getEndpoints()) {
Endpoint newEndpoint = strategy.registerEndpoint(endpoint.getEndpointUri(), endpoint);
if (newEndpoint != null) {
// put will replace existing endpoint with the new endpoint
endpoints.put(getEndpointKey(endpoint.getEndpointUri()), newEndpoint);
}
}
}
}
/**
* Strategy to add the given endpoint to the internal endpoint registry
*
* @param uri uri of the endpoint
* @param endpoint the endpoint to add
* @return the added endpoint
*/
protected Endpoint addEndpointToRegistry(String uri, Endpoint endpoint) {
ObjectHelper.notEmpty(uri, "uri");
ObjectHelper.notNull(endpoint, "endpoint");
// if there is endpoint strategies, then use the endpoints they return
// as this allows to intercept endpoints etc.
for (EndpointStrategy strategy : endpointStrategies) {
endpoint = strategy.registerEndpoint(uri, endpoint);
}
endpoints.put(getEndpointKey(uri, endpoint), endpoint);
return endpoint;
}
/**
* Normalize uri so we can do endpoint hits with minor mistakes and parameters is not in the same order.
*
* @param uri the uri
* @return normalized uri
* @throws ResolveEndpointFailedException if uri cannot be normalized
*/
protected static String normalizeEndpointUri(String uri) {
try {
uri = URISupport.normalizeUri(uri);
} catch (Exception e) {
throw new ResolveEndpointFailedException(uri, e);
}
return uri;
}
/**
* Gets the endpoint key to use for lookup or whe adding endpoints to the {@link EndpointRegistry}
*
* @param uri the endpoint uri
* @return the key
*/
protected EndpointKey getEndpointKey(String uri) {
return new EndpointKey(uri);
}
/**
* Gets the endpoint key to use for lookup or whe adding endpoints to the {@link EndpointRegistry}
*
* @param uri the endpoint uri
* @param endpoint the endpoint
* @return the key
*/
protected EndpointKey getEndpointKey(String uri, Endpoint endpoint) {
if (endpoint != null && !endpoint.isSingleton()) {
int counter = endpointKeyCounter.incrementAndGet();
return new EndpointKey(uri + ":" + counter);
} else {
return new EndpointKey(uri);
}
}
// Route Management Methods
// -----------------------------------------------------------------------
public List<RouteStartupOrder> getRouteStartupOrder() {
return routeStartupOrder;
}
public synchronized List<Route> getRoutes() {
// lets return a copy of the collection as objects are removed later when services are stopped
if (routes.isEmpty()) {
return Collections.emptyList();
} else {
return new ArrayList<Route>(routes);
}
}
public Route getRoute(String id) {
for (Route route : getRoutes()) {
if (route.getId().equals(id)) {
return route;
}
}
return null;
}
@Deprecated
public void setRoutes(List<Route> routes) {
throw new UnsupportedOperationException("Overriding existing routes is not supported yet, use addRouteCollection instead");
}
synchronized void removeRouteCollection(Collection<Route> routes) {
this.routes.removeAll(routes);
}
synchronized void addRouteCollection(Collection<Route> routes) throws Exception {
this.routes.addAll(routes);
}
public void addRoutes(RoutesBuilder builder) throws Exception {
log.debug("Adding routes from builder: {}", builder);
// lets now add the routes from the builder
builder.addRoutesToCamelContext(this);
}
public synchronized RoutesDefinition loadRoutesDefinition(InputStream is) throws Exception {
// load routes using JAXB
if (jaxbContext == null) {
// must use classloader from CamelContext to have JAXB working
jaxbContext = JAXBContext.newInstance(Constants.JAXB_CONTEXT_PACKAGES, CamelContext.class.getClassLoader());
}
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Object result = unmarshaller.unmarshal(is);
if (result == null) {
throw new IOException("Cannot unmarshal to routes using JAXB from input stream: " + is);
}
// can either be routes or a single route
RoutesDefinition answer = null;
if (result instanceof RouteDefinition) {
RouteDefinition route = (RouteDefinition) result;
answer = new RoutesDefinition();
answer.getRoutes().add(route);
} else if (result instanceof RoutesDefinition) {
answer = (RoutesDefinition) result;
} else {
throw new IllegalArgumentException("Unmarshalled object is an unsupported type: " + ObjectHelper.className(result) + " -> " + result);
}
return answer;
}
public synchronized void addRouteDefinitions(Collection<RouteDefinition> routeDefinitions) throws Exception {
if (routeDefinitions == null || routeDefinitions.isEmpty()) {
return;
}
for (RouteDefinition routeDefinition : routeDefinitions) {
removeRouteDefinition(routeDefinition);
}
this.routeDefinitions.addAll(routeDefinitions);
if (shouldStartRoutes()) {
startRouteDefinitions(routeDefinitions);
}
}
public void addRouteDefinition(RouteDefinition routeDefinition) throws Exception {
addRouteDefinitions(Arrays.asList(routeDefinition));
}
/**
* Removes the route definition with the given key.
*
* @return true if one or more routes was removed
*/
protected boolean removeRouteDefinition(String key) {
boolean answer = false;
Iterator<RouteDefinition> iter = routeDefinitions.iterator();
while (iter.hasNext()) {
RouteDefinition route = iter.next();
if (route.idOrCreate(nodeIdFactory).equals(key)) {
iter.remove();
answer = true;
}
}
return answer;
}
public synchronized void removeRouteDefinitions(Collection<RouteDefinition> routeDefinitions) throws Exception {
for (RouteDefinition routeDefinition : routeDefinitions) {
removeRouteDefinition(routeDefinition);
}
}
public synchronized void removeRouteDefinition(RouteDefinition routeDefinition) throws Exception {
String id = routeDefinition.idOrCreate(nodeIdFactory);
stopRoute(id);
removeRoute(id);
this.routeDefinitions.remove(routeDefinition);
}
public ServiceStatus getRouteStatus(String key) {
RouteService routeService = routeServices.get(key);
if (routeService != null) {
return routeService.getStatus();
}
return null;
}
public void startRoute(RouteDefinition route) throws Exception {
// assign ids to the routes and validate that the id's is all unique
RouteDefinitionHelper.forceAssignIds(this, routeDefinitions);
String duplicate = RouteDefinitionHelper.validateUniqueIds(route, routeDefinitions);
if (duplicate != null) {
throw new FailedToStartRouteException(route.getId(), "duplicate id detected: " + duplicate + ". Please correct ids to be unique among all your routes.");
}
// indicate we are staring the route using this thread so
// we are able to query this if needed
isStartingRoutes.set(true);
try {
// must ensure route is prepared, before we can start it
route.prepare(this);
List<Route> routes = new ArrayList<Route>();
List<RouteContext> routeContexts = route.addRoutes(this, routes);
RouteService routeService = new RouteService(this, route, routeContexts, routes);
startRouteService(routeService, true);
} finally {
// we are done staring routes
isStartingRoutes.remove();
}
}
public boolean isStartingRoutes() {
Boolean answer = isStartingRoutes.get();
return answer != null && answer;
}
public boolean isSetupRoutes() {
Boolean answer = isSetupRoutes.get();
return answer != null && answer;
}
public void stopRoute(RouteDefinition route) throws Exception {
stopRoute(route.idOrCreate(nodeIdFactory));
}
public void startAllRoutes() throws Exception {
doStartOrResumeRoutes(routeServices, true, true, false, false);
}
public synchronized void startRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
startRouteService(routeService, false);
}
}
public synchronized void resumeRoute(String routeId) throws Exception {
if (!routeSupportsSuspension(routeId)) {
// start route if suspension is not supported
startRoute(routeId);
return;
}
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
resumeRouteService(routeService);
}
}
public synchronized boolean stopRoute(String routeId, long timeout, TimeUnit timeUnit, boolean abortAfterTimeout) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
RouteStartupOrder route = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
boolean completed = getShutdownStrategy().shutdown(this, route, timeout, timeUnit, abortAfterTimeout);
if (completed) {
// must stop route service as well
stopRouteService(routeService, false);
} else {
// shutdown was aborted, make sure route is re-started properly
startRouteService(routeService, false);
}
return completed;
}
return false;
}
public synchronized void stopRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes);
// must stop route service as well
stopRouteService(routeService, false);
}
}
public synchronized void stopRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes, timeout, timeUnit);
// must stop route service as well
stopRouteService(routeService, false);
}
}
public synchronized void shutdownRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes);
// must stop route service as well (and remove the routes from management)
stopRouteService(routeService, true);
}
}
public synchronized void shutdownRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes, timeout, timeUnit);
// must stop route service as well (and remove the routes from management)
stopRouteService(routeService, true);
}
}
public synchronized boolean removeRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
if (getRouteStatus(routeId).isStopped()) {
routeService.setRemovingRoutes(true);
shutdownRouteService(routeService);
removeRouteDefinition(routeId);
routeServices.remove(routeId);
// remove route from startup order as well, as it was removed
Iterator<RouteStartupOrder> it = routeStartupOrder.iterator();
while (it.hasNext()) {
RouteStartupOrder order = it.next();
if (order.getRoute().getId().equals(routeId)) {
it.remove();
}
}
return true;
} else {
return false;
}
}
return false;
}
public synchronized void suspendRoute(String routeId) throws Exception {
if (!routeSupportsSuspension(routeId)) {
// stop if we suspend is not supported
stopRoute(routeId);
return;
}
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().suspend(this, routes);
// must suspend route service as well
suspendRouteService(routeService);
}
}
public synchronized void suspendRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception {
if (!routeSupportsSuspension(routeId)) {
stopRoute(routeId, timeout, timeUnit);
return;
}
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().suspend(this, routes, timeout, timeUnit);
// must suspend route service as well
suspendRouteService(routeService);
}
}
public void addService(Object object) throws Exception {
addService(object, true);
}
public void addService(Object object, boolean closeOnShutdown) throws Exception {
doAddService(object, closeOnShutdown);
}
private void doAddService(Object object, boolean closeOnShutdown) throws Exception {
// inject CamelContext
if (object instanceof CamelContextAware) {
CamelContextAware aware = (CamelContextAware) object;
aware.setCamelContext(this);
}
if (object instanceof Service) {
Service service = (Service) object;
for (LifecycleStrategy strategy : lifecycleStrategies) {
if (service instanceof Endpoint) {
// use specialized endpoint add
strategy.onEndpointAdd((Endpoint) service);
} else {
strategy.onServiceAdd(this, service, null);
}
}
// only add to services to close if its a singleton
// otherwise we could for example end up with a lot of prototype scope endpoints
boolean singleton = true; // assume singleton by default
if (service instanceof IsSingleton) {
singleton = ((IsSingleton) service).isSingleton();
}
// do not add endpoints as they have their own list
if (singleton && !(service instanceof Endpoint)) {
// only add to list of services to close if its not already there
if (closeOnShutdown && !hasService(service)) {
servicesToClose.add(service);
}
}
}
// and then ensure service is started (as stated in the javadoc)
if (object instanceof Service) {
startService((Service)object);
} else if (object instanceof Collection<?>) {
startServices((Collection<?>)object);
}
}
public boolean removeService(Object object) throws Exception {
if (object instanceof Service) {
Service service = (Service) object;
for (LifecycleStrategy strategy : lifecycleStrategies) {
if (service instanceof Endpoint) {
// use specialized endpoint remove
strategy.onEndpointRemove((Endpoint) service);
} else {
strategy.onServiceRemove(this, service, null);
}
}
return servicesToClose.remove(service);
}
return false;
}
public boolean hasService(Object object) {
if (object instanceof Service) {
Service service = (Service) object;
return servicesToClose.contains(service);
}
return false;
}
@Override
public <T> T hasService(Class<T> type) {
for (Service service : servicesToClose) {
if (type.isInstance(service)) {
return type.cast(service);
}
}
return null;
}
public void addStartupListener(StartupListener listener) throws Exception {
// either add to listener so we can invoke then later when CamelContext has been started
// or invoke the callback right now
if (isStarted()) {
listener.onCamelContextStarted(this, true);
} else {
startupListeners.add(listener);
}
}
public Map<String, Properties> findComponents() throws LoadPropertiesException, IOException {
return CamelContextHelper.findComponents(this);
}
public String getComponentDocumentation(String componentName) throws IOException {
String packageName = sanitizeComponentName(componentName);
String path = CamelContextHelper.COMPONENT_DOCUMENTATION_PREFIX + packageName + "/" + componentName + ".html";
ClassResolver resolver = getClassResolver();
InputStream inputStream = resolver.loadResourceAsStream(path);
log.debug("Loading component documentation for: {} using class resolver: {} -> {}", new Object[]{componentName, resolver, inputStream});
if (inputStream != null) {
try {
return IOHelper.loadText(inputStream);
} finally {
IOHelper.close(inputStream);
}
}
return null;
}
/**
* Sanitizes the component name by removing dash (-) in the name, when using the component name to load
* resources from the classpath.
*/
private static String sanitizeComponentName(String componentName) {
// the ftp components are in a special package
if ("ftp".equals(componentName) || "ftps".equals(componentName) || "sftp".equals(componentName)) {
return "file/remote";
} else if ("cxfrs".equals(componentName)) {
return "cxf/jaxrs";
} else if ("gauth".equals(componentName) || "ghttp".equals(componentName) || "glogin".equals(componentName)
|| "gmail".equals(componentName) || "gtask".equals(componentName)) {
return "gae/" + componentName.substring(1);
} else if ("atmosphere-websocket".equals(componentName)) {
return "atmosphere/websocket";
} else if ("netty-http".equals(componentName)) {
return "netty/http";
} else if ("netty4-http".equals(componentName)) {
return "netty4/http";
}
return componentName.replaceAll("-", "");
}
public String createRouteStaticEndpointJson(String routeId) {
// lets include dynamic as well as we want as much data as possible
return createRouteStaticEndpointJson(routeId, true);
}
public String createRouteStaticEndpointJson(String routeId, boolean includeDynamic) {
List<RouteDefinition> routes = new ArrayList<RouteDefinition>();
if (routeId != null) {
RouteDefinition route = getRouteDefinition(routeId);
if (route == null) {
throw new IllegalArgumentException("Route with id " + routeId + " does not exist");
}
routes.add(route);
} else {
routes.addAll(getRouteDefinitions());
}
StringBuilder buffer = new StringBuilder("{\n \"routes\": {");
boolean firstRoute = true;
for (RouteDefinition route : routes) {
if (!firstRoute) {
buffer.append("\n },");
} else {
firstRoute = false;
}
String id = route.getId();
buffer.append("\n \"" + id + "\": {");
buffer.append("\n \"inputs\": [");
// for inputs we do not need to check dynamic as we have the data from the route definition
Set<String> inputs = RouteDefinitionHelper.gatherAllStaticEndpointUris(this, route, true, false);
boolean first = true;
for (String input : inputs) {
if (!first) {
buffer.append(",");
} else {
first = false;
}
buffer.append("\n ");
buffer.append(StringHelper.toJson("uri", input, true));
}
buffer.append("\n ]");
buffer.append(",");
buffer.append("\n \"outputs\": [");
Set<String> outputs = RouteDefinitionHelper.gatherAllEndpointUris(this, route, false, true, includeDynamic);
first = true;
for (String output : outputs) {
if (!first) {
buffer.append(",");
} else {
first = false;
}
buffer.append("\n ");
buffer.append(StringHelper.toJson("uri", output, true));
}
buffer.append("\n ]");
}
if (!firstRoute) {
buffer.append("\n }");
}
buffer.append("\n }\n}\n");
return buffer.toString();
}
// Helper methods
// -----------------------------------------------------------------------
public Language resolveLanguage(String language) {
Language answer;
synchronized (languages) {
answer = languages.get(language);
// check if the language is singleton, if so return the shared instance
if (answer instanceof IsSingleton) {
boolean singleton = ((IsSingleton) answer).isSingleton();
if (singleton) {
return answer;
}
}
// language not known or not singleton, then use resolver
answer = getLanguageResolver().resolveLanguage(language, this);
// inject CamelContext if aware
if (answer != null) {
if (answer instanceof CamelContextAware) {
((CamelContextAware) answer).setCamelContext(this);
}
if (answer instanceof Service) {
try {
startService((Service) answer);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
languages.put(language, answer);
}
}
return answer;
}
public String getPropertyPrefixToken() {
PropertiesComponent pc = getPropertiesComponent();
if (pc != null) {
return pc.getPrefixToken();
} else {
return null;
}
}
public String getPropertySuffixToken() {
PropertiesComponent pc = getPropertiesComponent();
if (pc != null) {
return pc.getSuffixToken();
} else {
return null;
}
}
public String resolvePropertyPlaceholders(String text) throws Exception {
// While it is more efficient to only do the lookup if we are sure we need the component,
// with custom tokens, we cannot know if the URI contains a property or not without having
// the component. We also lose fail-fast behavior for the missing component with this change.
PropertiesComponent pc = getPropertiesComponent();
// Do not parse uris that are designated for the properties component as it will handle that itself
if (text != null && !text.startsWith("properties:")) {
// No component, assume default tokens.
if (pc == null && text.contains(PropertiesComponent.DEFAULT_PREFIX_TOKEN)) {
// try to lookup component, as we may be initializing CamelContext itself
Component existing = lookupPropertiesComponent();
if (existing != null) {
if (existing instanceof PropertiesComponent) {
pc = (PropertiesComponent) existing;
} else {
// properties component must be expected type
throw new IllegalArgumentException("Found properties component of type: " + existing.getClass() + " instead of expected: " + PropertiesComponent.class);
}
}
if (pc != null) {
// the parser will throw exception if property key was not found
String answer = pc.parseUri(text);
log.debug("Resolved text: {} -> {}", text, answer);
return answer;
} else {
throw new IllegalArgumentException("PropertiesComponent with name properties must be defined"
+ " in CamelContext to support property placeholders.");
}
// Component available, use actual tokens
} else if (pc != null && text.contains(pc.getPrefixToken())) {
// the parser will throw exception if property key was not found
String answer = pc.parseUri(text);
log.debug("Resolved text: {} -> {}", text, answer);
return answer;
}
}
// return original text as is
return text;
}
// Properties
// -----------------------------------------------------------------------
public TypeConverter getTypeConverter() {
if (typeConverter == null) {
synchronized (this) {
// we can synchronize on this as there is only one instance
// of the camel context (its the container)
typeConverter = createTypeConverter();
try {
// must add service eager
addService(typeConverter);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
}
return typeConverter;
}
public void setTypeConverter(TypeConverter typeConverter) {
this.typeConverter = typeConverter;
try {
// must add service eager
addService(typeConverter);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
public TypeConverterRegistry getTypeConverterRegistry() {
if (typeConverterRegistry == null) {
// init type converter as its lazy
if (typeConverter == null) {
getTypeConverter();
}
if (typeConverter instanceof TypeConverterRegistry) {
typeConverterRegistry = (TypeConverterRegistry) typeConverter;
}
}
return typeConverterRegistry;
}
public void setTypeConverterRegistry(TypeConverterRegistry typeConverterRegistry) {
this.typeConverterRegistry = typeConverterRegistry;
}
public Injector getInjector() {
if (injector == null) {
injector = createInjector();
}
return injector;
}
public void setInjector(Injector injector) {
this.injector = injector;
}
public ManagementMBeanAssembler getManagementMBeanAssembler() {
return managementMBeanAssembler;
}
public void setManagementMBeanAssembler(ManagementMBeanAssembler managementMBeanAssembler) {
this.managementMBeanAssembler = managementMBeanAssembler;
}
public ComponentResolver getComponentResolver() {
if (componentResolver == null) {
componentResolver = createComponentResolver();
}
return componentResolver;
}
public void setComponentResolver(ComponentResolver componentResolver) {
this.componentResolver = componentResolver;
}
public LanguageResolver getLanguageResolver() {
if (languageResolver == null) {
languageResolver = new DefaultLanguageResolver();
}
return languageResolver;
}
public void setLanguageResolver(LanguageResolver languageResolver) {
this.languageResolver = languageResolver;
}
public boolean isAutoCreateComponents() {
return autoCreateComponents;
}
public void setAutoCreateComponents(boolean autoCreateComponents) {
this.autoCreateComponents = autoCreateComponents;
}
public Registry getRegistry() {
if (registry == null) {
registry = createRegistry();
setRegistry(registry);
}
return registry;
}
public <T> T getRegistry(Class<T> type) {
Registry reg = getRegistry();
// unwrap the property placeholder delegate
if (reg instanceof PropertyPlaceholderDelegateRegistry) {
reg = ((PropertyPlaceholderDelegateRegistry) reg).getRegistry();
}
if (type.isAssignableFrom(reg.getClass())) {
return type.cast(reg);
} else if (reg instanceof CompositeRegistry) {
List<Registry> list = ((CompositeRegistry) reg).getRegistryList();
for (Registry r : list) {
if (type.isAssignableFrom(r.getClass())) {
return type.cast(r);
}
}
}
return null;
}
/**
* Sets the registry to the given JNDI context
*
* @param jndiContext is the JNDI context to use as the registry
* @see #setRegistry(org.apache.camel.spi.Registry)
*/
public void setJndiContext(Context jndiContext) {
setRegistry(new JndiRegistry(jndiContext));
}
public void setRegistry(Registry registry) {
// wrap the registry so we always do property placeholder lookups
if (!(registry instanceof PropertyPlaceholderDelegateRegistry)) {
registry = new PropertyPlaceholderDelegateRegistry(this, registry);
}
this.registry = registry;
}
public List<LifecycleStrategy> getLifecycleStrategies() {
return lifecycleStrategies;
}
public void setLifecycleStrategies(List<LifecycleStrategy> lifecycleStrategies) {
this.lifecycleStrategies = lifecycleStrategies;
}
public void addLifecycleStrategy(LifecycleStrategy lifecycleStrategy) {
this.lifecycleStrategies.add(lifecycleStrategy);
}
public void setupRoutes(boolean done) {
if (done) {
isSetupRoutes.remove();
} else {
isSetupRoutes.set(true);
}
}
public synchronized List<RouteDefinition> getRouteDefinitions() {
return routeDefinitions;
}
public synchronized RouteDefinition getRouteDefinition(String id) {
for (RouteDefinition route : routeDefinitions) {
if (route.getId().equals(id)) {
return route;
}
}
return null;
}
public synchronized List<RestDefinition> getRestDefinitions() {
return restDefinitions;
}
public void addRestDefinitions(Collection<RestDefinition> restDefinitions) throws Exception {
if (restDefinitions == null || restDefinitions.isEmpty()) {
return;
}
this.restDefinitions.addAll(restDefinitions);
// convert rests into routes so we reuse routes for runtime
List<RouteDefinition> routes = new ArrayList<RouteDefinition>();
for (RestDefinition rest : restDefinitions) {
routes.addAll(rest.asRouteDefinition(this));
}
addRouteDefinitions(routes);
}
public RestConfiguration getRestConfiguration() {
return restConfiguration;
}
public void setRestConfiguration(RestConfiguration restConfiguration) {
this.restConfiguration = restConfiguration;
}
public List<InterceptStrategy> getInterceptStrategies() {
return interceptStrategies;
}
public void setInterceptStrategies(List<InterceptStrategy> interceptStrategies) {
this.interceptStrategies = interceptStrategies;
}
public void addInterceptStrategy(InterceptStrategy interceptStrategy) {
getInterceptStrategies().add(interceptStrategy);
// for backwards compatible or if user add them here instead of the setXXX methods
if (interceptStrategy instanceof Tracer) {
setTracing(true);
} else if (interceptStrategy instanceof HandleFault) {
setHandleFault(true);
} else if (interceptStrategy instanceof StreamCaching) {
setStreamCaching(true);
} else if (interceptStrategy instanceof Delayer) {
setDelayer(((Delayer)interceptStrategy).getDelay());
}
}
public List<RoutePolicyFactory> getRoutePolicyFactories() {
return routePolicyFactories;
}
public void setRoutePolicyFactories(List<RoutePolicyFactory> routePolicyFactories) {
this.routePolicyFactories = routePolicyFactories;
}
public void addRoutePolicyFactory(RoutePolicyFactory routePolicyFactory) {
getRoutePolicyFactories().add(routePolicyFactory);
}
public void setStreamCaching(Boolean cache) {
this.streamCache = cache;
}
public Boolean isStreamCaching() {
return streamCache;
}
public void setTracing(Boolean tracing) {
this.trace = tracing;
}
public Boolean isTracing() {
return trace;
}
public Boolean isMessageHistory() {
return messageHistory;
}
public void setMessageHistory(Boolean messageHistory) {
this.messageHistory = messageHistory;
}
public Boolean isHandleFault() {
return handleFault;
}
public void setHandleFault(Boolean handleFault) {
this.handleFault = handleFault;
}
public Long getDelayer() {
return delay;
}
public void setDelayer(Long delay) {
this.delay = delay;
}
public ProducerTemplate createProducerTemplate() {
int size = CamelContextHelper.getMaximumCachePoolSize(this);
return createProducerTemplate(size);
}
public ProducerTemplate createProducerTemplate(int maximumCacheSize) {
DefaultProducerTemplate answer = new DefaultProducerTemplate(this);
answer.setMaximumCacheSize(maximumCacheSize);
// start it so its ready to use
try {
startService(answer);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
return answer;
}
public ConsumerTemplate createConsumerTemplate() {
int size = CamelContextHelper.getMaximumCachePoolSize(this);
return createConsumerTemplate(size);
}
public ConsumerTemplate createConsumerTemplate(int maximumCacheSize) {
DefaultConsumerTemplate answer = new DefaultConsumerTemplate(this);
answer.setMaximumCacheSize(maximumCacheSize);
// start it so its ready to use
try {
startService(answer);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
return answer;
}
public ErrorHandlerBuilder getErrorHandlerBuilder() {
return (ErrorHandlerBuilder)errorHandlerBuilder;
}
public void setErrorHandlerBuilder(ErrorHandlerFactory errorHandlerBuilder) {
this.errorHandlerBuilder = errorHandlerBuilder;
}
public ScheduledExecutorService getErrorHandlerExecutorService() {
synchronized (errorHandlerExecutorServiceLock) {
if (errorHandlerExecutorService == null) {
// setup default thread pool for error handler
errorHandlerExecutorService = getExecutorServiceManager().newDefaultScheduledThreadPool("ErrorHandlerRedeliveryThreadPool", "ErrorHandlerRedeliveryTask");
}
}
return errorHandlerExecutorService;
}
public void setProducerServicePool(ServicePool<Endpoint, Producer> producerServicePool) {
this.producerServicePool = producerServicePool;
}
public ServicePool<Endpoint, Producer> getProducerServicePool() {
return producerServicePool;
}
public UnitOfWorkFactory getUnitOfWorkFactory() {
return unitOfWorkFactory;
}
public void setUnitOfWorkFactory(UnitOfWorkFactory unitOfWorkFactory) {
this.unitOfWorkFactory = unitOfWorkFactory;
}
public RuntimeEndpointRegistry getRuntimeEndpointRegistry() {
return runtimeEndpointRegistry;
}
public void setRuntimeEndpointRegistry(RuntimeEndpointRegistry runtimeEndpointRegistry) {
this.runtimeEndpointRegistry = runtimeEndpointRegistry;
}
public String getUptime() {
// compute and log uptime
if (startDate == null) {
return "not started";
}
long delta = new Date().getTime() - startDate.getTime();
return TimeUtils.printDuration(delta);
}
@Override
protected void doSuspend() throws Exception {
EventHelper.notifyCamelContextSuspending(this);
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is suspending");
StopWatch watch = new StopWatch();
// update list of started routes to be suspended
// because we only want to suspend started routes
// (so when we resume we only resume the routes which actually was suspended)
for (Map.Entry<String, RouteService> entry : getRouteServices().entrySet()) {
if (entry.getValue().getStatus().isStarted()) {
suspendedRouteServices.put(entry.getKey(), entry.getValue());
}
}
// assemble list of startup ordering so routes can be shutdown accordingly
List<RouteStartupOrder> orders = new ArrayList<RouteStartupOrder>();
for (Map.Entry<String, RouteService> entry : suspendedRouteServices.entrySet()) {
Route route = entry.getValue().getRoutes().iterator().next();
Integer order = entry.getValue().getRouteDefinition().getStartupOrder();
if (order == null) {
order = defaultRouteStartupOrder++;
}
orders.add(new DefaultRouteStartupOrder(order, route, entry.getValue()));
}
// suspend routes using the shutdown strategy so it can shutdown in correct order
// routes which doesn't support suspension will be stopped instead
getShutdownStrategy().suspend(this, orders);
// mark the route services as suspended or stopped
for (RouteService service : suspendedRouteServices.values()) {
if (routeSupportsSuspension(service.getId())) {
service.suspend();
} else {
service.stop();
}
}
watch.stop();
if (log.isInfoEnabled()) {
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is suspended in " + TimeUtils.printDuration(watch.taken()));
}
EventHelper.notifyCamelContextSuspended(this);
}
@Override
protected void doResume() throws Exception {
try {
EventHelper.notifyCamelContextResuming(this);
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is resuming");
StopWatch watch = new StopWatch();
// start the suspended routes (do not check for route clashes, and indicate)
doStartOrResumeRoutes(suspendedRouteServices, false, true, true, false);
// mark the route services as resumed (will be marked as started) as well
for (RouteService service : suspendedRouteServices.values()) {
if (routeSupportsSuspension(service.getId())) {
service.resume();
} else {
service.start();
}
}
watch.stop();
if (log.isInfoEnabled()) {
log.info("Resumed " + suspendedRouteServices.size() + " routes");
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") resumed in " + TimeUtils.printDuration(watch.taken()));
}
// and clear the list as they have been resumed
suspendedRouteServices.clear();
EventHelper.notifyCamelContextResumed(this);
} catch (Exception e) {
EventHelper.notifyCamelContextResumeFailed(this, e);
throw e;
}
}
public void start() throws Exception {
startDate = new Date();
stopWatch.restart();
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is starting");
doNotStartRoutesOnFirstStart = !firstStartDone && !isAutoStartup();
// if the context was configured with auto startup = false, and we are already started,
// then we may need to start the routes on the 2nd start call
if (firstStartDone && !isAutoStartup() && isStarted()) {
// invoke this logic to warm up the routes and if possible also start the routes
doStartOrResumeRoutes(routeServices, true, true, false, true);
}
// super will invoke doStart which will prepare internal services and start routes etc.
try {
firstStartDone = true;
super.start();
} catch (VetoCamelContextStartException e) {
if (e.isRethrowException()) {
throw e;
} else {
log.info("CamelContext ({}) vetoed to not start due {}", getName(), e.getMessage());
// swallow exception and change state of this camel context to stopped
stop();
return;
}
}
stopWatch.stop();
if (log.isInfoEnabled()) {
// count how many routes are actually started
int started = 0;
for (Route route : getRoutes()) {
if (getRouteStatus(route.getId()).isStarted()) {
started++;
}
}
log.info("Total " + getRoutes().size() + " routes, of which " + started + " is started.");
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") started in " + TimeUtils.printDuration(stopWatch.taken()));
}
EventHelper.notifyCamelContextStarted(this);
}
// Implementation methods
// -----------------------------------------------------------------------
protected synchronized void doStart() throws Exception {
try {
doStartCamel();
} catch (Exception e) {
// fire event that we failed to start
EventHelper.notifyCamelContextStartupFailed(this, e);
// rethrow cause
throw e;
}
}
private void doStartCamel() throws Exception {
if (applicationContextClassLoader == null) {
// Using the TCCL as the default value of ApplicationClassLoader
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
// use the classloader that loaded this class
cl = this.getClass().getClassLoader();
}
setApplicationContextClassLoader(cl);
}
if (log.isDebugEnabled()) {
log.debug("Using ClassResolver={}, PackageScanClassResolver={}, ApplicationContextClassLoader={}",
new Object[]{getClassResolver(), getPackageScanClassResolver(), getApplicationContextClassLoader()});
}
if (isStreamCaching()) {
log.info("StreamCaching is enabled on CamelContext: {}", getName());
}
if (isTracing()) {
// tracing is added in the DefaultChannel so we can enable it on the fly
log.info("Tracing is enabled on CamelContext: {}", getName());
}
if (isUseMDCLogging()) {
// log if MDC has been enabled
log.info("MDC logging is enabled on CamelContext: {}", getName());
}
if (isHandleFault()) {
// only add a new handle fault if not already configured
if (HandleFault.getHandleFault(this) == null) {
log.info("HandleFault is enabled on CamelContext: {}", getName());
addInterceptStrategy(new HandleFault());
}
}
if (getDelayer() != null && getDelayer() > 0) {
log.info("Delayer is enabled with: {} ms. on CamelContext: {}", getDelayer(), getName());
}
// register debugger
if (getDebugger() != null) {
log.info("Debugger: {} is enabled on CamelContext: {}", getDebugger(), getName());
// register this camel context on the debugger
getDebugger().setCamelContext(this);
startService(getDebugger());
addInterceptStrategy(new Debug(getDebugger()));
}
// start management strategy before lifecycles are started
ManagementStrategy managementStrategy = getManagementStrategy();
// inject CamelContext if aware
if (managementStrategy instanceof CamelContextAware) {
((CamelContextAware) managementStrategy).setCamelContext(this);
}
ServiceHelper.startService(managementStrategy);
// start lifecycle strategies
ServiceHelper.startServices(lifecycleStrategies);
Iterator<LifecycleStrategy> it = lifecycleStrategies.iterator();
while (it.hasNext()) {
LifecycleStrategy strategy = it.next();
try {
strategy.onContextStart(this);
} catch (VetoCamelContextStartException e) {
// okay we should not start Camel since it was vetoed
log.warn("Lifecycle strategy vetoed starting CamelContext ({}) due {}", getName(), e.getMessage());
throw e;
} catch (Exception e) {
log.warn("Lifecycle strategy " + strategy + " failed starting CamelContext ({}) due {}", getName(), e.getMessage());
throw e;
}
}
// start notifiers as services
for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
if (notifier instanceof Service) {
Service service = (Service) notifier;
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onServiceAdd(this, service, null);
}
}
if (notifier instanceof Service) {
startService((Service)notifier);
}
}
// must let some bootstrap service be started before we can notify the starting event
EventHelper.notifyCamelContextStarting(this);
forceLazyInitialization();
// re-create endpoint registry as the cache size limit may be set after the constructor of this instance was called.
// and we needed to create endpoints up-front as it may be accessed before this context is started
endpoints = new EndpointRegistry(this, endpoints);
addService(endpoints);
// special for executorServiceManager as want to stop it manually
doAddService(executorServiceManager, false);
addService(producerServicePool);
addService(inflightRepository);
addService(shutdownStrategy);
addService(packageScanClassResolver);
addService(restRegistry);
if (runtimeEndpointRegistry != null) {
if (runtimeEndpointRegistry instanceof EventNotifier) {
getManagementStrategy().addEventNotifier((EventNotifier) runtimeEndpointRegistry);
}
addService(runtimeEndpointRegistry);
}
// eager lookup any configured properties component to avoid subsequent lookup attempts which may impact performance
// due we use properties component for property placeholder resolution at runtime
Component existing = lookupPropertiesComponent();
if (existing != null) {
// store reference to the existing properties component
if (existing instanceof PropertiesComponent) {
propertiesComponent = (PropertiesComponent) existing;
} else {
// properties component must be expected type
throw new IllegalArgumentException("Found properties component of type: " + existing.getClass() + " instead of expected: " + PropertiesComponent.class);
}
}
// start components
startServices(components.values());
// start the route definitions before the routes is started
startRouteDefinitions(routeDefinitions);
// is there any stream caching enabled then log an info about this and its limit of spooling to disk, so people is aware of this
boolean streamCachingInUse = isStreamCaching();
if (!streamCachingInUse) {
for (RouteDefinition route : routeDefinitions) {
Boolean routeCache = CamelContextHelper.parseBoolean(this, route.getStreamCache());
if (routeCache != null && routeCache) {
streamCachingInUse = true;
break;
}
}
}
if (isAllowUseOriginalMessage()) {
log.info("AllowUseOriginalMessage is enabled. If access to the original message is not needed,"
+ " then its recommended to turn this option off as it may improve performance.");
}
if (streamCachingInUse) {
// stream caching is in use so enable the strategy
getStreamCachingStrategy().setEnabled(true);
addService(getStreamCachingStrategy());
} else {
// log if stream caching is not in use as this can help people to enable it if they use streams
log.info("StreamCaching is not in use. If using streams then its recommended to enable stream caching."
+ " See more details at http://camel.apache.org/stream-caching.html");
}
// start routes
if (doNotStartRoutesOnFirstStart) {
log.debug("Skip starting of routes as CamelContext has been configured with autoStartup=false");
}
// invoke this logic to warmup the routes and if possible also start the routes
doStartOrResumeRoutes(routeServices, true, !doNotStartRoutesOnFirstStart, false, true);
// starting will continue in the start method
}
protected synchronized void doStop() throws Exception {
stopWatch.restart();
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is shutting down");
EventHelper.notifyCamelContextStopping(this);
// stop route inputs in the same order as they was started so we stop the very first inputs first
try {
// force shutting down routes as they may otherwise cause shutdown to hang
shutdownStrategy.shutdownForced(this, getRouteStartupOrder());
} catch (Throwable e) {
log.warn("Error occurred while shutting down routes. This exception will be ignored.", e);
}
getRouteStartupOrder().clear();
shutdownServices(routeServices.values());
// do not clear route services or startup listeners as we can start Camel again and get the route back as before
// but clear any suspend routes
suspendedRouteServices.clear();
// stop consumers from the services to close first, such as POJO consumer (eg @Consumer)
// which we need to stop after the routes, as a POJO consumer is essentially a route also
for (Service service : servicesToClose) {
if (service instanceof Consumer) {
shutdownServices(service);
}
}
// the stop order is important
// shutdown default error handler thread pool
if (errorHandlerExecutorService != null) {
// force shutting down the thread pool
getExecutorServiceManager().shutdownNow(errorHandlerExecutorService);
errorHandlerExecutorService = null;
}
// shutdown debugger
ServiceHelper.stopAndShutdownService(getDebugger());
shutdownServices(endpoints.values());
endpoints.clear();
shutdownServices(components.values());
components.clear();
shutdownServices(languages.values());
languages.clear();
try {
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onContextStop(this);
}
} catch (Throwable e) {
log.warn("Error occurred while stopping lifecycle strategies. This exception will be ignored.", e);
}
// shutdown services as late as possible
shutdownServices(servicesToClose);
servicesToClose.clear();
// must notify that we are stopped before stopping the management strategy
EventHelper.notifyCamelContextStopped(this);
// stop the notifier service
for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
shutdownServices(notifier);
}
// shutdown executor service and management as the last one
shutdownServices(executorServiceManager);
shutdownServices(managementStrategy);
shutdownServices(managementMBeanAssembler);
shutdownServices(lifecycleStrategies);
// do not clear lifecycleStrategies as we can start Camel again and get the route back as before
// stop the lazy created so they can be re-created on restart
forceStopLazyInitialization();
// stop to clear introspection cache
IntrospectionSupport.stop();
stopWatch.stop();
if (log.isInfoEnabled()) {
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") uptime {}", getUptime());
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is shutdown in " + TimeUtils.printDuration(stopWatch.taken()));
}
// and clear start date
startDate = null;
Container.Instance.unmanage(this);
}
/**
* Starts or resumes the routes
*
* @param routeServices the routes to start (will only start a route if its not already started)
* @param checkClash whether to check for startup ordering clash
* @param startConsumer whether the route consumer should be started. Can be used to warmup the route without starting the consumer.
* @param resumeConsumer whether the route consumer should be resumed.
* @param addingRoutes whether we are adding new routes
* @throws Exception is thrown if error starting routes
*/
protected void doStartOrResumeRoutes(Map<String, RouteService> routeServices, boolean checkClash,
boolean startConsumer, boolean resumeConsumer, boolean addingRoutes) throws Exception {
isStartingRoutes.set(true);
try {
// filter out already started routes
Map<String, RouteService> filtered = new LinkedHashMap<String, RouteService>();
for (Map.Entry<String, RouteService> entry : routeServices.entrySet()) {
boolean startable = false;
Consumer consumer = entry.getValue().getRoutes().iterator().next().getConsumer();
if (consumer instanceof SuspendableService) {
// consumer could be suspended, which is not reflected in the RouteService status
startable = ((SuspendableService) consumer).isSuspended();
}
if (!startable && consumer instanceof StatefulService) {
// consumer could be stopped, which is not reflected in the RouteService status
startable = ((StatefulService) consumer).getStatus().isStartable();
} else if (!startable) {
// no consumer so use state from route service
startable = entry.getValue().getStatus().isStartable();
}
if (startable) {
filtered.put(entry.getKey(), entry.getValue());
}
}
if (!filtered.isEmpty()) {
// the context is now considered started (i.e. isStarted() == true))
// starting routes is done after, not during context startup
safelyStartRouteServices(checkClash, startConsumer, resumeConsumer, addingRoutes, filtered.values());
}
// we are finished starting routes, so remove flag before we emit the startup listeners below
isStartingRoutes.remove();
// now notify any startup aware listeners as all the routes etc has been started,
// allowing the listeners to do custom work after routes has been started
for (StartupListener startup : startupListeners) {
startup.onCamelContextStarted(this, isStarted());
}
} finally {
isStartingRoutes.remove();
}
}
protected boolean routeSupportsSuspension(String routeId) {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
return routeService.getRoutes().iterator().next().supportsSuspension();
}
return false;
}
private void shutdownServices(Object service) {
// do not rethrow exception as we want to keep shutting down in case of problems
// allow us to do custom work before delegating to service helper
try {
if (service instanceof Service) {
ServiceHelper.stopAndShutdownService(service);
} else if (service instanceof Collection) {
ServiceHelper.stopAndShutdownServices((Collection<?>)service);
}
} catch (Throwable e) {
log.warn("Error occurred while shutting down service: " + service + ". This exception will be ignored.", e);
// fire event
EventHelper.notifyServiceStopFailure(this, service, e);
}
}
private void shutdownServices(Collection<?> services) {
// reverse stopping by default
shutdownServices(services, true);
}
private void shutdownServices(Collection<?> services, boolean reverse) {
Collection<?> list = services;
if (reverse) {
List<Object> reverseList = new ArrayList<Object>(services);
Collections.reverse(reverseList);
list = reverseList;
}
for (Object service : list) {
shutdownServices(service);
}
}
private void startService(Service service) throws Exception {
// and register startup aware so they can be notified when
// camel context has been started
if (service instanceof StartupListener) {
StartupListener listener = (StartupListener) service;
addStartupListener(listener);
}
service.start();
}
private void startServices(Collection<?> services) throws Exception {
for (Object element : services) {
if (element instanceof Service) {
startService((Service)element);
}
}
}
private void stopServices(Object service) throws Exception {
// allow us to do custom work before delegating to service helper
try {
ServiceHelper.stopService(service);
} catch (Exception e) {
// fire event
EventHelper.notifyServiceStopFailure(this, service, e);
// rethrow to signal error with stopping
throw e;
}
}
protected void startRouteDefinitions(Collection<RouteDefinition> list) throws Exception {
if (list != null) {
for (RouteDefinition route : list) {
startRoute(route);
}
}
}
/**
* Starts the given route service
*/
protected synchronized void startRouteService(RouteService routeService, boolean addingRoutes) throws Exception {
// we may already be starting routes so remember this, so we can unset accordingly in finally block
boolean alreadyStartingRoutes = isStartingRoutes();
if (!alreadyStartingRoutes) {
isStartingRoutes.set(true);
}
try {
// the route service could have been suspended, and if so then resume it instead
if (routeService.getStatus().isSuspended()) {
resumeRouteService(routeService);
} else {
// start the route service
routeServices.put(routeService.getId(), routeService);
if (shouldStartRoutes()) {
// this method will log the routes being started
safelyStartRouteServices(true, true, true, false, addingRoutes, routeService);
// start route services if it was configured to auto startup and we are not adding routes
boolean autoStartup = routeService.getRouteDefinition().isAutoStartup(this) && this.isAutoStartup();
if (!addingRoutes || autoStartup) {
// start the route since auto start is enabled or we are starting a route (not adding new routes)
routeService.start();
}
}
}
} finally {
if (!alreadyStartingRoutes) {
isStartingRoutes.remove();
}
}
}
/**
* Resumes the given route service
*/
protected synchronized void resumeRouteService(RouteService routeService) throws Exception {
// the route service could have been stopped, and if so then start it instead
if (!routeService.getStatus().isSuspended()) {
startRouteService(routeService, false);
} else {
// resume the route service
if (shouldStartRoutes()) {
// this method will log the routes being started
safelyStartRouteServices(true, false, true, true, false, routeService);
// must resume route service as well
routeService.resume();
}
}
}
protected synchronized void stopRouteService(RouteService routeService, boolean removingRoutes) throws Exception {
routeService.setRemovingRoutes(removingRoutes);
stopRouteService(routeService);
}
protected void logRouteState(Route route, String state) {
if (log.isInfoEnabled()) {
if (route.getConsumer() != null) {
log.info("Route: {} is {}, was consuming from: {}", new Object[]{route.getId(), state, route.getConsumer().getEndpoint()});
} else {
log.info("Route: {} is {}.", route.getId(), state);
}
}
}
protected synchronized void stopRouteService(RouteService routeService) throws Exception {
routeService.stop();
for (Route route : routeService.getRoutes()) {
logRouteState(route, "stopped");
}
}
protected synchronized void shutdownRouteService(RouteService routeService) throws Exception {
routeService.shutdown();
for (Route route : routeService.getRoutes()) {
logRouteState(route, "shutdown and removed");
}
}
protected synchronized void suspendRouteService(RouteService routeService) throws Exception {
routeService.setRemovingRoutes(false);
routeService.suspend();
for (Route route : routeService.getRoutes()) {
logRouteState(route, "suspended");
}
}
/**
* Starts the routes services in a proper manner which ensures the routes will be started in correct order,
* check for clash and that the routes will also be shutdown in correct order as well.
* <p/>
* This method <b>must</b> be used to start routes in a safe manner.
*
* @param checkClash whether to check for startup order clash
* @param startConsumer whether the route consumer should be started. Can be used to warmup the route without starting the consumer.
* @param resumeConsumer whether the route consumer should be resumed.
* @param addingRoutes whether we are adding new routes
* @param routeServices the routes
* @throws Exception is thrown if error starting the routes
*/
protected synchronized void safelyStartRouteServices(boolean checkClash, boolean startConsumer, boolean resumeConsumer,
boolean addingRoutes, Collection<RouteService> routeServices) throws Exception {
// list of inputs to start when all the routes have been prepared for starting
// we use a tree map so the routes will be ordered according to startup order defined on the route
Map<Integer, DefaultRouteStartupOrder> inputs = new TreeMap<Integer, DefaultRouteStartupOrder>();
// figure out the order in which the routes should be started
for (RouteService routeService : routeServices) {
DefaultRouteStartupOrder order = doPrepareRouteToBeStarted(routeService);
// check for clash before we add it as input
if (checkClash) {
doCheckStartupOrderClash(order, inputs);
}
inputs.put(order.getStartupOrder(), order);
}
// warm up routes before we start them
doWarmUpRoutes(inputs, startConsumer);
if (startConsumer) {
if (resumeConsumer) {
// and now resume the routes
doResumeRouteConsumers(inputs, addingRoutes);
} else {
// and now start the routes
// and check for clash with multiple consumers of the same endpoints which is not allowed
doStartRouteConsumers(inputs, addingRoutes);
}
}
// inputs no longer needed
inputs.clear();
}
/**
* @see #safelyStartRouteServices(boolean,boolean,boolean,boolean,java.util.Collection)
*/
protected synchronized void safelyStartRouteServices(boolean forceAutoStart, boolean checkClash, boolean startConsumer,
boolean resumeConsumer, boolean addingRoutes, RouteService... routeServices) throws Exception {
safelyStartRouteServices(checkClash, startConsumer, resumeConsumer, addingRoutes, Arrays.asList(routeServices));
}
private DefaultRouteStartupOrder doPrepareRouteToBeStarted(RouteService routeService) {
// add the inputs from this route service to the list to start afterwards
// should be ordered according to the startup number
Integer startupOrder = routeService.getRouteDefinition().getStartupOrder();
if (startupOrder == null) {
// auto assign a default startup order
startupOrder = defaultRouteStartupOrder++;
}
// create holder object that contains information about this route to be started
Route route = routeService.getRoutes().iterator().next();
return new DefaultRouteStartupOrder(startupOrder, route, routeService);
}
private boolean doCheckStartupOrderClash(DefaultRouteStartupOrder answer, Map<Integer, DefaultRouteStartupOrder> inputs) throws FailedToStartRouteException {
// check for clash by startupOrder id
DefaultRouteStartupOrder other = inputs.get(answer.getStartupOrder());
if (other != null && answer != other) {
String otherId = other.getRoute().getId();
throw new FailedToStartRouteException(answer.getRoute().getId(), "startupOrder clash. Route " + otherId + " already has startupOrder "
+ answer.getStartupOrder() + " configured which this route have as well. Please correct startupOrder to be unique among all your routes.");
}
// check in existing already started as well
for (RouteStartupOrder order : routeStartupOrder) {
String otherId = order.getRoute().getId();
if (answer.getRoute().getId().equals(otherId)) {
// its the same route id so skip clash check as its the same route (can happen when using suspend/resume)
} else if (answer.getStartupOrder() == order.getStartupOrder()) {
throw new FailedToStartRouteException(answer.getRoute().getId(), "startupOrder clash. Route " + otherId + " already has startupOrder "
+ answer.getStartupOrder() + " configured which this route have as well. Please correct startupOrder to be unique among all your routes.");
}
}
return true;
}
private void doWarmUpRoutes(Map<Integer, DefaultRouteStartupOrder> inputs, boolean autoStartup) throws Exception {
// now prepare the routes by starting its services before we start the input
for (Map.Entry<Integer, DefaultRouteStartupOrder> entry : inputs.entrySet()) {
// defer starting inputs till later as we want to prepare the routes by starting
// all their processors and child services etc.
// then later we open the floods to Camel by starting the inputs
// what this does is to ensure Camel is more robust on starting routes as all routes
// will then be prepared in time before we start inputs which will consume messages to be routed
RouteService routeService = entry.getValue().getRouteService();
log.debug("Warming up route id: {} having autoStartup={}", routeService.getId(), autoStartup);
routeService.warmUp();
}
}
private void doResumeRouteConsumers(Map<Integer, DefaultRouteStartupOrder> inputs, boolean addingRoutes) throws Exception {
doStartOrResumeRouteConsumers(inputs, true, addingRoutes);
}
private void doStartRouteConsumers(Map<Integer, DefaultRouteStartupOrder> inputs, boolean addingRoutes) throws Exception {
doStartOrResumeRouteConsumers(inputs, false, addingRoutes);
}
private void doStartOrResumeRouteConsumers(Map<Integer, DefaultRouteStartupOrder> inputs, boolean resumeOnly, boolean addingRoute) throws Exception {
List<Endpoint> routeInputs = new ArrayList<Endpoint>();
for (Map.Entry<Integer, DefaultRouteStartupOrder> entry : inputs.entrySet()) {
Integer order = entry.getKey();
Route route = entry.getValue().getRoute();
RouteService routeService = entry.getValue().getRouteService();
// if we are starting camel, then skip routes which are configured to not be auto started
boolean autoStartup = routeService.getRouteDefinition().isAutoStartup(this) && this.isAutoStartup();
if (addingRoute && !autoStartup) {
log.info("Skipping starting of route " + routeService.getId() + " as its configured with autoStartup=false");
continue;
}
// start the service
for (Consumer consumer : routeService.getInputs().values()) {
Endpoint endpoint = consumer.getEndpoint();
// check multiple consumer violation, with the other routes to be started
if (!doCheckMultipleConsumerSupportClash(endpoint, routeInputs)) {
throw new FailedToStartRouteException(routeService.getId(),
"Multiple consumers for the same endpoint is not allowed: " + endpoint);
}
// check for multiple consumer violations with existing routes which
// have already been started, or is currently starting
List<Endpoint> existingEndpoints = new ArrayList<Endpoint>();
for (Route existingRoute : getRoutes()) {
if (route.getId().equals(existingRoute.getId())) {
// skip ourselves
continue;
}
Endpoint existing = existingRoute.getEndpoint();
ServiceStatus status = getRouteStatus(existingRoute.getId());
if (status != null && (status.isStarted() || status.isStarting())) {
existingEndpoints.add(existing);
}
}
if (!doCheckMultipleConsumerSupportClash(endpoint, existingEndpoints)) {
throw new FailedToStartRouteException(routeService.getId(),
"Multiple consumers for the same endpoint is not allowed: " + endpoint);
}
// start the consumer on the route
log.debug("Route: {} >>> {}", route.getId(), route);
if (resumeOnly) {
log.debug("Resuming consumer (order: {}) on route: {}", order, route.getId());
} else {
log.debug("Starting consumer (order: {}) on route: {}", order, route.getId());
}
if (resumeOnly && route.supportsSuspension()) {
// if we are resuming and the route can be resumed
ServiceHelper.resumeService(consumer);
log.info("Route: " + route.getId() + " resumed and consuming from: " + endpoint);
} else {
// when starting we should invoke the lifecycle strategies
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onServiceAdd(this, consumer, route);
}
startService(consumer);
log.info("Route: " + route.getId() + " started and consuming from: " + endpoint);
}
routeInputs.add(endpoint);
// add to the order which they was started, so we know how to stop them in reverse order
// but only add if we haven't already registered it before (we dont want to double add when restarting)
boolean found = false;
for (RouteStartupOrder other : routeStartupOrder) {
if (other.getRoute().getId().equals(route.getId())) {
found = true;
break;
}
}
if (!found) {
routeStartupOrder.add(entry.getValue());
}
}
if (resumeOnly) {
routeService.resume();
} else {
// and start the route service (no need to start children as they are already warmed up)
routeService.start(false);
}
}
}
private boolean doCheckMultipleConsumerSupportClash(Endpoint endpoint, List<Endpoint> routeInputs) {
// is multiple consumers supported
boolean multipleConsumersSupported = false;
if (endpoint instanceof MultipleConsumersSupport) {
multipleConsumersSupported = ((MultipleConsumersSupport) endpoint).isMultipleConsumersSupported();
}
if (multipleConsumersSupported) {
// multiple consumer allowed, so return true
return true;
}
// check in progress list
if (routeInputs.contains(endpoint)) {
return false;
}
return true;
}
/**
* Force some lazy initialization to occur upfront before we start any
* components and create routes
*/
protected void forceLazyInitialization() {
getRegistry();
getInjector();
getLanguageResolver();
getTypeConverterRegistry();
getTypeConverter();
getRuntimeEndpointRegistry();
if (isTypeConverterStatisticsEnabled() != null) {
getTypeConverterRegistry().getStatistics().setStatisticsEnabled(isTypeConverterStatisticsEnabled());
}
}
/**
* Force clear lazy initialization so they can be re-created on restart
*/
protected void forceStopLazyInitialization() {
injector = null;
languageResolver = null;
typeConverterRegistry = null;
typeConverter = null;
}
/**
* Lazily create a default implementation
*/
protected TypeConverter createTypeConverter() {
BaseTypeConverterRegistry answer;
if (isLazyLoadTypeConverters()) {
answer = new LazyLoadingTypeConverter(packageScanClassResolver, getInjector(), getDefaultFactoryFinder());
} else {
answer = new DefaultTypeConverter(packageScanClassResolver, getInjector(), getDefaultFactoryFinder());
}
setTypeConverterRegistry(answer);
return answer;
}
/**
* Lazily create a default implementation
*/
protected Injector createInjector() {
FactoryFinder finder = getDefaultFactoryFinder();
try {
return (Injector) finder.newInstance("Injector");
} catch (NoFactoryAvailableException e) {
// lets use the default injector
return new DefaultInjector(this);
}
}
/**
* Lazily create a default implementation
*/
protected ManagementMBeanAssembler createManagementMBeanAssembler() {
return new DefaultManagementMBeanAssembler(this);
}
/**
* Lazily create a default implementation
*/
protected ComponentResolver createComponentResolver() {
return new DefaultComponentResolver();
}
/**
* Lazily create a default implementation
*/
protected Registry createRegistry() {
JndiRegistry jndi = new JndiRegistry();
try {
// getContext() will force setting up JNDI
jndi.getContext();
return jndi;
} catch (Throwable e) {
log.debug("Cannot create javax.naming.InitialContext due " + e.getMessage() + ". Will fallback and use SimpleRegistry instead. This exception is ignored.", e);
return new SimpleRegistry();
}
}
/**
* A pluggable strategy to allow an endpoint to be created without requiring
* a component to be its factory, such as for looking up the URI inside some
* {@link Registry}
*
* @param uri the uri for the endpoint to be created
* @return the newly created endpoint or null if it could not be resolved
*/
protected Endpoint createEndpoint(String uri) {
Object value = getRegistry().lookupByName(uri);
if (value instanceof Endpoint) {
return (Endpoint) value;
} else if (value instanceof Processor) {
return new ProcessorEndpoint(uri, this, (Processor) value);
} else if (value != null) {
return convertBeanToEndpoint(uri, value);
}
return null;
}
/**
* Strategy method for attempting to convert the bean from a {@link Registry} to an endpoint using
* some kind of transformation or wrapper
*
* @param uri the uri for the endpoint (and name in the registry)
* @param bean the bean to be converted to an endpoint, which will be not null
* @return a new endpoint
*/
protected Endpoint convertBeanToEndpoint(String uri, Object bean) {
throw new IllegalArgumentException("uri: " + uri + " bean: " + bean
+ " could not be converted to an Endpoint");
}
/**
* Should we start newly added routes?
*/
protected boolean shouldStartRoutes() {
return isStarted() && !isStarting();
}
/**
* Gets the properties component in use.
* Returns {@code null} if no properties component is in use.
*/
protected PropertiesComponent getPropertiesComponent() {
return propertiesComponent;
}
public void setDataFormats(Map<String, DataFormatDefinition> dataFormats) {
this.dataFormats = dataFormats;
}
public Map<String, DataFormatDefinition> getDataFormats() {
return dataFormats;
}
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
public FactoryFinder getDefaultFactoryFinder() {
if (defaultFactoryFinder == null) {
defaultFactoryFinder = factoryFinderResolver.resolveDefaultFactoryFinder(getClassResolver());
}
return defaultFactoryFinder;
}
public void setFactoryFinderResolver(FactoryFinderResolver resolver) {
this.factoryFinderResolver = resolver;
}
public FactoryFinder getFactoryFinder(String path) throws NoFactoryAvailableException {
synchronized (factories) {
FactoryFinder answer = factories.get(path);
if (answer == null) {
answer = factoryFinderResolver.resolveFactoryFinder(getClassResolver(), path);
factories.put(path, answer);
}
return answer;
}
}
public ClassResolver getClassResolver() {
return classResolver;
}
public void setClassResolver(ClassResolver classResolver) {
this.classResolver = classResolver;
}
public PackageScanClassResolver getPackageScanClassResolver() {
return packageScanClassResolver;
}
public void setPackageScanClassResolver(PackageScanClassResolver packageScanClassResolver) {
this.packageScanClassResolver = packageScanClassResolver;
}
public List<String> getComponentNames() {
synchronized (components) {
List<String> answer = new ArrayList<String>();
for (String name : components.keySet()) {
answer.add(name);
}
return answer;
}
}
public List<String> getLanguageNames() {
synchronized (languages) {
List<String> answer = new ArrayList<String>();
for (String name : languages.keySet()) {
answer.add(name);
}
return answer;
}
}
public NodeIdFactory getNodeIdFactory() {
return nodeIdFactory;
}
public void setNodeIdFactory(NodeIdFactory idFactory) {
this.nodeIdFactory = idFactory;
}
public ManagementStrategy getManagementStrategy() {
return managementStrategy;
}
public void setManagementStrategy(ManagementStrategy managementStrategy) {
this.managementStrategy = managementStrategy;
}
public InterceptStrategy getDefaultTracer() {
if (defaultTracer == null) {
defaultTracer = new Tracer();
}
return defaultTracer;
}
public void setDefaultTracer(InterceptStrategy tracer) {
this.defaultTracer = tracer;
}
public InterceptStrategy getDefaultBacklogTracer() {
if (defaultBacklogTracer == null) {
defaultBacklogTracer = new BacklogTracer(this);
}
return defaultBacklogTracer;
}
public void setDefaultBacklogTracer(InterceptStrategy backlogTracer) {
this.defaultBacklogTracer = backlogTracer;
}
public InterceptStrategy getDefaultBacklogDebugger() {
if (defaultBacklogDebugger == null) {
defaultBacklogDebugger = new BacklogDebugger(this);
}
return defaultBacklogDebugger;
}
public void setDefaultBacklogDebugger(InterceptStrategy defaultBacklogDebugger) {
this.defaultBacklogDebugger = defaultBacklogDebugger;
}
public void disableJMX() {
if (isStarting() || isStarted()) {
throw new IllegalStateException("Disabling JMX can only be done when CamelContext has not been started");
}
managementStrategy = new DefaultManagementStrategy(this);
// must clear lifecycle strategies as we add DefaultManagementLifecycleStrategy by default for JMX support
lifecycleStrategies.clear();
}
public InflightRepository getInflightRepository() {
return inflightRepository;
}
public void setInflightRepository(InflightRepository repository) {
this.inflightRepository = repository;
}
public void setAutoStartup(Boolean autoStartup) {
this.autoStartup = autoStartup;
}
public Boolean isAutoStartup() {
return autoStartup != null && autoStartup;
}
@Deprecated
public Boolean isLazyLoadTypeConverters() {
return lazyLoadTypeConverters != null && lazyLoadTypeConverters;
}
@Deprecated
public void setLazyLoadTypeConverters(Boolean lazyLoadTypeConverters) {
this.lazyLoadTypeConverters = lazyLoadTypeConverters;
}
public Boolean isTypeConverterStatisticsEnabled() {
return typeConverterStatisticsEnabled != null && typeConverterStatisticsEnabled;
}
public void setTypeConverterStatisticsEnabled(Boolean typeConverterStatisticsEnabled) {
this.typeConverterStatisticsEnabled = typeConverterStatisticsEnabled;
}
public Boolean isUseMDCLogging() {
return useMDCLogging != null && useMDCLogging;
}
public void setUseMDCLogging(Boolean useMDCLogging) {
this.useMDCLogging = useMDCLogging;
}
public Boolean isUseBreadcrumb() {
return useBreadcrumb != null && useBreadcrumb;
}
public void setUseBreadcrumb(Boolean useBreadcrumb) {
this.useBreadcrumb = useBreadcrumb;
}
public ClassLoader getApplicationContextClassLoader() {
return applicationContextClassLoader;
}
public void setApplicationContextClassLoader(ClassLoader classLoader) {
applicationContextClassLoader = classLoader;
}
public DataFormatResolver getDataFormatResolver() {
return dataFormatResolver;
}
public void setDataFormatResolver(DataFormatResolver dataFormatResolver) {
this.dataFormatResolver = dataFormatResolver;
}
public DataFormat resolveDataFormat(String name) {
DataFormat answer = dataFormatResolver.resolveDataFormat(name, this);
// inject CamelContext if aware
if (answer != null && answer instanceof CamelContextAware) {
((CamelContextAware) answer).setCamelContext(this);
}
return answer;
}
public DataFormatDefinition resolveDataFormatDefinition(String name) {
// lookup type and create the data format from it
DataFormatDefinition type = lookup(this, name, DataFormatDefinition.class);
if (type == null && getDataFormats() != null) {
type = getDataFormats().get(name);
}
return type;
}
private static <T> T lookup(CamelContext context, String ref, Class<T> type) {
try {
return context.getRegistry().lookupByNameAndType(ref, type);
} catch (Exception e) {
// need to ignore not same type and return it as null
return null;
}
}
protected Component lookupPropertiesComponent() {
// no existing properties component so lookup and add as component if possible
PropertiesComponent answer = (PropertiesComponent) hasComponent("properties");
if (answer == null) {
answer = getRegistry().lookupByNameAndType("properties", PropertiesComponent.class);
if (answer != null) {
addComponent("properties", answer);
}
}
return answer;
}
public ShutdownStrategy getShutdownStrategy() {
return shutdownStrategy;
}
public void setShutdownStrategy(ShutdownStrategy shutdownStrategy) {
this.shutdownStrategy = shutdownStrategy;
}
public ShutdownRoute getShutdownRoute() {
return shutdownRoute;
}
public void setShutdownRoute(ShutdownRoute shutdownRoute) {
this.shutdownRoute = shutdownRoute;
}
public ShutdownRunningTask getShutdownRunningTask() {
return shutdownRunningTask;
}
public void setShutdownRunningTask(ShutdownRunningTask shutdownRunningTask) {
this.shutdownRunningTask = shutdownRunningTask;
}
public void setAllowUseOriginalMessage(Boolean allowUseOriginalMessage) {
this.allowUseOriginalMessage = allowUseOriginalMessage;
}
public Boolean isAllowUseOriginalMessage() {
return allowUseOriginalMessage != null && allowUseOriginalMessage;
}
public ExecutorServiceManager getExecutorServiceManager() {
return this.executorServiceManager;
}
@Deprecated
public org.apache.camel.spi.ExecutorServiceStrategy getExecutorServiceStrategy() {
// its okay to create a new instance as its stateless, and just delegate
// ExecutorServiceManager which is the new API
return new DefaultExecutorServiceStrategy(this);
}
public void setExecutorServiceManager(ExecutorServiceManager executorServiceManager) {
this.executorServiceManager = executorServiceManager;
}
public ProcessorFactory getProcessorFactory() {
return processorFactory;
}
public void setProcessorFactory(ProcessorFactory processorFactory) {
this.processorFactory = processorFactory;
}
public Debugger getDebugger() {
return debugger;
}
public void setDebugger(Debugger debugger) {
this.debugger = debugger;
}
public UuidGenerator getUuidGenerator() {
return uuidGenerator;
}
public void setUuidGenerator(UuidGenerator uuidGenerator) {
this.uuidGenerator = uuidGenerator;
}
public StreamCachingStrategy getStreamCachingStrategy() {
if (streamCachingStrategy == null) {
streamCachingStrategy = new DefaultStreamCachingStrategy();
}
return streamCachingStrategy;
}
public void setStreamCachingStrategy(StreamCachingStrategy streamCachingStrategy) {
this.streamCachingStrategy = streamCachingStrategy;
}
public RestRegistry getRestRegistry() {
return restRegistry;
}
public void setRestRegistry(RestRegistry restRegistry) {
this.restRegistry = restRegistry;
}
@Override
public String getProperty(String name) {
String value = getProperties().get(name);
if (ObjectHelper.isNotEmpty(value)) {
try {
value = resolvePropertyPlaceholders(value);
} catch (Exception e) {
throw new RuntimeCamelException("Error getting property: " + name, e);
}
}
return value;
}
protected Map<String, RouteService> getRouteServices() {
return routeServices;
}
protected ManagementStrategy createManagementStrategy() {
return new ManagementStrategyFactory().create(this, disableJMX || Boolean.getBoolean(JmxSystemPropertyKeys.DISABLED));
}
/**
* Reset context counter to a preset value. Mostly used for tests to ensure a predictable getName()
*
* @param value new value for the context counter
*/
public static void setContextCounter(int value) {
DefaultCamelContextNameStrategy.setCounter(value);
DefaultManagementNameStrategy.setCounter(value);
}
private static UuidGenerator createDefaultUuidGenerator() {
if (System.getProperty("com.google.appengine.runtime.environment") != null) {
// either "Production" or "Development"
return new JavaUuidGenerator();
} else {
return new ActiveMQUuidGenerator();
}
}
@Override
public String toString() {
return "CamelContext(" + getName() + ")";
}
}
| camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.impl;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.naming.Context;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Endpoint;
import org.apache.camel.ErrorHandlerFactory;
import org.apache.camel.FailedToStartRouteException;
import org.apache.camel.IsSingleton;
import org.apache.camel.MultipleConsumersSupport;
import org.apache.camel.NoFactoryAvailableException;
import org.apache.camel.NoSuchEndpointException;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.ResolveEndpointFailedException;
import org.apache.camel.Route;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.Service;
import org.apache.camel.ServiceStatus;
import org.apache.camel.ShutdownRoute;
import org.apache.camel.ShutdownRunningTask;
import org.apache.camel.StartupListener;
import org.apache.camel.StatefulService;
import org.apache.camel.SuspendableService;
import org.apache.camel.TypeConverter;
import org.apache.camel.VetoCamelContextStartException;
import org.apache.camel.builder.ErrorHandlerBuilder;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.impl.converter.BaseTypeConverterRegistry;
import org.apache.camel.impl.converter.DefaultTypeConverter;
import org.apache.camel.impl.converter.LazyLoadingTypeConverter;
import org.apache.camel.management.DefaultManagementMBeanAssembler;
import org.apache.camel.management.DefaultManagementStrategy;
import org.apache.camel.management.JmxSystemPropertyKeys;
import org.apache.camel.management.ManagementStrategyFactory;
import org.apache.camel.model.Constants;
import org.apache.camel.model.DataFormatDefinition;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.model.RouteDefinitionHelper;
import org.apache.camel.model.RoutesDefinition;
import org.apache.camel.model.rest.RestDefinition;
import org.apache.camel.processor.interceptor.BacklogDebugger;
import org.apache.camel.processor.interceptor.BacklogTracer;
import org.apache.camel.processor.interceptor.Debug;
import org.apache.camel.processor.interceptor.Delayer;
import org.apache.camel.processor.interceptor.HandleFault;
import org.apache.camel.processor.interceptor.StreamCaching;
import org.apache.camel.processor.interceptor.Tracer;
import org.apache.camel.spi.CamelContextNameStrategy;
import org.apache.camel.spi.ClassResolver;
import org.apache.camel.spi.ComponentResolver;
import org.apache.camel.spi.Container;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.DataFormatResolver;
import org.apache.camel.spi.Debugger;
import org.apache.camel.spi.EndpointStrategy;
import org.apache.camel.spi.EventNotifier;
import org.apache.camel.spi.ExecutorServiceManager;
import org.apache.camel.spi.FactoryFinder;
import org.apache.camel.spi.FactoryFinderResolver;
import org.apache.camel.spi.InflightRepository;
import org.apache.camel.spi.Injector;
import org.apache.camel.spi.InterceptStrategy;
import org.apache.camel.spi.Language;
import org.apache.camel.spi.LanguageResolver;
import org.apache.camel.spi.LifecycleStrategy;
import org.apache.camel.spi.ManagementMBeanAssembler;
import org.apache.camel.spi.ManagementNameStrategy;
import org.apache.camel.spi.ManagementStrategy;
import org.apache.camel.spi.NodeIdFactory;
import org.apache.camel.spi.PackageScanClassResolver;
import org.apache.camel.spi.ProcessorFactory;
import org.apache.camel.spi.Registry;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.RestRegistry;
import org.apache.camel.spi.RouteContext;
import org.apache.camel.spi.RoutePolicyFactory;
import org.apache.camel.spi.RouteStartupOrder;
import org.apache.camel.spi.RuntimeEndpointRegistry;
import org.apache.camel.spi.ServicePool;
import org.apache.camel.spi.ShutdownStrategy;
import org.apache.camel.spi.StreamCachingStrategy;
import org.apache.camel.spi.TypeConverterRegistry;
import org.apache.camel.spi.UnitOfWorkFactory;
import org.apache.camel.spi.UuidGenerator;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.util.CamelContextHelper;
import org.apache.camel.util.EndpointHelper;
import org.apache.camel.util.EventHelper;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.LoadPropertiesException;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ServiceHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.URISupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents the context used to configure routes and the policies to use.
*
* @version
*/
@SuppressWarnings("deprecation")
public class DefaultCamelContext extends ServiceSupport implements ModelCamelContext, SuspendableService {
private final Logger log = LoggerFactory.getLogger(getClass());
private JAXBContext jaxbContext;
private CamelContextNameStrategy nameStrategy = new DefaultCamelContextNameStrategy();
private ManagementNameStrategy managementNameStrategy = new DefaultManagementNameStrategy(this);
private String managementName;
private ClassLoader applicationContextClassLoader;
private Map<EndpointKey, Endpoint> endpoints;
private final AtomicInteger endpointKeyCounter = new AtomicInteger();
private final List<EndpointStrategy> endpointStrategies = new ArrayList<EndpointStrategy>();
private final Map<String, Component> components = new HashMap<String, Component>();
private final Set<Route> routes = new LinkedHashSet<Route>();
private final List<Service> servicesToClose = new CopyOnWriteArrayList<Service>();
private final Set<StartupListener> startupListeners = new LinkedHashSet<StartupListener>();
private TypeConverter typeConverter;
private TypeConverterRegistry typeConverterRegistry;
private Injector injector;
private ComponentResolver componentResolver;
private boolean autoCreateComponents = true;
private LanguageResolver languageResolver = new DefaultLanguageResolver();
private final Map<String, Language> languages = new HashMap<String, Language>();
private Registry registry;
private List<LifecycleStrategy> lifecycleStrategies = new CopyOnWriteArrayList<LifecycleStrategy>();
private ManagementStrategy managementStrategy;
private ManagementMBeanAssembler managementMBeanAssembler;
private final List<RouteDefinition> routeDefinitions = new ArrayList<RouteDefinition>();
private final List<RestDefinition> restDefinitions = new ArrayList<RestDefinition>();
private RestConfiguration restConfiguration = new RestConfiguration();
private RestRegistry restRegistry = new DefaultRestRegistry();
private List<InterceptStrategy> interceptStrategies = new ArrayList<InterceptStrategy>();
private List<RoutePolicyFactory> routePolicyFactories = new ArrayList<RoutePolicyFactory>();
// special flags to control the first startup which can are special
private volatile boolean firstStartDone;
private volatile boolean doNotStartRoutesOnFirstStart;
private final ThreadLocal<Boolean> isStartingRoutes = new ThreadLocal<Boolean>();
private final ThreadLocal<Boolean> isSetupRoutes = new ThreadLocal<Boolean>();
private Boolean autoStartup = Boolean.TRUE;
private Boolean trace = Boolean.FALSE;
private Boolean messageHistory = Boolean.TRUE;
private Boolean streamCache = Boolean.FALSE;
private Boolean handleFault = Boolean.FALSE;
private Boolean disableJMX = Boolean.FALSE;
private Boolean lazyLoadTypeConverters = Boolean.FALSE;
private Boolean typeConverterStatisticsEnabled = Boolean.FALSE;
private Boolean useMDCLogging = Boolean.FALSE;
private Boolean useBreadcrumb = Boolean.TRUE;
private Boolean allowUseOriginalMessage = Boolean.TRUE;
private Long delay;
private ErrorHandlerFactory errorHandlerBuilder;
private final Object errorHandlerExecutorServiceLock = new Object();
private ScheduledExecutorService errorHandlerExecutorService;
private Map<String, DataFormatDefinition> dataFormats = new HashMap<String, DataFormatDefinition>();
private DataFormatResolver dataFormatResolver = new DefaultDataFormatResolver();
private Map<String, String> properties = new HashMap<String, String>();
private FactoryFinderResolver factoryFinderResolver = new DefaultFactoryFinderResolver();
private FactoryFinder defaultFactoryFinder;
private PropertiesComponent propertiesComponent;
private StreamCachingStrategy streamCachingStrategy;
private final Map<String, FactoryFinder> factories = new HashMap<String, FactoryFinder>();
private final Map<String, RouteService> routeServices = new LinkedHashMap<String, RouteService>();
private final Map<String, RouteService> suspendedRouteServices = new LinkedHashMap<String, RouteService>();
private ClassResolver classResolver = new DefaultClassResolver();
private PackageScanClassResolver packageScanClassResolver;
// we use a capacity of 100 per endpoint, so for the same endpoint we have at most 100 producers in the pool
// so if we have 6 endpoints in the pool, we can have 6 x 100 producers in total
private ServicePool<Endpoint, Producer> producerServicePool = new SharedProducerServicePool(100);
private NodeIdFactory nodeIdFactory = new DefaultNodeIdFactory();
private ProcessorFactory processorFactory;
private InterceptStrategy defaultTracer;
private InterceptStrategy defaultBacklogTracer;
private InterceptStrategy defaultBacklogDebugger;
private InflightRepository inflightRepository = new DefaultInflightRepository();
private RuntimeEndpointRegistry runtimeEndpointRegistry = new DefaultRuntimeEndpointRegistry();
private final List<RouteStartupOrder> routeStartupOrder = new ArrayList<RouteStartupOrder>();
// start auto assigning route ids using numbering 1000 and upwards
private int defaultRouteStartupOrder = 1000;
private ShutdownStrategy shutdownStrategy = new DefaultShutdownStrategy(this);
private ShutdownRoute shutdownRoute = ShutdownRoute.Default;
private ShutdownRunningTask shutdownRunningTask = ShutdownRunningTask.CompleteCurrentTaskOnly;
private ExecutorServiceManager executorServiceManager;
private Debugger debugger;
private UuidGenerator uuidGenerator = createDefaultUuidGenerator();
private UnitOfWorkFactory unitOfWorkFactory = new DefaultUnitOfWorkFactory();
private final StopWatch stopWatch = new StopWatch(false);
private Date startDate;
/**
* Creates the {@link CamelContext} using {@link JndiRegistry} as registry,
* but will silently fallback and use {@link SimpleRegistry} if JNDI cannot be used.
* <p/>
* Use one of the other constructors to force use an explicit registry / JNDI.
*/
public DefaultCamelContext() {
this.executorServiceManager = new DefaultExecutorServiceManager(this);
// create endpoint registry at first since end users may access endpoints before CamelContext is started
this.endpoints = new EndpointRegistry(this);
// use WebSphere specific resolver if running on WebSphere
if (WebSpherePackageScanClassResolver.isWebSphereClassLoader(this.getClass().getClassLoader())) {
log.info("Using WebSphere specific PackageScanClassResolver");
packageScanClassResolver = new WebSpherePackageScanClassResolver("META-INF/services/org/apache/camel/TypeConverter");
} else {
packageScanClassResolver = new DefaultPackageScanClassResolver();
}
// setup management strategy first since end users may use it to add event notifiers
// using the management strategy before the CamelContext has been started
this.managementStrategy = createManagementStrategy();
this.managementMBeanAssembler = createManagementMBeanAssembler();
Container.Instance.manage(this);
}
/**
* Creates the {@link CamelContext} using the given JNDI context as the registry
*
* @param jndiContext the JNDI context
*/
public DefaultCamelContext(Context jndiContext) {
this();
setJndiContext(jndiContext);
}
/**
* Creates the {@link CamelContext} using the given registry
*
* @param registry the registry
*/
public DefaultCamelContext(Registry registry) {
this();
setRegistry(registry);
}
public String getName() {
return getNameStrategy().getName();
}
/**
* Sets the name of the this context.
*
* @param name the name
*/
public void setName(String name) {
// use an explicit name strategy since an explicit name was provided to be used
this.nameStrategy = new ExplicitCamelContextNameStrategy(name);
}
public CamelContextNameStrategy getNameStrategy() {
return nameStrategy;
}
public void setNameStrategy(CamelContextNameStrategy nameStrategy) {
this.nameStrategy = nameStrategy;
}
public ManagementNameStrategy getManagementNameStrategy() {
return managementNameStrategy;
}
public void setManagementNameStrategy(ManagementNameStrategy managementNameStrategy) {
this.managementNameStrategy = managementNameStrategy;
}
public String getManagementName() {
return managementName;
}
public void setManagementName(String managementName) {
this.managementName = managementName;
}
public Component hasComponent(String componentName) {
return components.get(componentName);
}
public void addComponent(String componentName, final Component component) {
ObjectHelper.notNull(component, "component");
synchronized (components) {
if (components.containsKey(componentName)) {
throw new IllegalArgumentException("Cannot add component as its already previously added: " + componentName);
}
component.setCamelContext(this);
components.put(componentName, component);
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onComponentAdd(componentName, component);
}
// keep reference to properties component up to date
if (component instanceof PropertiesComponent && "properties".equals(componentName)) {
propertiesComponent = (PropertiesComponent) component;
}
}
}
public Component getComponent(String name) {
return getComponent(name, autoCreateComponents);
}
public Component getComponent(String name, boolean autoCreateComponents) {
// synchronize the look up and auto create so that 2 threads can't
// concurrently auto create the same component.
synchronized (components) {
Component component = components.get(name);
if (component == null && autoCreateComponents) {
try {
if (log.isDebugEnabled()) {
log.debug("Using ComponentResolver: {} to resolve component with name: {}", getComponentResolver(), name);
}
component = getComponentResolver().resolveComponent(name, this);
if (component != null) {
addComponent(name, component);
if (isStarted() || isStarting()) {
// If the component is looked up after the context is started, lets start it up.
if (component instanceof Service) {
startService((Service)component);
}
}
}
} catch (Exception e) {
throw new RuntimeCamelException("Cannot auto create component: " + name, e);
}
}
log.trace("getComponent({}) -> {}", name, component);
return component;
}
}
public <T extends Component> T getComponent(String name, Class<T> componentType) {
Component component = getComponent(name);
if (componentType.isInstance(component)) {
return componentType.cast(component);
} else {
String message;
if (component == null) {
message = "Did not find component given by the name: " + name;
} else {
message = "Found component of type: " + component.getClass() + " instead of expected: " + componentType;
}
throw new IllegalArgumentException(message);
}
}
public Component removeComponent(String componentName) {
synchronized (components) {
Component oldComponent = components.remove(componentName);
if (oldComponent != null) {
try {
stopServices(oldComponent);
} catch (Exception e) {
log.warn("Error stopping component " + oldComponent + ". This exception will be ignored.", e);
}
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onComponentRemove(componentName, oldComponent);
}
}
// keep reference to properties component up to date
if (oldComponent != null && "properties".equals(componentName)) {
propertiesComponent = null;
}
return oldComponent;
}
}
// Endpoint Management Methods
// -----------------------------------------------------------------------
public Collection<Endpoint> getEndpoints() {
return new ArrayList<Endpoint>(endpoints.values());
}
public Map<String, Endpoint> getEndpointMap() {
Map<String, Endpoint> answer = new TreeMap<String, Endpoint>();
for (Map.Entry<EndpointKey, Endpoint> entry : endpoints.entrySet()) {
answer.put(entry.getKey().get(), entry.getValue());
}
return answer;
}
public Endpoint hasEndpoint(String uri) {
return endpoints.get(getEndpointKey(uri));
}
public Endpoint addEndpoint(String uri, Endpoint endpoint) throws Exception {
Endpoint oldEndpoint;
startService(endpoint);
oldEndpoint = endpoints.remove(getEndpointKey(uri));
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onEndpointAdd(endpoint);
}
addEndpointToRegistry(uri, endpoint);
if (oldEndpoint != null) {
stopServices(oldEndpoint);
}
return oldEndpoint;
}
public Collection<Endpoint> removeEndpoints(String uri) throws Exception {
Collection<Endpoint> answer = new ArrayList<Endpoint>();
Endpoint oldEndpoint = endpoints.remove(getEndpointKey(uri));
if (oldEndpoint != null) {
answer.add(oldEndpoint);
stopServices(oldEndpoint);
} else {
for (Map.Entry<EndpointKey, Endpoint> entry : endpoints.entrySet()) {
oldEndpoint = entry.getValue();
if (EndpointHelper.matchEndpoint(this, oldEndpoint.getEndpointUri(), uri)) {
try {
stopServices(oldEndpoint);
} catch (Exception e) {
log.warn("Error stopping endpoint " + oldEndpoint + ". This exception will be ignored.", e);
}
answer.add(oldEndpoint);
endpoints.remove(entry.getKey());
}
}
}
// notify lifecycle its being removed
for (Endpoint endpoint : answer) {
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onEndpointRemove(endpoint);
}
}
return answer;
}
public Endpoint getEndpoint(String uri) {
ObjectHelper.notEmpty(uri, "uri");
log.trace("Getting endpoint with uri: {}", uri);
// in case path has property placeholders then try to let property component resolve those
try {
uri = resolvePropertyPlaceholders(uri);
} catch (Exception e) {
throw new ResolveEndpointFailedException(uri, e);
}
final String rawUri = uri;
// normalize uri so we can do endpoint hits with minor mistakes and parameters is not in the same order
uri = normalizeEndpointUri(uri);
log.trace("Getting endpoint with raw uri: {}, normalized uri: {}", rawUri, uri);
Endpoint answer;
String scheme = null;
EndpointKey key = getEndpointKey(uri);
answer = endpoints.get(key);
if (answer == null) {
try {
// Use the URI prefix to find the component.
String splitURI[] = ObjectHelper.splitOnCharacter(uri, ":", 2);
if (splitURI[1] != null) {
scheme = splitURI[0];
log.trace("Endpoint uri: {} is from component with name: {}", uri, scheme);
Component component = getComponent(scheme);
// Ask the component to resolve the endpoint.
if (component != null) {
log.trace("Creating endpoint from uri: {} using component: {}", uri, component);
// Have the component create the endpoint if it can.
if (component.useRawUri()) {
answer = component.createEndpoint(rawUri);
} else {
answer = component.createEndpoint(uri);
}
if (answer != null && log.isDebugEnabled()) {
log.debug("{} converted to endpoint: {} by component: {}", new Object[]{URISupport.sanitizeUri(uri), answer, component});
}
}
}
if (answer == null) {
// no component then try in registry and elsewhere
answer = createEndpoint(uri);
log.trace("No component to create endpoint from uri: {} fallback lookup in registry -> {}", uri, answer);
}
if (answer != null) {
addService(answer);
answer = addEndpointToRegistry(uri, answer);
}
} catch (Exception e) {
throw new ResolveEndpointFailedException(uri, e);
}
}
// unknown scheme
if (answer == null && scheme != null) {
throw new ResolveEndpointFailedException(uri, "No component found with scheme: " + scheme);
}
return answer;
}
public <T extends Endpoint> T getEndpoint(String name, Class<T> endpointType) {
Endpoint endpoint = getEndpoint(name);
if (endpoint == null) {
throw new NoSuchEndpointException(name);
}
if (endpoint instanceof InterceptSendToEndpoint) {
endpoint = ((InterceptSendToEndpoint) endpoint).getDelegate();
}
if (endpointType.isInstance(endpoint)) {
return endpointType.cast(endpoint);
} else {
throw new IllegalArgumentException("The endpoint is not of type: " + endpointType
+ " but is: " + endpoint.getClass().getCanonicalName());
}
}
public void addRegisterEndpointCallback(EndpointStrategy strategy) {
if (!endpointStrategies.contains(strategy)) {
// let it be invoked for already registered endpoints so it can catch-up.
endpointStrategies.add(strategy);
for (Endpoint endpoint : getEndpoints()) {
Endpoint newEndpoint = strategy.registerEndpoint(endpoint.getEndpointUri(), endpoint);
if (newEndpoint != null) {
// put will replace existing endpoint with the new endpoint
endpoints.put(getEndpointKey(endpoint.getEndpointUri()), newEndpoint);
}
}
}
}
/**
* Strategy to add the given endpoint to the internal endpoint registry
*
* @param uri uri of the endpoint
* @param endpoint the endpoint to add
* @return the added endpoint
*/
protected Endpoint addEndpointToRegistry(String uri, Endpoint endpoint) {
ObjectHelper.notEmpty(uri, "uri");
ObjectHelper.notNull(endpoint, "endpoint");
// if there is endpoint strategies, then use the endpoints they return
// as this allows to intercept endpoints etc.
for (EndpointStrategy strategy : endpointStrategies) {
endpoint = strategy.registerEndpoint(uri, endpoint);
}
endpoints.put(getEndpointKey(uri, endpoint), endpoint);
return endpoint;
}
/**
* Normalize uri so we can do endpoint hits with minor mistakes and parameters is not in the same order.
*
* @param uri the uri
* @return normalized uri
* @throws ResolveEndpointFailedException if uri cannot be normalized
*/
protected static String normalizeEndpointUri(String uri) {
try {
uri = URISupport.normalizeUri(uri);
} catch (Exception e) {
throw new ResolveEndpointFailedException(uri, e);
}
return uri;
}
/**
* Gets the endpoint key to use for lookup or whe adding endpoints to the {@link EndpointRegistry}
*
* @param uri the endpoint uri
* @return the key
*/
protected EndpointKey getEndpointKey(String uri) {
return new EndpointKey(uri);
}
/**
* Gets the endpoint key to use for lookup or whe adding endpoints to the {@link EndpointRegistry}
*
* @param uri the endpoint uri
* @param endpoint the endpoint
* @return the key
*/
protected EndpointKey getEndpointKey(String uri, Endpoint endpoint) {
if (endpoint != null && !endpoint.isSingleton()) {
int counter = endpointKeyCounter.incrementAndGet();
return new EndpointKey(uri + ":" + counter);
} else {
return new EndpointKey(uri);
}
}
// Route Management Methods
// -----------------------------------------------------------------------
public List<RouteStartupOrder> getRouteStartupOrder() {
return routeStartupOrder;
}
public List<Route> getRoutes() {
// lets return a copy of the collection as objects are removed later when services are stopped
if (routes.isEmpty()) {
return Collections.emptyList();
} else {
return new ArrayList<Route>(routes);
}
}
public Route getRoute(String id) {
for (Route route : getRoutes()) {
if (route.getId().equals(id)) {
return route;
}
}
return null;
}
@Deprecated
public void setRoutes(List<Route> routes) {
throw new UnsupportedOperationException("Overriding existing routes is not supported yet, use addRouteCollection instead");
}
synchronized void removeRouteCollection(Collection<Route> routes) {
this.routes.removeAll(routes);
}
synchronized void addRouteCollection(Collection<Route> routes) throws Exception {
this.routes.addAll(routes);
}
public void addRoutes(RoutesBuilder builder) throws Exception {
log.debug("Adding routes from builder: {}", builder);
// lets now add the routes from the builder
builder.addRoutesToCamelContext(this);
}
public synchronized RoutesDefinition loadRoutesDefinition(InputStream is) throws Exception {
// load routes using JAXB
if (jaxbContext == null) {
// must use classloader from CamelContext to have JAXB working
jaxbContext = JAXBContext.newInstance(Constants.JAXB_CONTEXT_PACKAGES, CamelContext.class.getClassLoader());
}
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Object result = unmarshaller.unmarshal(is);
if (result == null) {
throw new IOException("Cannot unmarshal to routes using JAXB from input stream: " + is);
}
// can either be routes or a single route
RoutesDefinition answer = null;
if (result instanceof RouteDefinition) {
RouteDefinition route = (RouteDefinition) result;
answer = new RoutesDefinition();
answer.getRoutes().add(route);
} else if (result instanceof RoutesDefinition) {
answer = (RoutesDefinition) result;
} else {
throw new IllegalArgumentException("Unmarshalled object is an unsupported type: " + ObjectHelper.className(result) + " -> " + result);
}
return answer;
}
public synchronized void addRouteDefinitions(Collection<RouteDefinition> routeDefinitions) throws Exception {
if (routeDefinitions == null || routeDefinitions.isEmpty()) {
return;
}
for (RouteDefinition routeDefinition : routeDefinitions) {
removeRouteDefinition(routeDefinition);
}
this.routeDefinitions.addAll(routeDefinitions);
if (shouldStartRoutes()) {
startRouteDefinitions(routeDefinitions);
}
}
public void addRouteDefinition(RouteDefinition routeDefinition) throws Exception {
addRouteDefinitions(Arrays.asList(routeDefinition));
}
/**
* Removes the route definition with the given key.
*
* @return true if one or more routes was removed
*/
protected boolean removeRouteDefinition(String key) {
boolean answer = false;
Iterator<RouteDefinition> iter = routeDefinitions.iterator();
while (iter.hasNext()) {
RouteDefinition route = iter.next();
if (route.idOrCreate(nodeIdFactory).equals(key)) {
iter.remove();
answer = true;
}
}
return answer;
}
public synchronized void removeRouteDefinitions(Collection<RouteDefinition> routeDefinitions) throws Exception {
for (RouteDefinition routeDefinition : routeDefinitions) {
removeRouteDefinition(routeDefinition);
}
}
public synchronized void removeRouteDefinition(RouteDefinition routeDefinition) throws Exception {
String id = routeDefinition.idOrCreate(nodeIdFactory);
stopRoute(id);
removeRoute(id);
this.routeDefinitions.remove(routeDefinition);
}
public ServiceStatus getRouteStatus(String key) {
RouteService routeService = routeServices.get(key);
if (routeService != null) {
return routeService.getStatus();
}
return null;
}
public void startRoute(RouteDefinition route) throws Exception {
// assign ids to the routes and validate that the id's is all unique
RouteDefinitionHelper.forceAssignIds(this, routeDefinitions);
String duplicate = RouteDefinitionHelper.validateUniqueIds(route, routeDefinitions);
if (duplicate != null) {
throw new FailedToStartRouteException(route.getId(), "duplicate id detected: " + duplicate + ". Please correct ids to be unique among all your routes.");
}
// indicate we are staring the route using this thread so
// we are able to query this if needed
isStartingRoutes.set(true);
try {
// must ensure route is prepared, before we can start it
route.prepare(this);
List<Route> routes = new ArrayList<Route>();
List<RouteContext> routeContexts = route.addRoutes(this, routes);
RouteService routeService = new RouteService(this, route, routeContexts, routes);
startRouteService(routeService, true);
} finally {
// we are done staring routes
isStartingRoutes.remove();
}
}
public boolean isStartingRoutes() {
Boolean answer = isStartingRoutes.get();
return answer != null && answer;
}
public boolean isSetupRoutes() {
Boolean answer = isSetupRoutes.get();
return answer != null && answer;
}
public void stopRoute(RouteDefinition route) throws Exception {
stopRoute(route.idOrCreate(nodeIdFactory));
}
public void startAllRoutes() throws Exception {
doStartOrResumeRoutes(routeServices, true, true, false, false);
}
public synchronized void startRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
startRouteService(routeService, false);
}
}
public synchronized void resumeRoute(String routeId) throws Exception {
if (!routeSupportsSuspension(routeId)) {
// start route if suspension is not supported
startRoute(routeId);
return;
}
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
resumeRouteService(routeService);
}
}
public synchronized boolean stopRoute(String routeId, long timeout, TimeUnit timeUnit, boolean abortAfterTimeout) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
RouteStartupOrder route = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
boolean completed = getShutdownStrategy().shutdown(this, route, timeout, timeUnit, abortAfterTimeout);
if (completed) {
// must stop route service as well
stopRouteService(routeService, false);
} else {
// shutdown was aborted, make sure route is re-started properly
startRouteService(routeService, false);
}
return completed;
}
return false;
}
public synchronized void stopRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes);
// must stop route service as well
stopRouteService(routeService, false);
}
}
public synchronized void stopRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes, timeout, timeUnit);
// must stop route service as well
stopRouteService(routeService, false);
}
}
public synchronized void shutdownRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes);
// must stop route service as well (and remove the routes from management)
stopRouteService(routeService, true);
}
}
public synchronized void shutdownRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes, timeout, timeUnit);
// must stop route service as well (and remove the routes from management)
stopRouteService(routeService, true);
}
}
public synchronized boolean removeRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
if (getRouteStatus(routeId).isStopped()) {
routeService.setRemovingRoutes(true);
shutdownRouteService(routeService);
removeRouteDefinition(routeId);
routeServices.remove(routeId);
// remove route from startup order as well, as it was removed
Iterator<RouteStartupOrder> it = routeStartupOrder.iterator();
while (it.hasNext()) {
RouteStartupOrder order = it.next();
if (order.getRoute().getId().equals(routeId)) {
it.remove();
}
}
return true;
} else {
return false;
}
}
return false;
}
public synchronized void suspendRoute(String routeId) throws Exception {
if (!routeSupportsSuspension(routeId)) {
// stop if we suspend is not supported
stopRoute(routeId);
return;
}
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().suspend(this, routes);
// must suspend route service as well
suspendRouteService(routeService);
}
}
public synchronized void suspendRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception {
if (!routeSupportsSuspension(routeId)) {
stopRoute(routeId, timeout, timeUnit);
return;
}
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().suspend(this, routes, timeout, timeUnit);
// must suspend route service as well
suspendRouteService(routeService);
}
}
public void addService(Object object) throws Exception {
addService(object, true);
}
public void addService(Object object, boolean closeOnShutdown) throws Exception {
doAddService(object, closeOnShutdown);
}
private void doAddService(Object object, boolean closeOnShutdown) throws Exception {
// inject CamelContext
if (object instanceof CamelContextAware) {
CamelContextAware aware = (CamelContextAware) object;
aware.setCamelContext(this);
}
if (object instanceof Service) {
Service service = (Service) object;
for (LifecycleStrategy strategy : lifecycleStrategies) {
if (service instanceof Endpoint) {
// use specialized endpoint add
strategy.onEndpointAdd((Endpoint) service);
} else {
strategy.onServiceAdd(this, service, null);
}
}
// only add to services to close if its a singleton
// otherwise we could for example end up with a lot of prototype scope endpoints
boolean singleton = true; // assume singleton by default
if (service instanceof IsSingleton) {
singleton = ((IsSingleton) service).isSingleton();
}
// do not add endpoints as they have their own list
if (singleton && !(service instanceof Endpoint)) {
// only add to list of services to close if its not already there
if (closeOnShutdown && !hasService(service)) {
servicesToClose.add(service);
}
}
}
// and then ensure service is started (as stated in the javadoc)
if (object instanceof Service) {
startService((Service)object);
} else if (object instanceof Collection<?>) {
startServices((Collection<?>)object);
}
}
public boolean removeService(Object object) throws Exception {
if (object instanceof Service) {
Service service = (Service) object;
for (LifecycleStrategy strategy : lifecycleStrategies) {
if (service instanceof Endpoint) {
// use specialized endpoint remove
strategy.onEndpointRemove((Endpoint) service);
} else {
strategy.onServiceRemove(this, service, null);
}
}
return servicesToClose.remove(service);
}
return false;
}
public boolean hasService(Object object) {
if (object instanceof Service) {
Service service = (Service) object;
return servicesToClose.contains(service);
}
return false;
}
@Override
public <T> T hasService(Class<T> type) {
for (Service service : servicesToClose) {
if (type.isInstance(service)) {
return type.cast(service);
}
}
return null;
}
public void addStartupListener(StartupListener listener) throws Exception {
// either add to listener so we can invoke then later when CamelContext has been started
// or invoke the callback right now
if (isStarted()) {
listener.onCamelContextStarted(this, true);
} else {
startupListeners.add(listener);
}
}
public Map<String, Properties> findComponents() throws LoadPropertiesException, IOException {
return CamelContextHelper.findComponents(this);
}
public String getComponentDocumentation(String componentName) throws IOException {
String packageName = sanitizeComponentName(componentName);
String path = CamelContextHelper.COMPONENT_DOCUMENTATION_PREFIX + packageName + "/" + componentName + ".html";
ClassResolver resolver = getClassResolver();
InputStream inputStream = resolver.loadResourceAsStream(path);
log.debug("Loading component documentation for: {} using class resolver: {} -> {}", new Object[]{componentName, resolver, inputStream});
if (inputStream != null) {
try {
return IOHelper.loadText(inputStream);
} finally {
IOHelper.close(inputStream);
}
}
return null;
}
/**
* Sanitizes the component name by removing dash (-) in the name, when using the component name to load
* resources from the classpath.
*/
private static String sanitizeComponentName(String componentName) {
// the ftp components are in a special package
if ("ftp".equals(componentName) || "ftps".equals(componentName) || "sftp".equals(componentName)) {
return "file/remote";
} else if ("cxfrs".equals(componentName)) {
return "cxf/jaxrs";
} else if ("gauth".equals(componentName) || "ghttp".equals(componentName) || "glogin".equals(componentName)
|| "gmail".equals(componentName) || "gtask".equals(componentName)) {
return "gae/" + componentName.substring(1);
} else if ("atmosphere-websocket".equals(componentName)) {
return "atmosphere/websocket";
} else if ("netty-http".equals(componentName)) {
return "netty/http";
} else if ("netty4-http".equals(componentName)) {
return "netty4/http";
}
return componentName.replaceAll("-", "");
}
public String createRouteStaticEndpointJson(String routeId) {
// lets include dynamic as well as we want as much data as possible
return createRouteStaticEndpointJson(routeId, true);
}
public String createRouteStaticEndpointJson(String routeId, boolean includeDynamic) {
List<RouteDefinition> routes = new ArrayList<RouteDefinition>();
if (routeId != null) {
RouteDefinition route = getRouteDefinition(routeId);
if (route == null) {
throw new IllegalArgumentException("Route with id " + routeId + " does not exist");
}
routes.add(route);
} else {
routes.addAll(getRouteDefinitions());
}
StringBuilder buffer = new StringBuilder("{\n \"routes\": {");
boolean firstRoute = true;
for (RouteDefinition route : routes) {
if (!firstRoute) {
buffer.append("\n },");
} else {
firstRoute = false;
}
String id = route.getId();
buffer.append("\n \"" + id + "\": {");
buffer.append("\n \"inputs\": [");
// for inputs we do not need to check dynamic as we have the data from the route definition
Set<String> inputs = RouteDefinitionHelper.gatherAllStaticEndpointUris(this, route, true, false);
boolean first = true;
for (String input : inputs) {
if (!first) {
buffer.append(",");
} else {
first = false;
}
buffer.append("\n ");
buffer.append(StringHelper.toJson("uri", input, true));
}
buffer.append("\n ]");
buffer.append(",");
buffer.append("\n \"outputs\": [");
Set<String> outputs = RouteDefinitionHelper.gatherAllEndpointUris(this, route, false, true, includeDynamic);
first = true;
for (String output : outputs) {
if (!first) {
buffer.append(",");
} else {
first = false;
}
buffer.append("\n ");
buffer.append(StringHelper.toJson("uri", output, true));
}
buffer.append("\n ]");
}
if (!firstRoute) {
buffer.append("\n }");
}
buffer.append("\n }\n}\n");
return buffer.toString();
}
// Helper methods
// -----------------------------------------------------------------------
public Language resolveLanguage(String language) {
Language answer;
synchronized (languages) {
answer = languages.get(language);
// check if the language is singleton, if so return the shared instance
if (answer instanceof IsSingleton) {
boolean singleton = ((IsSingleton) answer).isSingleton();
if (singleton) {
return answer;
}
}
// language not known or not singleton, then use resolver
answer = getLanguageResolver().resolveLanguage(language, this);
// inject CamelContext if aware
if (answer != null) {
if (answer instanceof CamelContextAware) {
((CamelContextAware) answer).setCamelContext(this);
}
if (answer instanceof Service) {
try {
startService((Service) answer);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
languages.put(language, answer);
}
}
return answer;
}
public String getPropertyPrefixToken() {
PropertiesComponent pc = getPropertiesComponent();
if (pc != null) {
return pc.getPrefixToken();
} else {
return null;
}
}
public String getPropertySuffixToken() {
PropertiesComponent pc = getPropertiesComponent();
if (pc != null) {
return pc.getSuffixToken();
} else {
return null;
}
}
public String resolvePropertyPlaceholders(String text) throws Exception {
// While it is more efficient to only do the lookup if we are sure we need the component,
// with custom tokens, we cannot know if the URI contains a property or not without having
// the component. We also lose fail-fast behavior for the missing component with this change.
PropertiesComponent pc = getPropertiesComponent();
// Do not parse uris that are designated for the properties component as it will handle that itself
if (text != null && !text.startsWith("properties:")) {
// No component, assume default tokens.
if (pc == null && text.contains(PropertiesComponent.DEFAULT_PREFIX_TOKEN)) {
// try to lookup component, as we may be initializing CamelContext itself
Component existing = lookupPropertiesComponent();
if (existing != null) {
if (existing instanceof PropertiesComponent) {
pc = (PropertiesComponent) existing;
} else {
// properties component must be expected type
throw new IllegalArgumentException("Found properties component of type: " + existing.getClass() + " instead of expected: " + PropertiesComponent.class);
}
}
if (pc != null) {
// the parser will throw exception if property key was not found
String answer = pc.parseUri(text);
log.debug("Resolved text: {} -> {}", text, answer);
return answer;
} else {
throw new IllegalArgumentException("PropertiesComponent with name properties must be defined"
+ " in CamelContext to support property placeholders.");
}
// Component available, use actual tokens
} else if (pc != null && text.contains(pc.getPrefixToken())) {
// the parser will throw exception if property key was not found
String answer = pc.parseUri(text);
log.debug("Resolved text: {} -> {}", text, answer);
return answer;
}
}
// return original text as is
return text;
}
// Properties
// -----------------------------------------------------------------------
public TypeConverter getTypeConverter() {
if (typeConverter == null) {
synchronized (this) {
// we can synchronize on this as there is only one instance
// of the camel context (its the container)
typeConverter = createTypeConverter();
try {
// must add service eager
addService(typeConverter);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
}
return typeConverter;
}
public void setTypeConverter(TypeConverter typeConverter) {
this.typeConverter = typeConverter;
try {
// must add service eager
addService(typeConverter);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
public TypeConverterRegistry getTypeConverterRegistry() {
if (typeConverterRegistry == null) {
// init type converter as its lazy
if (typeConverter == null) {
getTypeConverter();
}
if (typeConverter instanceof TypeConverterRegistry) {
typeConverterRegistry = (TypeConverterRegistry) typeConverter;
}
}
return typeConverterRegistry;
}
public void setTypeConverterRegistry(TypeConverterRegistry typeConverterRegistry) {
this.typeConverterRegistry = typeConverterRegistry;
}
public Injector getInjector() {
if (injector == null) {
injector = createInjector();
}
return injector;
}
public void setInjector(Injector injector) {
this.injector = injector;
}
public ManagementMBeanAssembler getManagementMBeanAssembler() {
return managementMBeanAssembler;
}
public void setManagementMBeanAssembler(ManagementMBeanAssembler managementMBeanAssembler) {
this.managementMBeanAssembler = managementMBeanAssembler;
}
public ComponentResolver getComponentResolver() {
if (componentResolver == null) {
componentResolver = createComponentResolver();
}
return componentResolver;
}
public void setComponentResolver(ComponentResolver componentResolver) {
this.componentResolver = componentResolver;
}
public LanguageResolver getLanguageResolver() {
if (languageResolver == null) {
languageResolver = new DefaultLanguageResolver();
}
return languageResolver;
}
public void setLanguageResolver(LanguageResolver languageResolver) {
this.languageResolver = languageResolver;
}
public boolean isAutoCreateComponents() {
return autoCreateComponents;
}
public void setAutoCreateComponents(boolean autoCreateComponents) {
this.autoCreateComponents = autoCreateComponents;
}
public Registry getRegistry() {
if (registry == null) {
registry = createRegistry();
setRegistry(registry);
}
return registry;
}
public <T> T getRegistry(Class<T> type) {
Registry reg = getRegistry();
// unwrap the property placeholder delegate
if (reg instanceof PropertyPlaceholderDelegateRegistry) {
reg = ((PropertyPlaceholderDelegateRegistry) reg).getRegistry();
}
if (type.isAssignableFrom(reg.getClass())) {
return type.cast(reg);
} else if (reg instanceof CompositeRegistry) {
List<Registry> list = ((CompositeRegistry) reg).getRegistryList();
for (Registry r : list) {
if (type.isAssignableFrom(r.getClass())) {
return type.cast(r);
}
}
}
return null;
}
/**
* Sets the registry to the given JNDI context
*
* @param jndiContext is the JNDI context to use as the registry
* @see #setRegistry(org.apache.camel.spi.Registry)
*/
public void setJndiContext(Context jndiContext) {
setRegistry(new JndiRegistry(jndiContext));
}
public void setRegistry(Registry registry) {
// wrap the registry so we always do property placeholder lookups
if (!(registry instanceof PropertyPlaceholderDelegateRegistry)) {
registry = new PropertyPlaceholderDelegateRegistry(this, registry);
}
this.registry = registry;
}
public List<LifecycleStrategy> getLifecycleStrategies() {
return lifecycleStrategies;
}
public void setLifecycleStrategies(List<LifecycleStrategy> lifecycleStrategies) {
this.lifecycleStrategies = lifecycleStrategies;
}
public void addLifecycleStrategy(LifecycleStrategy lifecycleStrategy) {
this.lifecycleStrategies.add(lifecycleStrategy);
}
public void setupRoutes(boolean done) {
if (done) {
isSetupRoutes.remove();
} else {
isSetupRoutes.set(true);
}
}
public synchronized List<RouteDefinition> getRouteDefinitions() {
return routeDefinitions;
}
public synchronized RouteDefinition getRouteDefinition(String id) {
for (RouteDefinition route : routeDefinitions) {
if (route.getId().equals(id)) {
return route;
}
}
return null;
}
public synchronized List<RestDefinition> getRestDefinitions() {
return restDefinitions;
}
public void addRestDefinitions(Collection<RestDefinition> restDefinitions) throws Exception {
if (restDefinitions == null || restDefinitions.isEmpty()) {
return;
}
this.restDefinitions.addAll(restDefinitions);
// convert rests into routes so we reuse routes for runtime
List<RouteDefinition> routes = new ArrayList<RouteDefinition>();
for (RestDefinition rest : restDefinitions) {
routes.addAll(rest.asRouteDefinition(this));
}
addRouteDefinitions(routes);
}
public RestConfiguration getRestConfiguration() {
return restConfiguration;
}
public void setRestConfiguration(RestConfiguration restConfiguration) {
this.restConfiguration = restConfiguration;
}
public List<InterceptStrategy> getInterceptStrategies() {
return interceptStrategies;
}
public void setInterceptStrategies(List<InterceptStrategy> interceptStrategies) {
this.interceptStrategies = interceptStrategies;
}
public void addInterceptStrategy(InterceptStrategy interceptStrategy) {
getInterceptStrategies().add(interceptStrategy);
// for backwards compatible or if user add them here instead of the setXXX methods
if (interceptStrategy instanceof Tracer) {
setTracing(true);
} else if (interceptStrategy instanceof HandleFault) {
setHandleFault(true);
} else if (interceptStrategy instanceof StreamCaching) {
setStreamCaching(true);
} else if (interceptStrategy instanceof Delayer) {
setDelayer(((Delayer)interceptStrategy).getDelay());
}
}
public List<RoutePolicyFactory> getRoutePolicyFactories() {
return routePolicyFactories;
}
public void setRoutePolicyFactories(List<RoutePolicyFactory> routePolicyFactories) {
this.routePolicyFactories = routePolicyFactories;
}
public void addRoutePolicyFactory(RoutePolicyFactory routePolicyFactory) {
getRoutePolicyFactories().add(routePolicyFactory);
}
public void setStreamCaching(Boolean cache) {
this.streamCache = cache;
}
public Boolean isStreamCaching() {
return streamCache;
}
public void setTracing(Boolean tracing) {
this.trace = tracing;
}
public Boolean isTracing() {
return trace;
}
public Boolean isMessageHistory() {
return messageHistory;
}
public void setMessageHistory(Boolean messageHistory) {
this.messageHistory = messageHistory;
}
public Boolean isHandleFault() {
return handleFault;
}
public void setHandleFault(Boolean handleFault) {
this.handleFault = handleFault;
}
public Long getDelayer() {
return delay;
}
public void setDelayer(Long delay) {
this.delay = delay;
}
public ProducerTemplate createProducerTemplate() {
int size = CamelContextHelper.getMaximumCachePoolSize(this);
return createProducerTemplate(size);
}
public ProducerTemplate createProducerTemplate(int maximumCacheSize) {
DefaultProducerTemplate answer = new DefaultProducerTemplate(this);
answer.setMaximumCacheSize(maximumCacheSize);
// start it so its ready to use
try {
startService(answer);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
return answer;
}
public ConsumerTemplate createConsumerTemplate() {
int size = CamelContextHelper.getMaximumCachePoolSize(this);
return createConsumerTemplate(size);
}
public ConsumerTemplate createConsumerTemplate(int maximumCacheSize) {
DefaultConsumerTemplate answer = new DefaultConsumerTemplate(this);
answer.setMaximumCacheSize(maximumCacheSize);
// start it so its ready to use
try {
startService(answer);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
return answer;
}
public ErrorHandlerBuilder getErrorHandlerBuilder() {
return (ErrorHandlerBuilder)errorHandlerBuilder;
}
public void setErrorHandlerBuilder(ErrorHandlerFactory errorHandlerBuilder) {
this.errorHandlerBuilder = errorHandlerBuilder;
}
public ScheduledExecutorService getErrorHandlerExecutorService() {
synchronized (errorHandlerExecutorServiceLock) {
if (errorHandlerExecutorService == null) {
// setup default thread pool for error handler
errorHandlerExecutorService = getExecutorServiceManager().newDefaultScheduledThreadPool("ErrorHandlerRedeliveryThreadPool", "ErrorHandlerRedeliveryTask");
}
}
return errorHandlerExecutorService;
}
public void setProducerServicePool(ServicePool<Endpoint, Producer> producerServicePool) {
this.producerServicePool = producerServicePool;
}
public ServicePool<Endpoint, Producer> getProducerServicePool() {
return producerServicePool;
}
public UnitOfWorkFactory getUnitOfWorkFactory() {
return unitOfWorkFactory;
}
public void setUnitOfWorkFactory(UnitOfWorkFactory unitOfWorkFactory) {
this.unitOfWorkFactory = unitOfWorkFactory;
}
public RuntimeEndpointRegistry getRuntimeEndpointRegistry() {
return runtimeEndpointRegistry;
}
public void setRuntimeEndpointRegistry(RuntimeEndpointRegistry runtimeEndpointRegistry) {
this.runtimeEndpointRegistry = runtimeEndpointRegistry;
}
public String getUptime() {
// compute and log uptime
if (startDate == null) {
return "not started";
}
long delta = new Date().getTime() - startDate.getTime();
return TimeUtils.printDuration(delta);
}
@Override
protected void doSuspend() throws Exception {
EventHelper.notifyCamelContextSuspending(this);
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is suspending");
StopWatch watch = new StopWatch();
// update list of started routes to be suspended
// because we only want to suspend started routes
// (so when we resume we only resume the routes which actually was suspended)
for (Map.Entry<String, RouteService> entry : getRouteServices().entrySet()) {
if (entry.getValue().getStatus().isStarted()) {
suspendedRouteServices.put(entry.getKey(), entry.getValue());
}
}
// assemble list of startup ordering so routes can be shutdown accordingly
List<RouteStartupOrder> orders = new ArrayList<RouteStartupOrder>();
for (Map.Entry<String, RouteService> entry : suspendedRouteServices.entrySet()) {
Route route = entry.getValue().getRoutes().iterator().next();
Integer order = entry.getValue().getRouteDefinition().getStartupOrder();
if (order == null) {
order = defaultRouteStartupOrder++;
}
orders.add(new DefaultRouteStartupOrder(order, route, entry.getValue()));
}
// suspend routes using the shutdown strategy so it can shutdown in correct order
// routes which doesn't support suspension will be stopped instead
getShutdownStrategy().suspend(this, orders);
// mark the route services as suspended or stopped
for (RouteService service : suspendedRouteServices.values()) {
if (routeSupportsSuspension(service.getId())) {
service.suspend();
} else {
service.stop();
}
}
watch.stop();
if (log.isInfoEnabled()) {
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is suspended in " + TimeUtils.printDuration(watch.taken()));
}
EventHelper.notifyCamelContextSuspended(this);
}
@Override
protected void doResume() throws Exception {
try {
EventHelper.notifyCamelContextResuming(this);
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is resuming");
StopWatch watch = new StopWatch();
// start the suspended routes (do not check for route clashes, and indicate)
doStartOrResumeRoutes(suspendedRouteServices, false, true, true, false);
// mark the route services as resumed (will be marked as started) as well
for (RouteService service : suspendedRouteServices.values()) {
if (routeSupportsSuspension(service.getId())) {
service.resume();
} else {
service.start();
}
}
watch.stop();
if (log.isInfoEnabled()) {
log.info("Resumed " + suspendedRouteServices.size() + " routes");
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") resumed in " + TimeUtils.printDuration(watch.taken()));
}
// and clear the list as they have been resumed
suspendedRouteServices.clear();
EventHelper.notifyCamelContextResumed(this);
} catch (Exception e) {
EventHelper.notifyCamelContextResumeFailed(this, e);
throw e;
}
}
public void start() throws Exception {
startDate = new Date();
stopWatch.restart();
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is starting");
doNotStartRoutesOnFirstStart = !firstStartDone && !isAutoStartup();
// if the context was configured with auto startup = false, and we are already started,
// then we may need to start the routes on the 2nd start call
if (firstStartDone && !isAutoStartup() && isStarted()) {
// invoke this logic to warm up the routes and if possible also start the routes
doStartOrResumeRoutes(routeServices, true, true, false, true);
}
// super will invoke doStart which will prepare internal services and start routes etc.
try {
firstStartDone = true;
super.start();
} catch (VetoCamelContextStartException e) {
if (e.isRethrowException()) {
throw e;
} else {
log.info("CamelContext ({}) vetoed to not start due {}", getName(), e.getMessage());
// swallow exception and change state of this camel context to stopped
stop();
return;
}
}
stopWatch.stop();
if (log.isInfoEnabled()) {
// count how many routes are actually started
int started = 0;
for (Route route : getRoutes()) {
if (getRouteStatus(route.getId()).isStarted()) {
started++;
}
}
log.info("Total " + getRoutes().size() + " routes, of which " + started + " is started.");
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") started in " + TimeUtils.printDuration(stopWatch.taken()));
}
EventHelper.notifyCamelContextStarted(this);
}
// Implementation methods
// -----------------------------------------------------------------------
protected synchronized void doStart() throws Exception {
try {
doStartCamel();
} catch (Exception e) {
// fire event that we failed to start
EventHelper.notifyCamelContextStartupFailed(this, e);
// rethrow cause
throw e;
}
}
private void doStartCamel() throws Exception {
if (applicationContextClassLoader == null) {
// Using the TCCL as the default value of ApplicationClassLoader
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
// use the classloader that loaded this class
cl = this.getClass().getClassLoader();
}
setApplicationContextClassLoader(cl);
}
if (log.isDebugEnabled()) {
log.debug("Using ClassResolver={}, PackageScanClassResolver={}, ApplicationContextClassLoader={}",
new Object[]{getClassResolver(), getPackageScanClassResolver(), getApplicationContextClassLoader()});
}
if (isStreamCaching()) {
log.info("StreamCaching is enabled on CamelContext: {}", getName());
}
if (isTracing()) {
// tracing is added in the DefaultChannel so we can enable it on the fly
log.info("Tracing is enabled on CamelContext: {}", getName());
}
if (isUseMDCLogging()) {
// log if MDC has been enabled
log.info("MDC logging is enabled on CamelContext: {}", getName());
}
if (isHandleFault()) {
// only add a new handle fault if not already configured
if (HandleFault.getHandleFault(this) == null) {
log.info("HandleFault is enabled on CamelContext: {}", getName());
addInterceptStrategy(new HandleFault());
}
}
if (getDelayer() != null && getDelayer() > 0) {
log.info("Delayer is enabled with: {} ms. on CamelContext: {}", getDelayer(), getName());
}
// register debugger
if (getDebugger() != null) {
log.info("Debugger: {} is enabled on CamelContext: {}", getDebugger(), getName());
// register this camel context on the debugger
getDebugger().setCamelContext(this);
startService(getDebugger());
addInterceptStrategy(new Debug(getDebugger()));
}
// start management strategy before lifecycles are started
ManagementStrategy managementStrategy = getManagementStrategy();
// inject CamelContext if aware
if (managementStrategy instanceof CamelContextAware) {
((CamelContextAware) managementStrategy).setCamelContext(this);
}
ServiceHelper.startService(managementStrategy);
// start lifecycle strategies
ServiceHelper.startServices(lifecycleStrategies);
Iterator<LifecycleStrategy> it = lifecycleStrategies.iterator();
while (it.hasNext()) {
LifecycleStrategy strategy = it.next();
try {
strategy.onContextStart(this);
} catch (VetoCamelContextStartException e) {
// okay we should not start Camel since it was vetoed
log.warn("Lifecycle strategy vetoed starting CamelContext ({}) due {}", getName(), e.getMessage());
throw e;
} catch (Exception e) {
log.warn("Lifecycle strategy " + strategy + " failed starting CamelContext ({}) due {}", getName(), e.getMessage());
throw e;
}
}
// start notifiers as services
for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
if (notifier instanceof Service) {
Service service = (Service) notifier;
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onServiceAdd(this, service, null);
}
}
if (notifier instanceof Service) {
startService((Service)notifier);
}
}
// must let some bootstrap service be started before we can notify the starting event
EventHelper.notifyCamelContextStarting(this);
forceLazyInitialization();
// re-create endpoint registry as the cache size limit may be set after the constructor of this instance was called.
// and we needed to create endpoints up-front as it may be accessed before this context is started
endpoints = new EndpointRegistry(this, endpoints);
addService(endpoints);
// special for executorServiceManager as want to stop it manually
doAddService(executorServiceManager, false);
addService(producerServicePool);
addService(inflightRepository);
addService(shutdownStrategy);
addService(packageScanClassResolver);
addService(restRegistry);
if (runtimeEndpointRegistry != null) {
if (runtimeEndpointRegistry instanceof EventNotifier) {
getManagementStrategy().addEventNotifier((EventNotifier) runtimeEndpointRegistry);
}
addService(runtimeEndpointRegistry);
}
// eager lookup any configured properties component to avoid subsequent lookup attempts which may impact performance
// due we use properties component for property placeholder resolution at runtime
Component existing = lookupPropertiesComponent();
if (existing != null) {
// store reference to the existing properties component
if (existing instanceof PropertiesComponent) {
propertiesComponent = (PropertiesComponent) existing;
} else {
// properties component must be expected type
throw new IllegalArgumentException("Found properties component of type: " + existing.getClass() + " instead of expected: " + PropertiesComponent.class);
}
}
// start components
startServices(components.values());
// start the route definitions before the routes is started
startRouteDefinitions(routeDefinitions);
// is there any stream caching enabled then log an info about this and its limit of spooling to disk, so people is aware of this
boolean streamCachingInUse = isStreamCaching();
if (!streamCachingInUse) {
for (RouteDefinition route : routeDefinitions) {
Boolean routeCache = CamelContextHelper.parseBoolean(this, route.getStreamCache());
if (routeCache != null && routeCache) {
streamCachingInUse = true;
break;
}
}
}
if (isAllowUseOriginalMessage()) {
log.info("AllowUseOriginalMessage is enabled. If access to the original message is not needed,"
+ " then its recommended to turn this option off as it may improve performance.");
}
if (streamCachingInUse) {
// stream caching is in use so enable the strategy
getStreamCachingStrategy().setEnabled(true);
addService(getStreamCachingStrategy());
} else {
// log if stream caching is not in use as this can help people to enable it if they use streams
log.info("StreamCaching is not in use. If using streams then its recommended to enable stream caching."
+ " See more details at http://camel.apache.org/stream-caching.html");
}
// start routes
if (doNotStartRoutesOnFirstStart) {
log.debug("Skip starting of routes as CamelContext has been configured with autoStartup=false");
}
// invoke this logic to warmup the routes and if possible also start the routes
doStartOrResumeRoutes(routeServices, true, !doNotStartRoutesOnFirstStart, false, true);
// starting will continue in the start method
}
protected synchronized void doStop() throws Exception {
stopWatch.restart();
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is shutting down");
EventHelper.notifyCamelContextStopping(this);
// stop route inputs in the same order as they was started so we stop the very first inputs first
try {
// force shutting down routes as they may otherwise cause shutdown to hang
shutdownStrategy.shutdownForced(this, getRouteStartupOrder());
} catch (Throwable e) {
log.warn("Error occurred while shutting down routes. This exception will be ignored.", e);
}
getRouteStartupOrder().clear();
shutdownServices(routeServices.values());
// do not clear route services or startup listeners as we can start Camel again and get the route back as before
// but clear any suspend routes
suspendedRouteServices.clear();
// stop consumers from the services to close first, such as POJO consumer (eg @Consumer)
// which we need to stop after the routes, as a POJO consumer is essentially a route also
for (Service service : servicesToClose) {
if (service instanceof Consumer) {
shutdownServices(service);
}
}
// the stop order is important
// shutdown default error handler thread pool
if (errorHandlerExecutorService != null) {
// force shutting down the thread pool
getExecutorServiceManager().shutdownNow(errorHandlerExecutorService);
errorHandlerExecutorService = null;
}
// shutdown debugger
ServiceHelper.stopAndShutdownService(getDebugger());
shutdownServices(endpoints.values());
endpoints.clear();
shutdownServices(components.values());
components.clear();
shutdownServices(languages.values());
languages.clear();
try {
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onContextStop(this);
}
} catch (Throwable e) {
log.warn("Error occurred while stopping lifecycle strategies. This exception will be ignored.", e);
}
// shutdown services as late as possible
shutdownServices(servicesToClose);
servicesToClose.clear();
// must notify that we are stopped before stopping the management strategy
EventHelper.notifyCamelContextStopped(this);
// stop the notifier service
for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
shutdownServices(notifier);
}
// shutdown executor service and management as the last one
shutdownServices(executorServiceManager);
shutdownServices(managementStrategy);
shutdownServices(managementMBeanAssembler);
shutdownServices(lifecycleStrategies);
// do not clear lifecycleStrategies as we can start Camel again and get the route back as before
// stop the lazy created so they can be re-created on restart
forceStopLazyInitialization();
// stop to clear introspection cache
IntrospectionSupport.stop();
stopWatch.stop();
if (log.isInfoEnabled()) {
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") uptime {}", getUptime());
log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is shutdown in " + TimeUtils.printDuration(stopWatch.taken()));
}
// and clear start date
startDate = null;
Container.Instance.unmanage(this);
}
/**
* Starts or resumes the routes
*
* @param routeServices the routes to start (will only start a route if its not already started)
* @param checkClash whether to check for startup ordering clash
* @param startConsumer whether the route consumer should be started. Can be used to warmup the route without starting the consumer.
* @param resumeConsumer whether the route consumer should be resumed.
* @param addingRoutes whether we are adding new routes
* @throws Exception is thrown if error starting routes
*/
protected void doStartOrResumeRoutes(Map<String, RouteService> routeServices, boolean checkClash,
boolean startConsumer, boolean resumeConsumer, boolean addingRoutes) throws Exception {
isStartingRoutes.set(true);
try {
// filter out already started routes
Map<String, RouteService> filtered = new LinkedHashMap<String, RouteService>();
for (Map.Entry<String, RouteService> entry : routeServices.entrySet()) {
boolean startable = false;
Consumer consumer = entry.getValue().getRoutes().iterator().next().getConsumer();
if (consumer instanceof SuspendableService) {
// consumer could be suspended, which is not reflected in the RouteService status
startable = ((SuspendableService) consumer).isSuspended();
}
if (!startable && consumer instanceof StatefulService) {
// consumer could be stopped, which is not reflected in the RouteService status
startable = ((StatefulService) consumer).getStatus().isStartable();
} else if (!startable) {
// no consumer so use state from route service
startable = entry.getValue().getStatus().isStartable();
}
if (startable) {
filtered.put(entry.getKey(), entry.getValue());
}
}
if (!filtered.isEmpty()) {
// the context is now considered started (i.e. isStarted() == true))
// starting routes is done after, not during context startup
safelyStartRouteServices(checkClash, startConsumer, resumeConsumer, addingRoutes, filtered.values());
}
// we are finished starting routes, so remove flag before we emit the startup listeners below
isStartingRoutes.remove();
// now notify any startup aware listeners as all the routes etc has been started,
// allowing the listeners to do custom work after routes has been started
for (StartupListener startup : startupListeners) {
startup.onCamelContextStarted(this, isStarted());
}
} finally {
isStartingRoutes.remove();
}
}
protected boolean routeSupportsSuspension(String routeId) {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
return routeService.getRoutes().iterator().next().supportsSuspension();
}
return false;
}
private void shutdownServices(Object service) {
// do not rethrow exception as we want to keep shutting down in case of problems
// allow us to do custom work before delegating to service helper
try {
if (service instanceof Service) {
ServiceHelper.stopAndShutdownService(service);
} else if (service instanceof Collection) {
ServiceHelper.stopAndShutdownServices((Collection<?>)service);
}
} catch (Throwable e) {
log.warn("Error occurred while shutting down service: " + service + ". This exception will be ignored.", e);
// fire event
EventHelper.notifyServiceStopFailure(this, service, e);
}
}
private void shutdownServices(Collection<?> services) {
// reverse stopping by default
shutdownServices(services, true);
}
private void shutdownServices(Collection<?> services, boolean reverse) {
Collection<?> list = services;
if (reverse) {
List<Object> reverseList = new ArrayList<Object>(services);
Collections.reverse(reverseList);
list = reverseList;
}
for (Object service : list) {
shutdownServices(service);
}
}
private void startService(Service service) throws Exception {
// and register startup aware so they can be notified when
// camel context has been started
if (service instanceof StartupListener) {
StartupListener listener = (StartupListener) service;
addStartupListener(listener);
}
service.start();
}
private void startServices(Collection<?> services) throws Exception {
for (Object element : services) {
if (element instanceof Service) {
startService((Service)element);
}
}
}
private void stopServices(Object service) throws Exception {
// allow us to do custom work before delegating to service helper
try {
ServiceHelper.stopService(service);
} catch (Exception e) {
// fire event
EventHelper.notifyServiceStopFailure(this, service, e);
// rethrow to signal error with stopping
throw e;
}
}
protected void startRouteDefinitions(Collection<RouteDefinition> list) throws Exception {
if (list != null) {
for (RouteDefinition route : list) {
startRoute(route);
}
}
}
/**
* Starts the given route service
*/
protected synchronized void startRouteService(RouteService routeService, boolean addingRoutes) throws Exception {
// we may already be starting routes so remember this, so we can unset accordingly in finally block
boolean alreadyStartingRoutes = isStartingRoutes();
if (!alreadyStartingRoutes) {
isStartingRoutes.set(true);
}
try {
// the route service could have been suspended, and if so then resume it instead
if (routeService.getStatus().isSuspended()) {
resumeRouteService(routeService);
} else {
// start the route service
routeServices.put(routeService.getId(), routeService);
if (shouldStartRoutes()) {
// this method will log the routes being started
safelyStartRouteServices(true, true, true, false, addingRoutes, routeService);
// start route services if it was configured to auto startup and we are not adding routes
boolean autoStartup = routeService.getRouteDefinition().isAutoStartup(this) && this.isAutoStartup();
if (!addingRoutes || autoStartup) {
// start the route since auto start is enabled or we are starting a route (not adding new routes)
routeService.start();
}
}
}
} finally {
if (!alreadyStartingRoutes) {
isStartingRoutes.remove();
}
}
}
/**
* Resumes the given route service
*/
protected synchronized void resumeRouteService(RouteService routeService) throws Exception {
// the route service could have been stopped, and if so then start it instead
if (!routeService.getStatus().isSuspended()) {
startRouteService(routeService, false);
} else {
// resume the route service
if (shouldStartRoutes()) {
// this method will log the routes being started
safelyStartRouteServices(true, false, true, true, false, routeService);
// must resume route service as well
routeService.resume();
}
}
}
protected synchronized void stopRouteService(RouteService routeService, boolean removingRoutes) throws Exception {
routeService.setRemovingRoutes(removingRoutes);
stopRouteService(routeService);
}
protected void logRouteState(Route route, String state) {
if (log.isInfoEnabled()) {
if (route.getConsumer() != null) {
log.info("Route: {} is {}, was consuming from: {}", new Object[]{route.getId(), state, route.getConsumer().getEndpoint()});
} else {
log.info("Route: {} is {}.", route.getId(), state);
}
}
}
protected synchronized void stopRouteService(RouteService routeService) throws Exception {
routeService.stop();
for (Route route : routeService.getRoutes()) {
logRouteState(route, "stopped");
}
}
protected synchronized void shutdownRouteService(RouteService routeService) throws Exception {
routeService.shutdown();
for (Route route : routeService.getRoutes()) {
logRouteState(route, "shutdown and removed");
}
}
protected synchronized void suspendRouteService(RouteService routeService) throws Exception {
routeService.setRemovingRoutes(false);
routeService.suspend();
for (Route route : routeService.getRoutes()) {
logRouteState(route, "suspended");
}
}
/**
* Starts the routes services in a proper manner which ensures the routes will be started in correct order,
* check for clash and that the routes will also be shutdown in correct order as well.
* <p/>
* This method <b>must</b> be used to start routes in a safe manner.
*
* @param checkClash whether to check for startup order clash
* @param startConsumer whether the route consumer should be started. Can be used to warmup the route without starting the consumer.
* @param resumeConsumer whether the route consumer should be resumed.
* @param addingRoutes whether we are adding new routes
* @param routeServices the routes
* @throws Exception is thrown if error starting the routes
*/
protected synchronized void safelyStartRouteServices(boolean checkClash, boolean startConsumer, boolean resumeConsumer,
boolean addingRoutes, Collection<RouteService> routeServices) throws Exception {
// list of inputs to start when all the routes have been prepared for starting
// we use a tree map so the routes will be ordered according to startup order defined on the route
Map<Integer, DefaultRouteStartupOrder> inputs = new TreeMap<Integer, DefaultRouteStartupOrder>();
// figure out the order in which the routes should be started
for (RouteService routeService : routeServices) {
DefaultRouteStartupOrder order = doPrepareRouteToBeStarted(routeService);
// check for clash before we add it as input
if (checkClash) {
doCheckStartupOrderClash(order, inputs);
}
inputs.put(order.getStartupOrder(), order);
}
// warm up routes before we start them
doWarmUpRoutes(inputs, startConsumer);
if (startConsumer) {
if (resumeConsumer) {
// and now resume the routes
doResumeRouteConsumers(inputs, addingRoutes);
} else {
// and now start the routes
// and check for clash with multiple consumers of the same endpoints which is not allowed
doStartRouteConsumers(inputs, addingRoutes);
}
}
// inputs no longer needed
inputs.clear();
}
/**
* @see #safelyStartRouteServices(boolean,boolean,boolean,boolean,java.util.Collection)
*/
protected synchronized void safelyStartRouteServices(boolean forceAutoStart, boolean checkClash, boolean startConsumer,
boolean resumeConsumer, boolean addingRoutes, RouteService... routeServices) throws Exception {
safelyStartRouteServices(checkClash, startConsumer, resumeConsumer, addingRoutes, Arrays.asList(routeServices));
}
private DefaultRouteStartupOrder doPrepareRouteToBeStarted(RouteService routeService) {
// add the inputs from this route service to the list to start afterwards
// should be ordered according to the startup number
Integer startupOrder = routeService.getRouteDefinition().getStartupOrder();
if (startupOrder == null) {
// auto assign a default startup order
startupOrder = defaultRouteStartupOrder++;
}
// create holder object that contains information about this route to be started
Route route = routeService.getRoutes().iterator().next();
return new DefaultRouteStartupOrder(startupOrder, route, routeService);
}
private boolean doCheckStartupOrderClash(DefaultRouteStartupOrder answer, Map<Integer, DefaultRouteStartupOrder> inputs) throws FailedToStartRouteException {
// check for clash by startupOrder id
DefaultRouteStartupOrder other = inputs.get(answer.getStartupOrder());
if (other != null && answer != other) {
String otherId = other.getRoute().getId();
throw new FailedToStartRouteException(answer.getRoute().getId(), "startupOrder clash. Route " + otherId + " already has startupOrder "
+ answer.getStartupOrder() + " configured which this route have as well. Please correct startupOrder to be unique among all your routes.");
}
// check in existing already started as well
for (RouteStartupOrder order : routeStartupOrder) {
String otherId = order.getRoute().getId();
if (answer.getRoute().getId().equals(otherId)) {
// its the same route id so skip clash check as its the same route (can happen when using suspend/resume)
} else if (answer.getStartupOrder() == order.getStartupOrder()) {
throw new FailedToStartRouteException(answer.getRoute().getId(), "startupOrder clash. Route " + otherId + " already has startupOrder "
+ answer.getStartupOrder() + " configured which this route have as well. Please correct startupOrder to be unique among all your routes.");
}
}
return true;
}
private void doWarmUpRoutes(Map<Integer, DefaultRouteStartupOrder> inputs, boolean autoStartup) throws Exception {
// now prepare the routes by starting its services before we start the input
for (Map.Entry<Integer, DefaultRouteStartupOrder> entry : inputs.entrySet()) {
// defer starting inputs till later as we want to prepare the routes by starting
// all their processors and child services etc.
// then later we open the floods to Camel by starting the inputs
// what this does is to ensure Camel is more robust on starting routes as all routes
// will then be prepared in time before we start inputs which will consume messages to be routed
RouteService routeService = entry.getValue().getRouteService();
log.debug("Warming up route id: {} having autoStartup={}", routeService.getId(), autoStartup);
routeService.warmUp();
}
}
private void doResumeRouteConsumers(Map<Integer, DefaultRouteStartupOrder> inputs, boolean addingRoutes) throws Exception {
doStartOrResumeRouteConsumers(inputs, true, addingRoutes);
}
private void doStartRouteConsumers(Map<Integer, DefaultRouteStartupOrder> inputs, boolean addingRoutes) throws Exception {
doStartOrResumeRouteConsumers(inputs, false, addingRoutes);
}
private void doStartOrResumeRouteConsumers(Map<Integer, DefaultRouteStartupOrder> inputs, boolean resumeOnly, boolean addingRoute) throws Exception {
List<Endpoint> routeInputs = new ArrayList<Endpoint>();
for (Map.Entry<Integer, DefaultRouteStartupOrder> entry : inputs.entrySet()) {
Integer order = entry.getKey();
Route route = entry.getValue().getRoute();
RouteService routeService = entry.getValue().getRouteService();
// if we are starting camel, then skip routes which are configured to not be auto started
boolean autoStartup = routeService.getRouteDefinition().isAutoStartup(this) && this.isAutoStartup();
if (addingRoute && !autoStartup) {
log.info("Skipping starting of route " + routeService.getId() + " as its configured with autoStartup=false");
continue;
}
// start the service
for (Consumer consumer : routeService.getInputs().values()) {
Endpoint endpoint = consumer.getEndpoint();
// check multiple consumer violation, with the other routes to be started
if (!doCheckMultipleConsumerSupportClash(endpoint, routeInputs)) {
throw new FailedToStartRouteException(routeService.getId(),
"Multiple consumers for the same endpoint is not allowed: " + endpoint);
}
// check for multiple consumer violations with existing routes which
// have already been started, or is currently starting
List<Endpoint> existingEndpoints = new ArrayList<Endpoint>();
for (Route existingRoute : getRoutes()) {
if (route.getId().equals(existingRoute.getId())) {
// skip ourselves
continue;
}
Endpoint existing = existingRoute.getEndpoint();
ServiceStatus status = getRouteStatus(existingRoute.getId());
if (status != null && (status.isStarted() || status.isStarting())) {
existingEndpoints.add(existing);
}
}
if (!doCheckMultipleConsumerSupportClash(endpoint, existingEndpoints)) {
throw new FailedToStartRouteException(routeService.getId(),
"Multiple consumers for the same endpoint is not allowed: " + endpoint);
}
// start the consumer on the route
log.debug("Route: {} >>> {}", route.getId(), route);
if (resumeOnly) {
log.debug("Resuming consumer (order: {}) on route: {}", order, route.getId());
} else {
log.debug("Starting consumer (order: {}) on route: {}", order, route.getId());
}
if (resumeOnly && route.supportsSuspension()) {
// if we are resuming and the route can be resumed
ServiceHelper.resumeService(consumer);
log.info("Route: " + route.getId() + " resumed and consuming from: " + endpoint);
} else {
// when starting we should invoke the lifecycle strategies
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onServiceAdd(this, consumer, route);
}
startService(consumer);
log.info("Route: " + route.getId() + " started and consuming from: " + endpoint);
}
routeInputs.add(endpoint);
// add to the order which they was started, so we know how to stop them in reverse order
// but only add if we haven't already registered it before (we dont want to double add when restarting)
boolean found = false;
for (RouteStartupOrder other : routeStartupOrder) {
if (other.getRoute().getId().equals(route.getId())) {
found = true;
break;
}
}
if (!found) {
routeStartupOrder.add(entry.getValue());
}
}
if (resumeOnly) {
routeService.resume();
} else {
// and start the route service (no need to start children as they are already warmed up)
routeService.start(false);
}
}
}
private boolean doCheckMultipleConsumerSupportClash(Endpoint endpoint, List<Endpoint> routeInputs) {
// is multiple consumers supported
boolean multipleConsumersSupported = false;
if (endpoint instanceof MultipleConsumersSupport) {
multipleConsumersSupported = ((MultipleConsumersSupport) endpoint).isMultipleConsumersSupported();
}
if (multipleConsumersSupported) {
// multiple consumer allowed, so return true
return true;
}
// check in progress list
if (routeInputs.contains(endpoint)) {
return false;
}
return true;
}
/**
* Force some lazy initialization to occur upfront before we start any
* components and create routes
*/
protected void forceLazyInitialization() {
getRegistry();
getInjector();
getLanguageResolver();
getTypeConverterRegistry();
getTypeConverter();
getRuntimeEndpointRegistry();
if (isTypeConverterStatisticsEnabled() != null) {
getTypeConverterRegistry().getStatistics().setStatisticsEnabled(isTypeConverterStatisticsEnabled());
}
}
/**
* Force clear lazy initialization so they can be re-created on restart
*/
protected void forceStopLazyInitialization() {
injector = null;
languageResolver = null;
typeConverterRegistry = null;
typeConverter = null;
}
/**
* Lazily create a default implementation
*/
protected TypeConverter createTypeConverter() {
BaseTypeConverterRegistry answer;
if (isLazyLoadTypeConverters()) {
answer = new LazyLoadingTypeConverter(packageScanClassResolver, getInjector(), getDefaultFactoryFinder());
} else {
answer = new DefaultTypeConverter(packageScanClassResolver, getInjector(), getDefaultFactoryFinder());
}
setTypeConverterRegistry(answer);
return answer;
}
/**
* Lazily create a default implementation
*/
protected Injector createInjector() {
FactoryFinder finder = getDefaultFactoryFinder();
try {
return (Injector) finder.newInstance("Injector");
} catch (NoFactoryAvailableException e) {
// lets use the default injector
return new DefaultInjector(this);
}
}
/**
* Lazily create a default implementation
*/
protected ManagementMBeanAssembler createManagementMBeanAssembler() {
return new DefaultManagementMBeanAssembler(this);
}
/**
* Lazily create a default implementation
*/
protected ComponentResolver createComponentResolver() {
return new DefaultComponentResolver();
}
/**
* Lazily create a default implementation
*/
protected Registry createRegistry() {
JndiRegistry jndi = new JndiRegistry();
try {
// getContext() will force setting up JNDI
jndi.getContext();
return jndi;
} catch (Throwable e) {
log.debug("Cannot create javax.naming.InitialContext due " + e.getMessage() + ". Will fallback and use SimpleRegistry instead. This exception is ignored.", e);
return new SimpleRegistry();
}
}
/**
* A pluggable strategy to allow an endpoint to be created without requiring
* a component to be its factory, such as for looking up the URI inside some
* {@link Registry}
*
* @param uri the uri for the endpoint to be created
* @return the newly created endpoint or null if it could not be resolved
*/
protected Endpoint createEndpoint(String uri) {
Object value = getRegistry().lookupByName(uri);
if (value instanceof Endpoint) {
return (Endpoint) value;
} else if (value instanceof Processor) {
return new ProcessorEndpoint(uri, this, (Processor) value);
} else if (value != null) {
return convertBeanToEndpoint(uri, value);
}
return null;
}
/**
* Strategy method for attempting to convert the bean from a {@link Registry} to an endpoint using
* some kind of transformation or wrapper
*
* @param uri the uri for the endpoint (and name in the registry)
* @param bean the bean to be converted to an endpoint, which will be not null
* @return a new endpoint
*/
protected Endpoint convertBeanToEndpoint(String uri, Object bean) {
throw new IllegalArgumentException("uri: " + uri + " bean: " + bean
+ " could not be converted to an Endpoint");
}
/**
* Should we start newly added routes?
*/
protected boolean shouldStartRoutes() {
return isStarted() && !isStarting();
}
/**
* Gets the properties component in use.
* Returns {@code null} if no properties component is in use.
*/
protected PropertiesComponent getPropertiesComponent() {
return propertiesComponent;
}
public void setDataFormats(Map<String, DataFormatDefinition> dataFormats) {
this.dataFormats = dataFormats;
}
public Map<String, DataFormatDefinition> getDataFormats() {
return dataFormats;
}
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
public FactoryFinder getDefaultFactoryFinder() {
if (defaultFactoryFinder == null) {
defaultFactoryFinder = factoryFinderResolver.resolveDefaultFactoryFinder(getClassResolver());
}
return defaultFactoryFinder;
}
public void setFactoryFinderResolver(FactoryFinderResolver resolver) {
this.factoryFinderResolver = resolver;
}
public FactoryFinder getFactoryFinder(String path) throws NoFactoryAvailableException {
synchronized (factories) {
FactoryFinder answer = factories.get(path);
if (answer == null) {
answer = factoryFinderResolver.resolveFactoryFinder(getClassResolver(), path);
factories.put(path, answer);
}
return answer;
}
}
public ClassResolver getClassResolver() {
return classResolver;
}
public void setClassResolver(ClassResolver classResolver) {
this.classResolver = classResolver;
}
public PackageScanClassResolver getPackageScanClassResolver() {
return packageScanClassResolver;
}
public void setPackageScanClassResolver(PackageScanClassResolver packageScanClassResolver) {
this.packageScanClassResolver = packageScanClassResolver;
}
public List<String> getComponentNames() {
synchronized (components) {
List<String> answer = new ArrayList<String>();
for (String name : components.keySet()) {
answer.add(name);
}
return answer;
}
}
public List<String> getLanguageNames() {
synchronized (languages) {
List<String> answer = new ArrayList<String>();
for (String name : languages.keySet()) {
answer.add(name);
}
return answer;
}
}
public NodeIdFactory getNodeIdFactory() {
return nodeIdFactory;
}
public void setNodeIdFactory(NodeIdFactory idFactory) {
this.nodeIdFactory = idFactory;
}
public ManagementStrategy getManagementStrategy() {
return managementStrategy;
}
public void setManagementStrategy(ManagementStrategy managementStrategy) {
this.managementStrategy = managementStrategy;
}
public InterceptStrategy getDefaultTracer() {
if (defaultTracer == null) {
defaultTracer = new Tracer();
}
return defaultTracer;
}
public void setDefaultTracer(InterceptStrategy tracer) {
this.defaultTracer = tracer;
}
public InterceptStrategy getDefaultBacklogTracer() {
if (defaultBacklogTracer == null) {
defaultBacklogTracer = new BacklogTracer(this);
}
return defaultBacklogTracer;
}
public void setDefaultBacklogTracer(InterceptStrategy backlogTracer) {
this.defaultBacklogTracer = backlogTracer;
}
public InterceptStrategy getDefaultBacklogDebugger() {
if (defaultBacklogDebugger == null) {
defaultBacklogDebugger = new BacklogDebugger(this);
}
return defaultBacklogDebugger;
}
public void setDefaultBacklogDebugger(InterceptStrategy defaultBacklogDebugger) {
this.defaultBacklogDebugger = defaultBacklogDebugger;
}
public void disableJMX() {
if (isStarting() || isStarted()) {
throw new IllegalStateException("Disabling JMX can only be done when CamelContext has not been started");
}
managementStrategy = new DefaultManagementStrategy(this);
// must clear lifecycle strategies as we add DefaultManagementLifecycleStrategy by default for JMX support
lifecycleStrategies.clear();
}
public InflightRepository getInflightRepository() {
return inflightRepository;
}
public void setInflightRepository(InflightRepository repository) {
this.inflightRepository = repository;
}
public void setAutoStartup(Boolean autoStartup) {
this.autoStartup = autoStartup;
}
public Boolean isAutoStartup() {
return autoStartup != null && autoStartup;
}
@Deprecated
public Boolean isLazyLoadTypeConverters() {
return lazyLoadTypeConverters != null && lazyLoadTypeConverters;
}
@Deprecated
public void setLazyLoadTypeConverters(Boolean lazyLoadTypeConverters) {
this.lazyLoadTypeConverters = lazyLoadTypeConverters;
}
public Boolean isTypeConverterStatisticsEnabled() {
return typeConverterStatisticsEnabled != null && typeConverterStatisticsEnabled;
}
public void setTypeConverterStatisticsEnabled(Boolean typeConverterStatisticsEnabled) {
this.typeConverterStatisticsEnabled = typeConverterStatisticsEnabled;
}
public Boolean isUseMDCLogging() {
return useMDCLogging != null && useMDCLogging;
}
public void setUseMDCLogging(Boolean useMDCLogging) {
this.useMDCLogging = useMDCLogging;
}
public Boolean isUseBreadcrumb() {
return useBreadcrumb != null && useBreadcrumb;
}
public void setUseBreadcrumb(Boolean useBreadcrumb) {
this.useBreadcrumb = useBreadcrumb;
}
public ClassLoader getApplicationContextClassLoader() {
return applicationContextClassLoader;
}
public void setApplicationContextClassLoader(ClassLoader classLoader) {
applicationContextClassLoader = classLoader;
}
public DataFormatResolver getDataFormatResolver() {
return dataFormatResolver;
}
public void setDataFormatResolver(DataFormatResolver dataFormatResolver) {
this.dataFormatResolver = dataFormatResolver;
}
public DataFormat resolveDataFormat(String name) {
DataFormat answer = dataFormatResolver.resolveDataFormat(name, this);
// inject CamelContext if aware
if (answer != null && answer instanceof CamelContextAware) {
((CamelContextAware) answer).setCamelContext(this);
}
return answer;
}
public DataFormatDefinition resolveDataFormatDefinition(String name) {
// lookup type and create the data format from it
DataFormatDefinition type = lookup(this, name, DataFormatDefinition.class);
if (type == null && getDataFormats() != null) {
type = getDataFormats().get(name);
}
return type;
}
private static <T> T lookup(CamelContext context, String ref, Class<T> type) {
try {
return context.getRegistry().lookupByNameAndType(ref, type);
} catch (Exception e) {
// need to ignore not same type and return it as null
return null;
}
}
protected Component lookupPropertiesComponent() {
// no existing properties component so lookup and add as component if possible
PropertiesComponent answer = (PropertiesComponent) hasComponent("properties");
if (answer == null) {
answer = getRegistry().lookupByNameAndType("properties", PropertiesComponent.class);
if (answer != null) {
addComponent("properties", answer);
}
}
return answer;
}
public ShutdownStrategy getShutdownStrategy() {
return shutdownStrategy;
}
public void setShutdownStrategy(ShutdownStrategy shutdownStrategy) {
this.shutdownStrategy = shutdownStrategy;
}
public ShutdownRoute getShutdownRoute() {
return shutdownRoute;
}
public void setShutdownRoute(ShutdownRoute shutdownRoute) {
this.shutdownRoute = shutdownRoute;
}
public ShutdownRunningTask getShutdownRunningTask() {
return shutdownRunningTask;
}
public void setShutdownRunningTask(ShutdownRunningTask shutdownRunningTask) {
this.shutdownRunningTask = shutdownRunningTask;
}
public void setAllowUseOriginalMessage(Boolean allowUseOriginalMessage) {
this.allowUseOriginalMessage = allowUseOriginalMessage;
}
public Boolean isAllowUseOriginalMessage() {
return allowUseOriginalMessage != null && allowUseOriginalMessage;
}
public ExecutorServiceManager getExecutorServiceManager() {
return this.executorServiceManager;
}
@Deprecated
public org.apache.camel.spi.ExecutorServiceStrategy getExecutorServiceStrategy() {
// its okay to create a new instance as its stateless, and just delegate
// ExecutorServiceManager which is the new API
return new DefaultExecutorServiceStrategy(this);
}
public void setExecutorServiceManager(ExecutorServiceManager executorServiceManager) {
this.executorServiceManager = executorServiceManager;
}
public ProcessorFactory getProcessorFactory() {
return processorFactory;
}
public void setProcessorFactory(ProcessorFactory processorFactory) {
this.processorFactory = processorFactory;
}
public Debugger getDebugger() {
return debugger;
}
public void setDebugger(Debugger debugger) {
this.debugger = debugger;
}
public UuidGenerator getUuidGenerator() {
return uuidGenerator;
}
public void setUuidGenerator(UuidGenerator uuidGenerator) {
this.uuidGenerator = uuidGenerator;
}
public StreamCachingStrategy getStreamCachingStrategy() {
if (streamCachingStrategy == null) {
streamCachingStrategy = new DefaultStreamCachingStrategy();
}
return streamCachingStrategy;
}
public void setStreamCachingStrategy(StreamCachingStrategy streamCachingStrategy) {
this.streamCachingStrategy = streamCachingStrategy;
}
public RestRegistry getRestRegistry() {
return restRegistry;
}
public void setRestRegistry(RestRegistry restRegistry) {
this.restRegistry = restRegistry;
}
@Override
public String getProperty(String name) {
String value = getProperties().get(name);
if (ObjectHelper.isNotEmpty(value)) {
try {
value = resolvePropertyPlaceholders(value);
} catch (Exception e) {
throw new RuntimeCamelException("Error getting property: " + name, e);
}
}
return value;
}
protected Map<String, RouteService> getRouteServices() {
return routeServices;
}
protected ManagementStrategy createManagementStrategy() {
return new ManagementStrategyFactory().create(this, disableJMX || Boolean.getBoolean(JmxSystemPropertyKeys.DISABLED));
}
/**
* Reset context counter to a preset value. Mostly used for tests to ensure a predictable getName()
*
* @param value new value for the context counter
*/
public static void setContextCounter(int value) {
DefaultCamelContextNameStrategy.setCounter(value);
DefaultManagementNameStrategy.setCounter(value);
}
private static UuidGenerator createDefaultUuidGenerator() {
if (System.getProperty("com.google.appengine.runtime.environment") != null) {
// either "Production" or "Development"
return new JavaUuidGenerator();
} else {
return new ActiveMQUuidGenerator();
}
}
@Override
public String toString() {
return "CamelContext(" + getName() + ")";
}
}
| CAMEL-7836: Fixed potential ConcurrentModificationException when calling getRoutes.
| camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java | CAMEL-7836: Fixed potential ConcurrentModificationException when calling getRoutes. | <ide><path>amel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java
<ide> return routeStartupOrder;
<ide> }
<ide>
<del> public List<Route> getRoutes() {
<add> public synchronized List<Route> getRoutes() {
<ide> // lets return a copy of the collection as objects are removed later when services are stopped
<ide> if (routes.isEmpty()) {
<ide> return Collections.emptyList(); |
|
Java | mit | a24196e1a9bc2a5854de01aad2290d547b5c0f2c | 0 | hres/cfg-task-service,hres/cfg-task-service,hres/cfg-task-service | package ca.gc.ip346.classification.resource;
import static javax.ws.rs.HttpMethod.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
// import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.client.ClientProperties;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.annotation.JacksonFeatures;
import com.google.gson.GsonBuilder;
@Path("/rulesets")
// @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class RulesResource {
private static final Logger logger = LogManager.getLogger(RulesResource.class);
private Map<String, String> map = null;
@Context
private HttpServletRequest request;
public RulesResource() {
map = new HashMap<String, String>();
}
/**
* Sprint 5 - Build REST service to return rulesets
*/
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response getRules() {
String target = request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-");
map.put("message", "REST service to return rulesets");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(target) + "[00;00m");
Response response = ClientBuilder
.newClient()
.target(target)
.path("/rulesets")
.request()
.property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE)
.accept(MediaType.APPLICATION_JSON)
.get();
// return FoodsResource.getResponse(GET, Response.Status.OK, response.readEntity(Object.class));
return FoodsResource.getResponse(GET, Response.Status.OK, response.readEntity(new GenericType<HashMap<String, Object>>() {}));
}
/**
* Sprint 5 - Build REST service to return a particular ruleset
*/
@GET
@Path("/{id}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response selectRules(@PathParam("id") String id) {
String target = request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-");
map.put("message", "REST service to return a particular ruleset");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
Response response = ClientBuilder
.newClient()
.target(target)
.path("/rulesets/" + id)
.request()
.get();
return FoodsResource.getResponse(GET, Response.Status.OK, response.readEntity(Object.class));
}
/**
* Sprint 5 - Build REST service to create new ruleset
*/
@POST
public Response createRules() {
map.put("message", "REST service to create new ruleset");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
return FoodsResource.getResponse(POST, Response.Status.OK, map);
}
/**
* Sprint 5 - Build REST service to update an existing ruleset
*/
@PUT
@Path("id")
public Response updateRules(@PathParam("id") String id) {
map.put("message", "REST service to update an existing ruleset");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
return FoodsResource.getResponse(PUT, Response.Status.OK, map);
}
/**
* Sprint 5 - Build REST service to delete an existing ruleset
*/
@DELETE
@Path("/{id}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response deleteRules(@PathParam("id") String id) {
String target = request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-");
map.put("message", "REST service to delete an existing ruleset");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
Response response = ClientBuilder
.newClient()
.target(target)
.path("/rulesets/" + id)
.request()
.delete();
return FoodsResource.getResponse(DELETE, Response.Status.OK, response.readEntity(Object.class));
}
}
| src/main/java/ca/gc/ip346/classification/resource/RulesResource.java | package ca.gc.ip346.classification.resource;
import static javax.ws.rs.HttpMethod.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
// import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.client.ClientProperties;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.annotation.JacksonFeatures;
import com.google.gson.GsonBuilder;
@Path("/rulesets")
// @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class RulesResource {
private static final Logger logger = LogManager.getLogger(RulesResource.class);
private Map<String, String> map = null;
@Context
private HttpServletRequest request;
public RulesResource() {
map = new HashMap<String, String>();
}
/**
* Sprint 5 - Build REST service to return rulesets
*/
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response getRules() {
String target = request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-");
map.put("message", "REST service to return rulesets");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(target) + "[00;00m");
Response response = ClientBuilder
.newClient()
.target(target)
.path("/rulesets")
.request()
.property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE)
.accept(MediaType.APPLICATION_JSON)
.get();
return FoodsResource.getResponse(GET, Response.Status.OK, response.readEntity(Object.class));
}
/**
* Sprint 5 - Build REST service to return a particular ruleset
*/
@GET
@Path("/{id}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response selectRules(@PathParam("id") String id) {
String target = request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-");
map.put("message", "REST service to return a particular ruleset");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
Response response = ClientBuilder
.newClient()
.target(target)
.path("/rulesets/" + id)
.request()
.get();
return FoodsResource.getResponse(GET, Response.Status.OK, response.readEntity(Object.class));
}
/**
* Sprint 5 - Build REST service to create new ruleset
*/
@POST
public Response createRules() {
map.put("message", "REST service to create new ruleset");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
return FoodsResource.getResponse(POST, Response.Status.OK, map);
}
/**
* Sprint 5 - Build REST service to update an existing ruleset
*/
@PUT
@Path("id")
public Response updateRules(@PathParam("id") String id) {
map.put("message", "REST service to update an existing ruleset");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
return FoodsResource.getResponse(PUT, Response.Status.OK, map);
}
/**
* Sprint 5 - Build REST service to delete an existing ruleset
*/
@DELETE
@Path("/{id}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response deleteRules(@PathParam("id") String id) {
String target = request.getRequestURL().toString().replaceAll("(\\w+:\\/\\/[^/]+(:\\d+)?/[^/]+).*", "$1").replaceAll("-task-", "-classification-");
map.put("message", "REST service to delete an existing ruleset");
logger.debug("\n[01;32m" + new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create().toJson(map) + "[00;00m");
Response response = ClientBuilder
.newClient()
.target(target)
.path("/rulesets/" + id)
.request()
.delete();
return FoodsResource.getResponse(DELETE, Response.Status.OK, response.readEntity(Object.class));
}
}
| changed to GenericType when reading the response from cfg-classification-service
| src/main/java/ca/gc/ip346/classification/resource/RulesResource.java | changed to GenericType when reading the response from cfg-classification-service | <ide><path>rc/main/java/ca/gc/ip346/classification/resource/RulesResource.java
<ide> import javax.ws.rs.Produces;
<ide> import javax.ws.rs.client.ClientBuilder;
<ide> import javax.ws.rs.core.Context;
<add>import javax.ws.rs.core.GenericType;
<ide> import javax.ws.rs.core.MediaType;
<ide> import javax.ws.rs.core.Response;
<ide>
<ide> .accept(MediaType.APPLICATION_JSON)
<ide> .get();
<ide>
<del> return FoodsResource.getResponse(GET, Response.Status.OK, response.readEntity(Object.class));
<add> // return FoodsResource.getResponse(GET, Response.Status.OK, response.readEntity(Object.class));
<add> return FoodsResource.getResponse(GET, Response.Status.OK, response.readEntity(new GenericType<HashMap<String, Object>>() {}));
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | e7e62ee38cea71948fd75e46ab53672ceb7e5285 | 0 | ganskef/LittleProxy-mitm | package de.ganskef.test;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import java.io.File;
import java.io.RandomAccessFile;
import java.net.URI;
import java.nio.channels.FileChannel;
import org.apache.commons.io.IOUtils;
public class NettyClient_NoHttps {
public File get(String url, IProxy proxy, String target) throws Exception {
return get(new URI(url), url, "127.0.0.1", proxy.getProxyPort(), target);
}
public File get(String url, IProxy proxy) throws Exception {
return get(new URI(url), url, "127.0.0.1", proxy.getProxyPort(),
"proxy.out");
}
public File get(String url) throws Exception {
return get(url, "client.out");
}
public File get(String url, String target) throws Exception {
URI uri = new URI(url);
String host = uri.getHost();
int port = uri.getPort();
if (port == -1) {
if (isSecured(uri)) {
port = 443;
} else {
port = 80;
}
}
return get(uri, uri.getRawPath(), host, port, target);
}
private boolean isSecured(URI uri) {
// XXX https via offline proxy won't work with this client. I mean, this
// was my experience while debugging it. I had no success with Apache
// HC, too. Only URLConnection works like expected for me.
//
// It seems to me we have to wait for a proper solution - see:
// https://github.com/netty/netty/issues/1133#event-299614098
// normanmaurer modified the milestone: 4.1.0.Beta5, 4.1.0.Beta6
//
// return uri.getScheme().equalsIgnoreCase("https");
return false;
}
private File get(URI uri, String url, String proxyHost, int proxyPort,
final String target) throws Exception {
final SslContext sslCtx;
if (isSecured(uri)) {
sslCtx = SslContext
.newClientContext(InsecureTrustManagerFactory.INSTANCE);
} else {
sslCtx = null;
}
final NettyClientHandler handler = new NettyClientHandler(target);
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.handler(new NettyClientInitializer(sslCtx, handler));
// .handler(new HttpSnoopClientInitializer(sslCtx));
Channel ch = b.connect(proxyHost, proxyPort).sync().channel();
HttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, url);
request.headers().set(HttpHeaders.Names.HOST, uri.getHost());
request.headers().set(HttpHeaders.Names.CONNECTION,
HttpHeaders.Values.CLOSE);
request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING,
HttpHeaders.Values.GZIP);
ch.writeAndFlush(request);
ch.closeFuture().sync();
} finally {
group.shutdownGracefully();
}
return handler.getFile();
}
}
class NettyClientHandler extends SimpleChannelInboundHandler<HttpObject> {
private File file;
public NettyClientHandler(String target) {
File dir = new File("src/test/resources/tmp");
dir.mkdirs();
file = new File(dir, target);
file.delete();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
throws Exception {
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
RandomAccessFile output = null;
FileChannel oc = null;
try {
output = new RandomAccessFile(file, "rw");
oc = output.getChannel();
oc.position(oc.size());
ByteBuf buffer = content.content();
for (int i = 0, len = buffer.nioBufferCount(); i < len; i++) {
oc.write(buffer.nioBuffers()[i]);
}
} finally {
IOUtils.closeQuietly(oc);
IOUtils.closeQuietly(output);
}
if (content instanceof LastHttpContent) {
ctx.close();
}
}
}
public File getFile() {
return file;
}
}
class NettyClientInitializer extends ChannelInitializer<SocketChannel> {
private ChannelHandler handler;
private SslContext sslCtx;
public NettyClientInitializer(SslContext sslCtx, ChannelHandler handler) {
this.sslCtx = sslCtx;
this.handler = handler;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast("log", new LoggingHandler(LogLevel.TRACE));
p.addLast("codec", new HttpClientCodec());
p.addLast("inflater", new HttpContentDecompressor());
// p.addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024));
p.addLast("handler", handler);
}
} | src/test/java/de/ganskef/test/NettyClient_NoHttps.java | package de.ganskef.test;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import java.io.File;
import java.io.RandomAccessFile;
import java.net.URI;
import java.nio.channels.FileChannel;
import org.apache.commons.io.IOUtils;
public class NettyClient_NoHttps {
public File get(String url, IProxy proxy, String target) throws Exception {
return get(new URI(url), url, "127.0.0.1", proxy.getProxyPort(), target);
}
public File get(String url, IProxy proxy) throws Exception {
return get(new URI(url), url, "127.0.0.1", proxy.getProxyPort(),
"proxy.out");
}
public File get(String url) throws Exception {
return get(url, "client.out");
}
public File get(String url, String target) throws Exception {
URI uri = new URI(url);
String host = uri.getHost();
int port = uri.getPort();
return get(uri, uri.getRawPath(), host, port, target);
}
private File get(URI uri, String url, String proxyHost, int proxyPort,
final String target) throws Exception {
if (url.toLowerCase().startsWith("https")) {
System.out.println("HTTPS is not supported, try HTTP for " + url);
}
if (proxyPort == -1) {
proxyPort = 80;
}
final NettyClientHandler handler = new NettyClientHandler(target);
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.handler(new NettyClientInitializer(handler));
Channel ch = b.connect(proxyHost, proxyPort).sync().channel();
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.GET, url);
request.headers().set(HttpHeaders.Names.HOST, uri.getHost());
request.headers().set(HttpHeaders.Names.CONNECTION,
HttpHeaders.Values.CLOSE);
request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING,
HttpHeaders.Values.GZIP);
ch.writeAndFlush(request);
ch.closeFuture().sync();
} finally {
group.shutdownGracefully();
}
return handler.getFile();
}
}
class NettyClientHandler extends SimpleChannelInboundHandler<HttpObject> {
private File file;
public NettyClientHandler(String target) {
File dir = new File("src/test/resources/tmp");
dir.mkdirs();
file = new File(dir, target);
file.delete();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
throws Exception {
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
RandomAccessFile output = null;
FileChannel oc = null;
try {
output = new RandomAccessFile(file, "rw");
oc = output.getChannel();
oc.position(oc.size());
ByteBuf buffer = content.content();
for (int i = 0, len = buffer.nioBufferCount(); i < len; i++) {
oc.write(buffer.nioBuffers()[i]);
}
} finally {
IOUtils.closeQuietly(oc);
IOUtils.closeQuietly(output);
}
}
}
public File getFile() {
return file;
}
}
class NettyClientInitializer extends ChannelInitializer<SocketChannel> {
private ChannelHandler handler;
public NettyClientInitializer(ChannelHandler handler) {
this.handler = handler;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("log", new LoggingHandler(LogLevel.TRACE));
p.addLast("codec", new HttpClientCodec());
p.addLast("inflater", new HttpContentDecompressor());
// p.addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024));
p.addLast("handler", handler);
}
} | Fix blocking behavior in the Netty based test client. | src/test/java/de/ganskef/test/NettyClient_NoHttps.java | Fix blocking behavior in the Netty based test client. | <ide><path>rc/test/java/de/ganskef/test/NettyClient_NoHttps.java
<ide> import io.netty.channel.nio.NioEventLoopGroup;
<ide> import io.netty.channel.socket.SocketChannel;
<ide> import io.netty.channel.socket.nio.NioSocketChannel;
<del>import io.netty.handler.codec.http.DefaultHttpRequest;
<add>import io.netty.handler.codec.http.DefaultFullHttpRequest;
<ide> import io.netty.handler.codec.http.HttpClientCodec;
<ide> import io.netty.handler.codec.http.HttpContent;
<ide> import io.netty.handler.codec.http.HttpContentDecompressor;
<ide> import io.netty.handler.codec.http.HttpObject;
<ide> import io.netty.handler.codec.http.HttpRequest;
<ide> import io.netty.handler.codec.http.HttpVersion;
<add>import io.netty.handler.codec.http.LastHttpContent;
<ide> import io.netty.handler.logging.LogLevel;
<ide> import io.netty.handler.logging.LoggingHandler;
<add>import io.netty.handler.ssl.SslContext;
<add>import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
<ide>
<ide> import java.io.File;
<ide> import java.io.RandomAccessFile;
<ide> URI uri = new URI(url);
<ide> String host = uri.getHost();
<ide> int port = uri.getPort();
<add> if (port == -1) {
<add> if (isSecured(uri)) {
<add> port = 443;
<add> } else {
<add> port = 80;
<add> }
<add> }
<ide> return get(uri, uri.getRawPath(), host, port, target);
<add> }
<add>
<add> private boolean isSecured(URI uri) {
<add>
<add> // XXX https via offline proxy won't work with this client. I mean, this
<add> // was my experience while debugging it. I had no success with Apache
<add> // HC, too. Only URLConnection works like expected for me.
<add> //
<add> // It seems to me we have to wait for a proper solution - see:
<add> // https://github.com/netty/netty/issues/1133#event-299614098
<add> // normanmaurer modified the milestone: 4.1.0.Beta5, 4.1.0.Beta6
<add> //
<add> // return uri.getScheme().equalsIgnoreCase("https");
<add>
<add> return false;
<ide> }
<ide>
<ide> private File get(URI uri, String url, String proxyHost, int proxyPort,
<ide> final String target) throws Exception {
<del> if (url.toLowerCase().startsWith("https")) {
<del> System.out.println("HTTPS is not supported, try HTTP for " + url);
<del> }
<del> if (proxyPort == -1) {
<del> proxyPort = 80;
<add> final SslContext sslCtx;
<add> if (isSecured(uri)) {
<add> sslCtx = SslContext
<add> .newClientContext(InsecureTrustManagerFactory.INSTANCE);
<add> } else {
<add> sslCtx = null;
<ide> }
<ide> final NettyClientHandler handler = new NettyClientHandler(target);
<ide> EventLoopGroup group = new NioEventLoopGroup();
<ide> try {
<ide> Bootstrap b = new Bootstrap();
<ide> b.group(group).channel(NioSocketChannel.class)
<del> .handler(new NettyClientInitializer(handler));
<add> .handler(new NettyClientInitializer(sslCtx, handler));
<add> // .handler(new HttpSnoopClientInitializer(sslCtx));
<ide>
<ide> Channel ch = b.connect(proxyHost, proxyPort).sync().channel();
<ide>
<del> HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
<del> HttpMethod.GET, url);
<add> HttpRequest request = new DefaultFullHttpRequest(
<add> HttpVersion.HTTP_1_1, HttpMethod.GET, url);
<ide> request.headers().set(HttpHeaders.Names.HOST, uri.getHost());
<ide> request.headers().set(HttpHeaders.Names.CONNECTION,
<ide> HttpHeaders.Values.CLOSE);
<ide> IOUtils.closeQuietly(oc);
<ide> IOUtils.closeQuietly(output);
<ide> }
<add> if (content instanceof LastHttpContent) {
<add> ctx.close();
<add> }
<ide> }
<ide> }
<ide>
<ide>
<ide> private ChannelHandler handler;
<ide>
<del> public NettyClientInitializer(ChannelHandler handler) {
<add> private SslContext sslCtx;
<add>
<add> public NettyClientInitializer(SslContext sslCtx, ChannelHandler handler) {
<add> this.sslCtx = sslCtx;
<ide> this.handler = handler;
<ide> }
<ide>
<ide> @Override
<ide> protected void initChannel(SocketChannel ch) throws Exception {
<ide> ChannelPipeline p = ch.pipeline();
<add> if (sslCtx != null) {
<add> p.addLast(sslCtx.newHandler(ch.alloc()));
<add> }
<ide> p.addLast("log", new LoggingHandler(LogLevel.TRACE));
<ide> p.addLast("codec", new HttpClientCodec());
<ide> p.addLast("inflater", new HttpContentDecompressor()); |
|
Java | apache-2.0 | 31ae41b42bf8ba48c80a914c85077ac3d4f5ddd3 | 0 | apache/wink,apache/wink,apache/wink,os890/wink_patches,os890/wink_patches | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*******************************************************************************/
package org.apache.wink.server.internal;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.wink.common.WinkApplication;
import org.apache.wink.common.internal.i18n.Messages;
import org.apache.wink.common.internal.runtime.RuntimeContextTLS;
import org.apache.wink.server.internal.application.ServletApplicationFileLoader;
import org.apache.wink.server.internal.handlers.ServerMessageContext;
import org.apache.wink.server.internal.resources.HtmlServiceDocumentResource;
import org.apache.wink.server.internal.resources.RootResource;
import org.apache.wink.server.utils.RegistrationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Responsible for request processing.
*/
public class RequestProcessor {
private static final Logger logger =
LoggerFactory
.getLogger(RequestProcessor.class);
private static final String PROPERTY_ROOT_RESOURCE_NONE = "none";
private static final String PROPERTY_ROOT_RESOURCE_ATOM = "atom";
private static final String PROPERTY_ROOT_RESOURCE_ATOM_HTML = "atom+html";
private static final String PROPERTY_ROOT_RESOURCE_DEFAULT =
PROPERTY_ROOT_RESOURCE_ATOM_HTML;
private static final String PROPERTY_ROOT_RESOURCE = "wink.rootResource";
private static final String PROPERTY_ROOT_RESOURCE_CSS =
"wink.serviceDocumentCssPath";
private static final String PROPERTY_LOAD_WINK_APPLICATIONS =
"wink.loadApplications";
private final DeploymentConfiguration configuration;
public RequestProcessor(DeploymentConfiguration configuration) {
this.configuration = configuration;
registerDefaultApplication();
registerRootResources();
}
private void registerDefaultApplication() {
try {
String loadWinkApplicationsProperty =
configuration.getProperties().getProperty(PROPERTY_LOAD_WINK_APPLICATIONS,
Boolean.toString(true));
logger.debug("{} property is set to: {}",
PROPERTY_LOAD_WINK_APPLICATIONS,
loadWinkApplicationsProperty);
final Set<Class<?>> classes =
new ServletApplicationFileLoader(Boolean.parseBoolean(loadWinkApplicationsProperty))
.getClasses();
RegistrationUtils.InnerApplication application =
new RegistrationUtils.InnerApplication(classes);
application.setPriority(WinkApplication.SYSTEM_PRIORITY);
configuration.addApplication(application, true);
} catch (FileNotFoundException e) {
throw new WebApplicationException(e);
}
}
private void registerRootResources() {
Properties properties = configuration.getProperties();
String registerRootResource =
properties.getProperty(PROPERTY_ROOT_RESOURCE, PROPERTY_ROOT_RESOURCE_DEFAULT);
logger.debug("{} property is set to: {}", PROPERTY_ROOT_RESOURCE, registerRootResource);
if (registerRootResource.equals(PROPERTY_ROOT_RESOURCE_ATOM)) {
RegistrationUtils.InnerApplication application =
new RegistrationUtils.InnerApplication(RootResource.class);
application.setPriority(WinkApplication.SYSTEM_PRIORITY);
configuration.addApplication(application, true);
} else if (registerRootResource.equals(PROPERTY_ROOT_RESOURCE_NONE)) {
// do nothing
} else {
String css = properties.getProperty(PROPERTY_ROOT_RESOURCE_CSS);
logger.debug("{} property is set to: {}", PROPERTY_ROOT_RESOURCE_CSS, css);
HtmlServiceDocumentResource instance = new HtmlServiceDocumentResource();
if (css != null) {
instance.setServiceDocumentCssPath(css);
}
RegistrationUtils.InnerApplication application =
new RegistrationUtils.InnerApplication(instance);
application.setPriority(WinkApplication.SYSTEM_PRIORITY);
configuration.addApplication(application, true);
}
}
// --- request processing ---
/**
* Dispatches the request and fills the response (even with an error
* message.
*
* @param request AS or mock request
* @param response AS or mock response
* @throws IOException I/O error
*/
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
try {
handleRequestWithoutFaultBarrier(request, response);
} catch (Throwable t) {
// exception was not handled properly
if (logger.isDebugEnabled()) {
logger.debug(Messages.getMessage("unhandledExceptionToContainer"), t);
} else {
logger.info(Messages.getMessage("unhandledExceptionToContainer"));
}
if (t instanceof RuntimeException) {
// let the servlet container to handle the runtime exception
throw (RuntimeException)t;
}
throw new ServletException(t);
}
}
private void handleRequestWithoutFaultBarrier(HttpServletRequest request,
HttpServletResponse response) throws Throwable {
try {
ServerMessageContext msgContext = createMessageContext(request, response);
RuntimeContextTLS.setRuntimeContext(msgContext);
logger.debug("Set message context and starting request handlers chain: {}", msgContext);
// run the request handler chain
configuration.getRequestHandlersChain().run(msgContext);
logger
.debug("Finished request handlers chain and starting response handlers chain: {}",
msgContext);
// run the response handler chain
configuration.getResponseHandlersChain().run(msgContext);
} catch (Throwable t) {
logException(t);
ServerMessageContext msgContext = createMessageContext(request, response);
RuntimeContextTLS.setRuntimeContext(msgContext);
msgContext.setResponseEntity(t);
// run the error handler chain
logger.debug("Exception occured, starting error handlers chain: {}", msgContext);
configuration.getErrorHandlersChain().run(msgContext);
} finally {
logger.debug("Finished response handlers chain");
RuntimeContextTLS.setRuntimeContext(null);
}
}
private void logException(Throwable t) {
String messageFormat = Messages.getMessage("exceptionOccurredDuringInvocation");
String exceptionName = t.getClass().getSimpleName();
if (t instanceof WebApplicationException) {
WebApplicationException wae = (WebApplicationException)t;
int statusCode = wae.getResponse().getStatus();
Status status = Response.Status.fromStatusCode(statusCode);
String statusSep = "";
String statusMessage = "";
if (status != null) {
statusSep = " - ";
statusMessage = status.toString();
}
exceptionName =
String.format("%s (%d%s%s)", exceptionName, statusCode, statusSep, statusMessage);
if (statusCode >= 500) {
if (logger.isDebugEnabled()) {
logger.debug(String.format(messageFormat, exceptionName), t);
} else {
logger.info(String.format(messageFormat, exceptionName));
}
} else {
// don't log the whole call stack for sub-500 return codes unless debugging
if (logger.isDebugEnabled()) {
logger.debug(String.format(messageFormat, exceptionName), t);
} else {
logger.info(String.format(messageFormat, exceptionName));
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug(String.format(messageFormat, exceptionName), t);
} else {
logger.info(String.format(messageFormat, exceptionName));
}
}
}
private ServerMessageContext createMessageContext(HttpServletRequest request,
HttpServletResponse response) {
ServerMessageContext messageContext =
new ServerMessageContext(request, response, configuration);
return messageContext;
}
public DeploymentConfiguration getConfiguration() {
return configuration;
}
public static RequestProcessor getRequestProcessor(ServletContext servletContext,
String attributeName) {
if (attributeName == null) {
attributeName = RequestProcessor.class.getName();
}
RequestProcessor requestProcessor =
(RequestProcessor)servletContext.getAttribute(attributeName);
logger
.debug("Retrieving request processor {} using attribute name {} in servlet context {}",
new Object[] {requestProcessor, attributeName, servletContext});
return requestProcessor;
}
public void storeRequestProcessorOnServletContext(ServletContext servletContext,
String attributeName) {
if (attributeName == null || attributeName.length() == 0) {
attributeName = RequestProcessor.class.getName();
}
logger.debug("Storing request processor {} using attribute name {} in servlet context {}",
new Object[] {this, attributeName, servletContext});
servletContext.setAttribute(attributeName, this);
}
}
| wink-server/src/main/java/org/apache/wink/server/internal/RequestProcessor.java | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*******************************************************************************/
package org.apache.wink.server.internal;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.wink.common.WinkApplication;
import org.apache.wink.common.internal.i18n.Messages;
import org.apache.wink.common.internal.runtime.RuntimeContextTLS;
import org.apache.wink.server.internal.application.ServletApplicationFileLoader;
import org.apache.wink.server.internal.handlers.ServerMessageContext;
import org.apache.wink.server.internal.resources.HtmlServiceDocumentResource;
import org.apache.wink.server.internal.resources.RootResource;
import org.apache.wink.server.utils.RegistrationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Responsible for request processing.
*/
public class RequestProcessor {
private static final Logger logger =
LoggerFactory
.getLogger(RequestProcessor.class);
private static final String PROPERTY_ROOT_RESOURCE_NONE = "none";
private static final String PROPERTY_ROOT_RESOURCE_ATOM = "atom";
private static final String PROPERTY_ROOT_RESOURCE_ATOM_HTML = "atom+html";
private static final String PROPERTY_ROOT_RESOURCE_DEFAULT =
PROPERTY_ROOT_RESOURCE_ATOM_HTML;
private static final String PROPERTY_ROOT_RESOURCE = "wink.rootResource";
private static final String PROPERTY_ROOT_RESOURCE_CSS =
"wink.serviceDocumentCssPath";
private static final String PROPERTY_LOAD_WINK_APPLICATIONS =
"wink.loadApplications";
private final DeploymentConfiguration configuration;
public RequestProcessor(DeploymentConfiguration configuration) {
this.configuration = configuration;
registerDefaultApplication();
registerRootResources();
}
private void registerDefaultApplication() {
try {
String loadWinkApplicationsProperty =
configuration.getProperties().getProperty(PROPERTY_LOAD_WINK_APPLICATIONS,
Boolean.toString(true));
logger.debug("{} property is set to: {}",
PROPERTY_LOAD_WINK_APPLICATIONS,
loadWinkApplicationsProperty);
final Set<Class<?>> classes =
new ServletApplicationFileLoader(Boolean.parseBoolean(loadWinkApplicationsProperty))
.getClasses();
RegistrationUtils.InnerApplication application =
new RegistrationUtils.InnerApplication(classes);
application.setPriority(WinkApplication.SYSTEM_PRIORITY);
configuration.addApplication(application, true);
} catch (FileNotFoundException e) {
throw new WebApplicationException(e);
}
}
private void registerRootResources() {
Properties properties = configuration.getProperties();
String registerRootResource =
properties.getProperty(PROPERTY_ROOT_RESOURCE, PROPERTY_ROOT_RESOURCE_DEFAULT);
logger.debug("{} property is set to: {}", PROPERTY_ROOT_RESOURCE, registerRootResource);
if (registerRootResource.equals(PROPERTY_ROOT_RESOURCE_ATOM)) {
RegistrationUtils.InnerApplication application =
new RegistrationUtils.InnerApplication(RootResource.class);
application.setPriority(WinkApplication.SYSTEM_PRIORITY);
configuration.addApplication(application, true);
} else if (registerRootResource.equals(PROPERTY_ROOT_RESOURCE_NONE)) {
// do nothing
} else {
String css = properties.getProperty(PROPERTY_ROOT_RESOURCE_CSS);
logger.debug("{} property is set to: {}", PROPERTY_ROOT_RESOURCE_CSS, css);
HtmlServiceDocumentResource instance = new HtmlServiceDocumentResource();
if (css != null) {
instance.setServiceDocumentCssPath(css);
}
RegistrationUtils.InnerApplication application =
new RegistrationUtils.InnerApplication(instance);
application.setPriority(WinkApplication.SYSTEM_PRIORITY);
configuration.addApplication(application, true);
}
}
// --- request processing ---
/**
* Dispatches the request and fills the response (even with an error
* message.
*
* @param request AS or mock request
* @param response AS or mock response
* @throws IOException I/O error
*/
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
try {
handleRequestWithoutFaultBarrier(request, response);
} catch (Throwable t) {
// exception was not handled properly
logger.error(Messages.getMessage("unhandledExceptionToContainer"), t);
if (t instanceof RuntimeException) {
// let the servlet container to handle the runtime exception
throw (RuntimeException)t;
}
throw new ServletException(t);
}
}
private void handleRequestWithoutFaultBarrier(HttpServletRequest request,
HttpServletResponse response) throws Throwable {
try {
ServerMessageContext msgContext = createMessageContext(request, response);
RuntimeContextTLS.setRuntimeContext(msgContext);
logger.debug("Set message context and starting request handlers chain: {}", msgContext);
// run the request handler chain
configuration.getRequestHandlersChain().run(msgContext);
logger
.debug("Finished request handlers chain and starting response handlers chain: {}",
msgContext);
// run the response handler chain
configuration.getResponseHandlersChain().run(msgContext);
} catch (Throwable t) {
logException(t);
ServerMessageContext msgContext = createMessageContext(request, response);
RuntimeContextTLS.setRuntimeContext(msgContext);
msgContext.setResponseEntity(t);
// run the error handler chain
logger.debug("Exception occured, starting error handlers chain: {}", msgContext);
configuration.getErrorHandlersChain().run(msgContext);
} finally {
logger.debug("Finished response handlers chain");
RuntimeContextTLS.setRuntimeContext(null);
}
}
private void logException(Throwable t) {
String messageFormat = Messages.getMessage("exceptionOccurredDuringInvocation");
String exceptionName = t.getClass().getSimpleName();
if (t instanceof WebApplicationException) {
WebApplicationException wae = (WebApplicationException)t;
int statusCode = wae.getResponse().getStatus();
Status status = Response.Status.fromStatusCode(statusCode);
String statusSep = "";
String statusMessage = "";
if (status != null) {
statusSep = " - ";
statusMessage = status.toString();
}
exceptionName =
String.format("%s (%d%s%s)", exceptionName, statusCode, statusSep, statusMessage);
if (statusCode >= 500) {
logger.error(String.format(messageFormat, exceptionName), t);
} else {
// don't log the whole call stack for sub-500 return codes unless debugging
if (logger.isDebugEnabled()) {
logger.debug(String.format(messageFormat, exceptionName), t);
} else {
logger.info(String.format(messageFormat, exceptionName));
}
}
} else {
logger.error(String.format(messageFormat, exceptionName), t);
}
}
private ServerMessageContext createMessageContext(HttpServletRequest request,
HttpServletResponse response) {
ServerMessageContext messageContext =
new ServerMessageContext(request, response, configuration);
return messageContext;
}
public DeploymentConfiguration getConfiguration() {
return configuration;
}
public static RequestProcessor getRequestProcessor(ServletContext servletContext,
String attributeName) {
if (attributeName == null) {
attributeName = RequestProcessor.class.getName();
}
RequestProcessor requestProcessor =
(RequestProcessor)servletContext.getAttribute(attributeName);
logger
.debug("Retrieving request processor {} using attribute name {} in servlet context {}",
new Object[] {requestProcessor, attributeName, servletContext});
return requestProcessor;
}
public void storeRequestProcessorOnServletContext(ServletContext servletContext,
String attributeName) {
if (attributeName == null || attributeName.length() == 0) {
attributeName = RequestProcessor.class.getName();
}
logger.debug("Storing request processor {} using attribute name {} in servlet context {}",
new Object[] {this, attributeName, servletContext});
servletContext.setAttribute(attributeName, this);
}
}
| Reduce logging in error path case
Stacktraces/exception objects still avaialble
in debug mode but in normal mode a simpler
info message is logged. Exception still thrown
to container and in Geronim/Tomcat this
means the stack trace is still printed out to
the container log outside of Wink.
See [WINK-240]
git-svn-id: 00d204a5454029cb4c4f043d44e9809460a5ea01@890399 13f79535-47bb-0310-9956-ffa450edef68
| wink-server/src/main/java/org/apache/wink/server/internal/RequestProcessor.java | Reduce logging in error path case | <ide><path>ink-server/src/main/java/org/apache/wink/server/internal/RequestProcessor.java
<ide> handleRequestWithoutFaultBarrier(request, response);
<ide> } catch (Throwable t) {
<ide> // exception was not handled properly
<del> logger.error(Messages.getMessage("unhandledExceptionToContainer"), t);
<add> if (logger.isDebugEnabled()) {
<add> logger.debug(Messages.getMessage("unhandledExceptionToContainer"), t);
<add> } else {
<add> logger.info(Messages.getMessage("unhandledExceptionToContainer"));
<add> }
<ide> if (t instanceof RuntimeException) {
<ide> // let the servlet container to handle the runtime exception
<ide> throw (RuntimeException)t;
<ide> exceptionName =
<ide> String.format("%s (%d%s%s)", exceptionName, statusCode, statusSep, statusMessage);
<ide> if (statusCode >= 500) {
<del> logger.error(String.format(messageFormat, exceptionName), t);
<add> if (logger.isDebugEnabled()) {
<add> logger.debug(String.format(messageFormat, exceptionName), t);
<add> } else {
<add> logger.info(String.format(messageFormat, exceptionName));
<add> }
<ide> } else {
<ide> // don't log the whole call stack for sub-500 return codes unless debugging
<ide> if (logger.isDebugEnabled()) {
<ide> }
<ide> }
<ide> } else {
<del> logger.error(String.format(messageFormat, exceptionName), t);
<add> if (logger.isDebugEnabled()) {
<add> logger.debug(String.format(messageFormat, exceptionName), t);
<add> } else {
<add> logger.info(String.format(messageFormat, exceptionName));
<add> }
<ide> }
<ide> }
<ide> |
|
Java | lgpl-2.1 | d3d0973548d7f047e1778fb56d674bf22a2cd50e | 0 | meg0man/languagetool,meg0man/languagetool,janissl/languagetool,janissl/languagetool,lopescan/languagetool,meg0man/languagetool,lopescan/languagetool,jimregan/languagetool,languagetool-org/languagetool,lopescan/languagetool,jimregan/languagetool,languagetool-org/languagetool,janissl/languagetool,lopescan/languagetool,janissl/languagetool,janissl/languagetool,jimregan/languagetool,languagetool-org/languagetool,lopescan/languagetool,meg0man/languagetool,jimregan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,meg0man/languagetool,jimregan/languagetool,janissl/languagetool | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package de.danielnaber.languagetool.gui;
import java.awt.AWTException;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileFilter;
import javax.xml.parsers.ParserConfigurationException;
import org.jdesktop.jdic.tray.SystemTray;
import org.jdesktop.jdic.tray.TrayIcon;
import org.xml.sax.SAXException;
import de.danielnaber.languagetool.JLanguageTool;
import de.danielnaber.languagetool.Language;
import de.danielnaber.languagetool.language.RuleFilenameException;
import de.danielnaber.languagetool.rules.Rule;
import de.danielnaber.languagetool.rules.RuleMatch;
import de.danielnaber.languagetool.server.HTTPServer;
import de.danielnaber.languagetool.server.PortBindingException;
import de.danielnaber.languagetool.tools.StringTools;
/**
* A simple GUI to check texts with.
*
* @author Daniel Naber
*/
public final class Main implements ActionListener {
private static final String HTML_FONT_START = "<font face='Arial,Helvetica'>";
private static final String HTML_FONT_END = "</font>";
private static final String SYSTEM_TRAY_ICON_NAME = "/TrayIcon.png";
private static final String SYSTEM_TRAY_TOOLTIP = "LanguageTool";
private static final String CONFIG_FILE = ".languagetool.cfg";
private static final int WINDOW_WIDTH = 600;
private static final int WINDOW_HEIGHT = 550;
private final ResourceBundle messages;
private final Configuration config;
private JFrame frame;
private JTextArea textArea;
private JTextPane resultArea;
private JComboBox languageBox;
private HTTPServer httpServer;
private final Map<Language, ConfigurationDialog> configDialogs = new HashMap<Language, ConfigurationDialog>();
private boolean closeHidesToTray;
private boolean isInTray;
private Main() throws IOException {
config = new Configuration(new File(System.getProperty("user.home")), CONFIG_FILE);
messages = JLanguageTool.getMessageBundle();
maybeStartServer();
}
private void createGUI() {
frame = new JFrame("LanguageTool " + JLanguageTool.VERSION);
setLookAndFeel();
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new CloseListener());
frame.setIconImage(new ImageIcon(JLanguageTool.getDataBroker().getFromResourceDirAsUrl(
Main.SYSTEM_TRAY_ICON_NAME)).getImage());
frame.setJMenuBar(new MainMenuBar(this, messages));
textArea = new JTextArea(messages.getString("guiDemoText"));
// TODO: wrong line number is displayed for lines that are wrapped automatically:
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
resultArea = new JTextPane();
resultArea.setContentType("text/html");
resultArea.setText(HTML_FONT_START + messages.getString("resultAreaText")
+ HTML_FONT_END);
resultArea.setEditable(false);
final JLabel label = new JLabel(messages.getString("enterText"));
final JButton button = new JButton(StringTools.getLabel(messages
.getString("checkText")));
button
.setMnemonic(StringTools.getMnemonic(messages.getString("checkText")));
button.addActionListener(this);
final JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
final GridBagConstraints buttonCons = new GridBagConstraints();
buttonCons.gridx = 0;
buttonCons.gridy = 0;
panel.add(button, buttonCons);
buttonCons.gridx = 1;
buttonCons.gridy = 0;
panel.add(new JLabel(" " + messages.getString("textLanguage") + " "), buttonCons);
buttonCons.gridx = 2;
buttonCons.gridy = 0;
languageBox = new JComboBox();
populateLanguageBox(languageBox);
panel.add(languageBox, buttonCons);
final Container contentPane = frame.getContentPane();
final GridBagLayout gridLayout = new GridBagLayout();
contentPane.setLayout(gridLayout);
final GridBagConstraints cons = new GridBagConstraints();
cons.insets = new Insets(5, 5, 5, 5);
cons.fill = GridBagConstraints.BOTH;
cons.weightx = 10.0f;
cons.weighty = 10.0f;
cons.gridx = 0;
cons.gridy = 1;
cons.weighty = 5.0f;
final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
new JScrollPane(textArea), new JScrollPane(resultArea));
splitPane.setDividerLocation(200);
contentPane.add(splitPane, cons);
cons.fill = GridBagConstraints.NONE;
cons.gridx = 0;
cons.gridy = 2;
cons.weighty = 0.0f;
cons.insets = new Insets(3, 3, 3, 3);
// cons.fill = GridBagConstraints.NONE;
contentPane.add(label, cons);
cons.gridy = 3;
contentPane.add(panel, cons);
frame.pack();
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
}
private void setLookAndFeel() {
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception ex) {
// Well, what can we do...
}
}
private void populateLanguageBox(final JComboBox languageBox) {
languageBox.removeAllItems();
final List<I18nLanguage> i18nLanguages = new ArrayList<I18nLanguage>();
for (Language language : Language.LANGUAGES) {
if (language != Language.DEMO) {
i18nLanguages.add(new I18nLanguage(language));
}
}
Collections.sort(i18nLanguages);
final String defaultLocale = Locale.getDefault().getLanguage();
String defaultLocaleInGui = null;
try {
defaultLocaleInGui = messages.getString(defaultLocale);
} catch (final MissingResourceException e) {
// language not supported, so don't select a default
}
for (final I18nLanguage i18nLanguage : i18nLanguages) {
languageBox.addItem(i18nLanguage);
if (i18nLanguage.toString().equals(defaultLocaleInGui)) {
languageBox.setSelectedItem(i18nLanguage);
}
}
}
private void showGUI() {
frame.setVisible(true);
}
public void actionPerformed(final ActionEvent e) {
try {
if (e.getActionCommand().equals(
StringTools.getLabel(messages.getString("checkText")))) {
final JLanguageTool langTool = getCurrentLanguageTool();
checkTextAndDisplayResults(langTool, getCurrentLanguage());
} else {
throw new IllegalArgumentException("Unknown action " + e);
}
} catch (final Exception exc) {
Tools.showError(exc);
}
}
void loadFile() {
final File file = Tools.openFileDialog(frame, new PlainTextFileFilter());
if (file == null) {
// user clicked cancel
return;
}
try {
final String fileContents = StringTools.readFile(new FileInputStream(file
.getAbsolutePath()));
textArea.setText(fileContents);
final JLanguageTool langTool = getCurrentLanguageTool();
checkTextAndDisplayResults(langTool, getCurrentLanguage());
} catch (final IOException e) {
Tools.showError(e);
}
}
void hideToTray() {
final String version = System.getProperty("java.version");
if (!isInTray && version.startsWith("1.5")) { // we don't run under <= 1.4,
// so we don't check for that
TrayIcon trayIcon = null;
try {
final Icon sysTrayIcon = new ImageIcon(JLanguageTool.getDataBroker().getFromResourceDirAsUrl(Main.SYSTEM_TRAY_ICON_NAME));
trayIcon = new TrayIcon(sysTrayIcon);
} catch (final NoClassDefFoundError e) {
throw new MissingJdicException(e);
}
final SystemTray tray = SystemTray.getDefaultSystemTray();
trayIcon.addActionListener(new TrayActionListener());
trayIcon.setToolTip(SYSTEM_TRAY_TOOLTIP);
tray.addTrayIcon(trayIcon);
} else if (!isInTray) {
// Java 1.6 or later
final java.awt.SystemTray tray = java.awt.SystemTray.getSystemTray();
final Image img = Toolkit.getDefaultToolkit().getImage(
JLanguageTool.getDataBroker().getFromResourceDirAsUrl(Main.SYSTEM_TRAY_ICON_NAME));
final PopupMenu popup = makePopupMenu();
try {
final java.awt.TrayIcon trayIcon = new java.awt.TrayIcon(img,
"tooltip", popup);
trayIcon.addMouseListener(new TrayActionListener());
trayIcon.setToolTip(SYSTEM_TRAY_TOOLTIP);
tray.add(trayIcon);
} catch (final AWTException e1) {
// thrown if there's no system tray
Tools.showError(e1);
}
}
isInTray = true;
frame.setVisible(false);
}
private PopupMenu makePopupMenu() {
final PopupMenu popup = new PopupMenu();
final ActionListener rmbListener = new TrayActionRMBListener();
// Check clipboard text:
final MenuItem checkClipboardItem = new MenuItem(StringTools
.getLabel(messages.getString("guiMenuCheckClipboard")));
checkClipboardItem.addActionListener(rmbListener);
popup.add(checkClipboardItem);
// Open main window:
final MenuItem restoreItem = new MenuItem(StringTools.getLabel(messages
.getString("guiMenuShowMainWindow")));
restoreItem.addActionListener(rmbListener);
popup.add(restoreItem);
// Exit:
final MenuItem exitItem = new MenuItem(StringTools.getLabel(messages
.getString("guiMenuQuit")));
exitItem.addActionListener(rmbListener);
popup.add(exitItem);
return popup;
}
void addLanguage() {
final LanguageManagerDialog lmd = new LanguageManagerDialog(frame, Language
.getExternalLanguages());
lmd.show();
try {
Language.reInit(lmd.getLanguages());
} catch (final RuleFilenameException e) {
Tools.showErrorMessage(e);
}
populateLanguageBox(languageBox);
}
void showOptions() {
final JLanguageTool langTool = getCurrentLanguageTool();
final List<Rule> rules = langTool.getAllRules();
final ConfigurationDialog configDialog = getCurrentConfigDialog();
configDialog.show(rules); // this blocks until OK/Cancel is clicked in the dialog
config.setDisabledRuleIds(configDialog.getDisabledRuleIds());
config.setEnabledRuleIds(configDialog.getEnabledRuleIds());
config.setDisabledCategoryNames(configDialog.getDisabledCategoryNames());
config.setMotherTongue(configDialog.getMotherTongue());
config.setRunServer(configDialog.getRunServer());
config.setServerPort(configDialog.getServerPort());
// Stop server, start new server if requested:
stopServer();
maybeStartServer();
}
private void restoreFromTray() {
frame.setVisible(true);
}
// show GUI and check the text from clipboard/selection:
private void restoreFromTrayAndCheck() {
final String s = getClipboardText();
restoreFromTray();
textArea.setText(s);
final JLanguageTool langTool = getCurrentLanguageTool();
checkTextAndDisplayResults(langTool, getCurrentLanguage());
}
void checkClipboardText() {
final String s = getClipboardText();
textArea.setText(s);
final JLanguageTool langTool = getCurrentLanguageTool();
checkTextAndDisplayResults(langTool, getCurrentLanguage());
}
private String getClipboardText() {
// get text from clipboard or selection:
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemSelection();
if (clipboard == null) { // on Windows
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
String s;
final Transferable data = clipboard.getContents(this);
try {
if (data != null
&& data.isDataFlavorSupported(DataFlavor.getTextPlainUnicodeFlavor())) {
final DataFlavor df = DataFlavor.getTextPlainUnicodeFlavor();
final Reader sr = df.getReaderForText(data);
s = StringTools.readerToString(sr);
} else {
s = "";
}
} catch (final Exception ex) {
ex.printStackTrace();
if (data != null) {
s = data.toString();
} else {
s = "";
}
}
return s;
}
void quitOrHide() {
if (closeHidesToTray) {
hideToTray();
} else {
quit();
}
}
void quit() {
stopServer();
try {
config.saveConfiguration();
} catch (final IOException e) {
Tools.showError(e);
}
frame.setVisible(false);
System.exit(0);
}
private void maybeStartServer() {
if (config.getRunServer()) {
httpServer = new HTTPServer(config.getServerPort());
try {
httpServer.run();
} catch (final PortBindingException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void stopServer() {
if (httpServer != null) {
httpServer.stop();
httpServer = null;
}
}
private Language getCurrentLanguage() {
return ((I18nLanguage) languageBox.getSelectedItem()).getLanguage();
}
private ConfigurationDialog getCurrentConfigDialog() {
final Language language = getCurrentLanguage();
final ConfigurationDialog configDialog;
if (configDialogs.containsKey(language)) {
configDialog = configDialogs.get(language);
} else {
configDialog = new ConfigurationDialog(frame, false);
configDialog.setMotherTongue(config.getMotherTongue());
configDialog.setDisabledRules(config.getDisabledRuleIds());
configDialog.setEnabledRules(config.getEnabledRuleIds());
configDialog.setDisabledCategories(config.getDisabledCategoryNames());
configDialog.setRunServer(config.getRunServer());
configDialog.setServerPort(config.getServerPort());
configDialogs.put(language, configDialog);
}
return configDialog;
}
private JLanguageTool getCurrentLanguageTool() {
final JLanguageTool langTool;
try {
final ConfigurationDialog configDialog = getCurrentConfigDialog();
langTool = new JLanguageTool(getCurrentLanguage(), configDialog
.getMotherTongue());
langTool.activateDefaultPatternRules();
langTool.activateDefaultFalseFriendRules();
final Set<String> disabledRules = configDialog.getDisabledRuleIds();
if (disabledRules != null) {
for (final String ruleId : disabledRules) {
langTool.disableRule(ruleId);
}
}
final Set<String> disabledCategories = configDialog
.getDisabledCategoryNames();
if (disabledCategories != null) {
for (final String categoryName : disabledCategories) {
langTool.disableCategory(categoryName);
}
}
final Set<String> enabledRules = configDialog.getEnabledRuleIds();
if (enabledRules != null) {
for (String ruleName : enabledRules) {
langTool.enableDefaultOffRule(ruleName);
langTool.enableRule(ruleName);
}
}
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
} catch (final ParserConfigurationException ex) {
throw new RuntimeException(ex);
} catch (final SAXException ex) {
throw new RuntimeException(ex);
}
return langTool;
}
private void checkTextAndDisplayResults(final JLanguageTool langTool,
final Language lang) {
if (StringTools.isEmpty(textArea.getText().trim())) {
textArea.setText(messages.getString("enterText2"));
} else {
final StringBuilder sb = new StringBuilder();
final String startCheckText = Tools.makeTexti18n(messages,
"startChecking", new Object[] { lang.getTranslatedName(messages) });
resultArea.setText(HTML_FONT_START + startCheckText + "<br>\n"
+ HTML_FONT_END);
resultArea.repaint(); // FIXME: why doesn't this work?
// TODO: resultArea.setCursor(new Cursor(Cursor.WAIT_CURSOR));
sb.append(startCheckText);
sb.append("...<br>\n");
int matches = 0;
try {
matches = checkText(langTool, textArea.getText(), sb);
} catch (final Exception ex) {
sb.append("<br><br><b><font color=\"red\">" + ex.toString() + "<br>");
final StackTraceElement[] elements = ex.getStackTrace();
for (final StackTraceElement element : elements) {
sb.append(element);
sb.append("<br>");
}
sb.append("</font></b><br>");
ex.printStackTrace();
}
final String checkDone = Tools.makeTexti18n(messages, "checkDone",
new Object[] {matches});
sb.append(checkDone);
sb.append("<br>\n");
resultArea.setText(HTML_FONT_START + sb.toString() + HTML_FONT_END);
resultArea.setCaretPosition(0);
}
}
private int checkText(final JLanguageTool langTool, final String text,
final StringBuilder sb) throws IOException {
final long startTime = System.currentTimeMillis();
final List<RuleMatch> ruleMatches = langTool.check(text);
final long startTimeMatching = System.currentTimeMillis();
int i = 0;
for (final RuleMatch match : ruleMatches) {
final String output = Tools.makeTexti18n(messages, "result1",
new Object[] {i + 1,
match.getLine() + 1,
match.getColumn()});
sb.append(output);
String msg = match.getMessage();
msg = msg.replaceAll("<suggestion>", "<b>");
msg = msg.replaceAll("</suggestion>", "</b>");
msg = msg.replaceAll("<old>", "<b>");
msg = msg.replaceAll("</old>", "</b>");
sb.append("<b>" + messages.getString("errorMessage") + "</b> " + msg + "<br>\n");
if (match.getSuggestedReplacements().size() > 0) {
final String repl = StringTools.listToString(match
.getSuggestedReplacements(), "; ");
sb.append("<b>" + messages.getString("correctionMessage") + "</b> "
+ repl + "<br>\n");
}
final String context = Tools.getContext(match.getFromPos(), match
.getToPos(), text);
sb.append("<b>" + messages.getString("errorContext") + "</b> " + context);
sb.append("<br>\n");
i++;
}
final long endTime = System.currentTimeMillis();
sb.append(Tools.makeTexti18n(messages, "resultTime", new Object[] {
endTime - startTime,
endTime - startTimeMatching}));
return ruleMatches.size();
}
private void setTrayMode(boolean trayMode) {
this.closeHidesToTray = trayMode;
}
public static void main(final String[] args) {
try {
final Main prg = new Main();
if (args.length == 1
&& (args[0].equals("-t") || args[0].equals("--tray"))) {
// dock to systray on startup
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
prg.createGUI();
prg.setTrayMode(true);
prg.hideToTray();
} catch (final MissingJdicException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
} catch (final Exception e) {
Tools.showError(e);
System.exit(1);
}
}
});
} else if (args.length >= 1) {
System.out
.println("Usage: java de.danielnaber.languagetool.gui.Main [-t|--tray]");
System.out
.println(" -t, --tray: dock LanguageTool to system tray on startup");
prg.stopServer();
} else {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
prg.createGUI();
prg.showGUI();
} catch (final Exception e) {
Tools.showError(e);
}
}
});
}
} catch (final Exception e) {
Tools.showError(e);
}
}
//
// The System Tray stuff
//
class TrayActionRMBListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase(
StringTools.getLabel(messages.getString("guiMenuCheckClipboard")))) {
restoreFromTrayAndCheck();
} else if (e.getActionCommand().equalsIgnoreCase(
StringTools.getLabel(messages.getString("guiMenuShowMainWindow")))) {
restoreFromTray();
} else if (e.getActionCommand().equalsIgnoreCase(
StringTools.getLabel(messages.getString("guiMenuQuit")))) {
quit();
} else {
JOptionPane.showMessageDialog(null, "Unknown action: "
+ e.getActionCommand(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
class TrayActionListener implements ActionListener, MouseListener {
// for Java 1.5 / Jdic:
public void actionPerformed(@SuppressWarnings("unused")ActionEvent e) {
handleClick();
}
// Java 1.6:
public void mouseClicked(@SuppressWarnings("unused")MouseEvent e) {
handleClick();
}
private void handleClick() {
if (frame.isVisible() && frame.isActive()) {
frame.setVisible(false);
} else if (frame.isVisible() && !frame.isActive()) {
frame.toFront();
restoreFromTrayAndCheck();
} else {
restoreFromTrayAndCheck();
}
}
public void mouseEntered(@SuppressWarnings("unused") MouseEvent e) {
}
public void mouseExited(@SuppressWarnings("unused")MouseEvent e) {
}
public void mousePressed(@SuppressWarnings("unused")MouseEvent e) {
}
public void mouseReleased(@SuppressWarnings("unused")MouseEvent e) {
}
}
class CloseListener implements WindowListener {
public void windowClosing(@SuppressWarnings("unused")WindowEvent e) {
quitOrHide();
}
public void windowActivated(@SuppressWarnings("unused")WindowEvent e) {
}
public void windowClosed(@SuppressWarnings("unused")WindowEvent e) {
}
public void windowDeactivated(@SuppressWarnings("unused")WindowEvent e) {
}
public void windowDeiconified(@SuppressWarnings("unused")WindowEvent e) {
}
public void windowIconified(@SuppressWarnings("unused")WindowEvent e) {
}
public void windowOpened(@SuppressWarnings("unused")WindowEvent e) {
}
}
static class PlainTextFileFilter extends FileFilter {
@Override
public boolean accept(final File f) {
return f.getName().toLowerCase().endsWith(".txt");
}
@Override
public String getDescription() {
return "*.txt";
}
}
private class I18nLanguage implements Comparable<I18nLanguage> {
private final Language language;
I18nLanguage(Language language) {
this.language = language;
}
Language getLanguage() {
return language;
}
// used by the GUI:
@Override
public String toString() {
if (language.isExternal()) {
return language.getName() + " (ext.)";
} else {
return messages.getString(language.getShortName());
}
}
@Override
public int compareTo(I18nLanguage o) {
return toString().compareTo(o.toString());
}
}
}
| trunk/JLanguageTool/src/java/de/danielnaber/languagetool/gui/Main.java | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package de.danielnaber.languagetool.gui;
import java.awt.AWTException;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileFilter;
import javax.xml.parsers.ParserConfigurationException;
import org.jdesktop.jdic.tray.SystemTray;
import org.jdesktop.jdic.tray.TrayIcon;
import org.xml.sax.SAXException;
import de.danielnaber.languagetool.JLanguageTool;
import de.danielnaber.languagetool.Language;
import de.danielnaber.languagetool.language.RuleFilenameException;
import de.danielnaber.languagetool.rules.Rule;
import de.danielnaber.languagetool.rules.RuleMatch;
import de.danielnaber.languagetool.server.HTTPServer;
import de.danielnaber.languagetool.server.PortBindingException;
import de.danielnaber.languagetool.tools.StringTools;
/**
* A simple GUI to check texts with.
*
* @author Daniel Naber
*/
public final class Main implements ActionListener {
private static final String HTML_FONT_START = "<font face='Arial,Helvetica'>";
private static final String HTML_FONT_END = "</font>";
private static final String SYSTEM_TRAY_ICON_NAME = "/TrayIcon.png";
private static final String SYSTEM_TRAY_TOOLTIP = "LanguageTool";
private static final String CONFIG_FILE = ".languagetool.cfg";
private static final int WINDOW_WIDTH = 600;
private static final int WINDOW_HEIGHT = 550;
private final ResourceBundle messages;
private final Configuration config;
private JFrame frame;
private JTextArea textArea;
private JTextPane resultArea;
private JComboBox languageBox;
private HTTPServer httpServer;
private final Map<Language, ConfigurationDialog> configDialogs = new HashMap<Language, ConfigurationDialog>();
private boolean closeHidesToTray;
private boolean isInTray;
private Main() throws IOException {
config = new Configuration(new File(System.getProperty("user.home")), CONFIG_FILE);
messages = JLanguageTool.getMessageBundle();
maybeStartServer();
}
private void createGUI() {
frame = new JFrame("LanguageTool " + JLanguageTool.VERSION);
setLookAndFeel();
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new CloseListener());
frame.setIconImage(new ImageIcon(JLanguageTool.getDataBroker().getFromResourceDirAsUrl(
Main.SYSTEM_TRAY_ICON_NAME)).getImage());
frame.setJMenuBar(new MainMenuBar(this, messages));
textArea = new JTextArea(messages.getString("guiDemoText"));
// TODO: wrong line number is displayed for lines that are wrapped automatically:
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
resultArea = new JTextPane();
resultArea.setContentType("text/html");
resultArea.setText(HTML_FONT_START + messages.getString("resultAreaText")
+ HTML_FONT_END);
resultArea.setEditable(false);
final JLabel label = new JLabel(messages.getString("enterText"));
final JButton button = new JButton(StringTools.getLabel(messages
.getString("checkText")));
button
.setMnemonic(StringTools.getMnemonic(messages.getString("checkText")));
button.addActionListener(this);
final JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
final GridBagConstraints buttonCons = new GridBagConstraints();
buttonCons.gridx = 0;
buttonCons.gridy = 0;
panel.add(button, buttonCons);
buttonCons.gridx = 1;
buttonCons.gridy = 0;
panel.add(new JLabel(" " + messages.getString("textLanguage") + " "), buttonCons);
buttonCons.gridx = 2;
buttonCons.gridy = 0;
languageBox = new JComboBox();
populateLanguageBox(languageBox);
panel.add(languageBox, buttonCons);
final Container contentPane = frame.getContentPane();
final GridBagLayout gridLayout = new GridBagLayout();
contentPane.setLayout(gridLayout);
final GridBagConstraints cons = new GridBagConstraints();
cons.insets = new Insets(5, 5, 5, 5);
cons.fill = GridBagConstraints.BOTH;
cons.weightx = 10.0f;
cons.weighty = 10.0f;
cons.gridx = 0;
cons.gridy = 1;
cons.weighty = 5.0f;
final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
new JScrollPane(textArea), new JScrollPane(resultArea));
splitPane.setDividerLocation(200);
contentPane.add(splitPane, cons);
cons.fill = GridBagConstraints.NONE;
cons.gridx = 0;
cons.gridy = 2;
cons.weighty = 0.0f;
cons.insets = new Insets(3, 3, 3, 3);
// cons.fill = GridBagConstraints.NONE;
contentPane.add(label, cons);
cons.gridy = 3;
contentPane.add(panel, cons);
frame.pack();
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
}
private void setLookAndFeel() {
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception ex) {
// Well, what can we do...
}
}
private void populateLanguageBox(final JComboBox languageBox) {
languageBox.removeAllItems();
final List<I18nLanguage> i18nLanguages = new ArrayList<I18nLanguage>();
for (Language language : Language.LANGUAGES) {
if (language != Language.DEMO) {
i18nLanguages.add(new I18nLanguage(language));
}
}
Collections.sort(i18nLanguages);
final String defaultLocale = Locale.getDefault().getLanguage();
String defaultLocaleInGui = null;
try {
defaultLocaleInGui = messages.getString(defaultLocale);
} catch (final MissingResourceException e) {
// language not supported, so don't select a default
}
for (final I18nLanguage i18nLanguage : i18nLanguages) {
languageBox.addItem(i18nLanguage);
if (i18nLanguage.toString().equals(defaultLocaleInGui)) {
languageBox.setSelectedItem(i18nLanguage);
}
}
}
private void showGUI() {
frame.setVisible(true);
}
public void actionPerformed(final ActionEvent e) {
try {
if (e.getActionCommand().equals(
StringTools.getLabel(messages.getString("checkText")))) {
final JLanguageTool langTool = getCurrentLanguageTool();
checkTextAndDisplayResults(langTool, getCurrentLanguage());
} else {
throw new IllegalArgumentException("Unknown action " + e);
}
} catch (final Exception exc) {
Tools.showError(exc);
}
}
void loadFile() {
final File file = Tools.openFileDialog(frame, new PlainTextFileFilter());
if (file == null) {
// user clicked cancel
return;
}
try {
final String fileContents = StringTools.readFile(new FileInputStream(file
.getAbsolutePath()));
textArea.setText(fileContents);
final JLanguageTool langTool = getCurrentLanguageTool();
checkTextAndDisplayResults(langTool, getCurrentLanguage());
} catch (final IOException e) {
Tools.showError(e);
}
}
void hideToTray() {
final String version = System.getProperty("java.version");
if (!isInTray && version.startsWith("1.5")) { // we don't run under <= 1.4,
// so we don't check for that
TrayIcon trayIcon = null;
try {
final Icon sysTrayIcon = new ImageIcon(JLanguageTool.getDataBroker().getFromResourceDirAsUrl(Main.SYSTEM_TRAY_ICON_NAME));
trayIcon = new TrayIcon(sysTrayIcon);
} catch (final NoClassDefFoundError e) {
throw new MissingJdicException(e);
}
final SystemTray tray = SystemTray.getDefaultSystemTray();
trayIcon.addActionListener(new TrayActionListener());
trayIcon.setToolTip(SYSTEM_TRAY_TOOLTIP);
tray.addTrayIcon(trayIcon);
} else if (!isInTray) {
// Java 1.6 or later
final java.awt.SystemTray tray = java.awt.SystemTray.getSystemTray();
final Image img = Toolkit.getDefaultToolkit().getImage(
JLanguageTool.getDataBroker().getFromResourceDirAsUrl(Main.SYSTEM_TRAY_ICON_NAME));
final PopupMenu popup = makePopupMenu();
try {
final java.awt.TrayIcon trayIcon = new java.awt.TrayIcon(img,
"tooltip", popup);
trayIcon.addMouseListener(new TrayActionListener());
trayIcon.setToolTip(SYSTEM_TRAY_TOOLTIP);
tray.add(trayIcon);
} catch (final AWTException e1) {
// thrown if there's no system tray
Tools.showError(e1);
}
}
isInTray = true;
frame.setVisible(false);
}
private PopupMenu makePopupMenu() {
final PopupMenu popup = new PopupMenu();
final ActionListener rmbListener = new TrayActionRMBListener();
// Check clipboard text:
final MenuItem checkClipboardItem = new MenuItem(StringTools
.getLabel(messages.getString("guiMenuCheckClipboard")));
checkClipboardItem.addActionListener(rmbListener);
popup.add(checkClipboardItem);
// Open main window:
final MenuItem restoreItem = new MenuItem(StringTools.getLabel(messages
.getString("guiMenuShowMainWindow")));
restoreItem.addActionListener(rmbListener);
popup.add(restoreItem);
// Exit:
final MenuItem exitItem = new MenuItem(StringTools.getLabel(messages
.getString("guiMenuQuit")));
exitItem.addActionListener(rmbListener);
popup.add(exitItem);
return popup;
}
void addLanguage() {
final LanguageManagerDialog lmd = new LanguageManagerDialog(frame, Language
.getExternalLanguages());
lmd.show();
try {
Language.reInit(lmd.getLanguages());
} catch (final RuleFilenameException e) {
Tools.showErrorMessage(e);
}
populateLanguageBox(languageBox);
}
void showOptions() {
final JLanguageTool langTool = getCurrentLanguageTool();
final List<Rule> rules = langTool.getAllRules();
final ConfigurationDialog configDialog = getCurrentConfigDialog();
configDialog.show(rules); // this blocks until OK/Cancel is clicked in the dialog
config.setDisabledRuleIds(configDialog.getDisabledRuleIds());
config.setEnabledRuleIds(configDialog.getEnabledRuleIds());
config.setDisabledCategoryNames(configDialog.getDisabledCategoryNames());
config.setMotherTongue(configDialog.getMotherTongue());
config.setRunServer(configDialog.getRunServer());
config.setServerPort(configDialog.getServerPort());
// Stop server, start new server if requested:
stopServer();
maybeStartServer();
}
private void restoreFromTray() {
frame.setVisible(true);
}
// show GUI and check the text from clipboard/selection:
private void restoreFromTrayAndCheck() {
final String s = getClipboardText();
restoreFromTray();
textArea.setText(s);
final JLanguageTool langTool = getCurrentLanguageTool();
checkTextAndDisplayResults(langTool, getCurrentLanguage());
}
void checkClipboardText() {
final String s = getClipboardText();
textArea.setText(s);
final JLanguageTool langTool = getCurrentLanguageTool();
checkTextAndDisplayResults(langTool, getCurrentLanguage());
}
private String getClipboardText() {
// get text from clipboard or selection:
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemSelection();
if (clipboard == null) { // on Windows
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
String s;
final Transferable data = clipboard.getContents(this);
try {
if (data != null
&& data.isDataFlavorSupported(DataFlavor.getTextPlainUnicodeFlavor())) {
final DataFlavor df = DataFlavor.getTextPlainUnicodeFlavor();
final Reader sr = df.getReaderForText(data);
s = StringTools.readerToString(sr);
} else {
s = "";
}
} catch (final Exception ex) {
ex.printStackTrace();
if (data != null) {
s = data.toString();
} else {
s = "";
}
}
return s;
}
void quitOrHide() {
if (closeHidesToTray) {
hideToTray();
} else {
quit();
}
}
void quit() {
stopServer();
try {
config.saveConfiguration();
} catch (final IOException e) {
Tools.showError(e);
}
frame.setVisible(false);
System.exit(0);
}
private void maybeStartServer() {
if (config.getRunServer()) {
httpServer = new HTTPServer(config.getServerPort());
try {
httpServer.run();
} catch (final PortBindingException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void stopServer() {
if (httpServer != null) {
httpServer.stop();
httpServer = null;
}
}
private Language getCurrentLanguage() {
return ((I18nLanguage) languageBox.getSelectedItem()).getLanguage();
}
private ConfigurationDialog getCurrentConfigDialog() {
final Language language = getCurrentLanguage();
final ConfigurationDialog configDialog;
if (configDialogs.containsKey(language)) {
configDialog = configDialogs.get(language);
} else {
configDialog = new ConfigurationDialog(frame, false);
configDialog.setMotherTongue(config.getMotherTongue());
configDialog.setDisabledRules(config.getDisabledRuleIds());
configDialog.setEnabledRules(config.getEnabledRuleIds());
configDialog.setDisabledCategories(config.getDisabledCategoryNames());
configDialog.setRunServer(config.getRunServer());
configDialog.setServerPort(config.getServerPort());
configDialogs.put(language, configDialog);
}
return configDialog;
}
private JLanguageTool getCurrentLanguageTool() {
final JLanguageTool langTool;
try {
final ConfigurationDialog configDialog = getCurrentConfigDialog();
langTool = new JLanguageTool(getCurrentLanguage(), configDialog
.getMotherTongue());
langTool.activateDefaultPatternRules();
langTool.activateDefaultFalseFriendRules();
final Set<String> disabledRules = configDialog.getDisabledRuleIds();
if (disabledRules != null) {
for (final String ruleId : disabledRules) {
langTool.disableRule(ruleId);
}
}
final Set<String> disabledCategories = configDialog
.getDisabledCategoryNames();
if (disabledCategories != null) {
for (final String categoryName : disabledCategories) {
langTool.disableCategory(categoryName);
}
}
final Set<String> enabledRules = configDialog.getEnabledRuleIds();
if (enabledRules != null) {
for (String ruleName : enabledRules) {
langTool.enableDefaultOffRule(ruleName);
langTool.enableRule(ruleName);
}
}
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
} catch (final ParserConfigurationException ex) {
throw new RuntimeException(ex);
} catch (final SAXException ex) {
throw new RuntimeException(ex);
}
return langTool;
}
private void checkTextAndDisplayResults(final JLanguageTool langTool,
final Language lang) {
if (StringTools.isEmpty(textArea.getText().trim())) {
textArea.setText(messages.getString("enterText2"));
} else {
final StringBuilder sb = new StringBuilder();
final String startCheckText = Tools.makeTexti18n(messages,
"startChecking", new Object[] { lang.getTranslatedName(messages) });
resultArea.setText(HTML_FONT_START + startCheckText + "<br>\n"
+ HTML_FONT_END);
resultArea.repaint(); // FIXME: why doesn't this work?
// TODO: resultArea.setCursor(new Cursor(Cursor.WAIT_CURSOR));
sb.append(startCheckText);
sb.append("...<br>\n");
int matches = 0;
try {
matches = checkText(langTool, textArea.getText(), sb);
} catch (final Exception ex) {
sb.append("<br><br><b><font color=\"red\">" + ex.toString() + "<br>");
final StackTraceElement[] elements = ex.getStackTrace();
for (final StackTraceElement element : elements) {
sb.append(element);
sb.append("<br>");
}
sb.append("</font></b><br>");
ex.printStackTrace();
}
final String checkDone = Tools.makeTexti18n(messages, "checkDone",
new Object[] {matches});
sb.append(checkDone);
sb.append("<br>\n");
resultArea.setText(HTML_FONT_START + sb.toString() + HTML_FONT_END);
resultArea.setCaretPosition(0);
}
}
private int checkText(final JLanguageTool langTool, final String text,
final StringBuilder sb) throws IOException {
final long startTime = System.currentTimeMillis();
final List<RuleMatch> ruleMatches = langTool.check(text);
final long startTimeMatching = System.currentTimeMillis();
int i = 0;
for (final RuleMatch match : ruleMatches) {
final String output = Tools.makeTexti18n(messages, "result1",
new Object[] {i + 1,
match.getLine() + 1,
match.getColumn()});
sb.append(output);
String msg = match.getMessage();
msg = msg.replaceAll("<suggestion>", "<b>");
msg = msg.replaceAll("</suggestion>", "</b>");
msg = msg.replaceAll("<old>", "<b>");
msg = msg.replaceAll("</old>", "</b>");
sb.append("<b>" + messages.getString("errorMessage") + "</b> " + msg + "<br>\n");
if (match.getSuggestedReplacements().size() > 0) {
final String repl = StringTools.listToString(match
.getSuggestedReplacements(), "; ");
sb.append("<b>" + messages.getString("correctionMessage") + "</b> "
+ repl + "<br>\n");
}
final String context = Tools.getContext(match.getFromPos(), match
.getToPos(), text);
sb.append("<b>" + messages.getString("errorContext") + "</b> " + context);
sb.append("<br>\n");
i++;
}
final long endTime = System.currentTimeMillis();
sb.append(Tools.makeTexti18n(messages, "resultTime", new Object[] {
endTime - startTime,
endTime - startTimeMatching}));
return ruleMatches.size();
}
private void setTrayMode(boolean trayMode) {
this.closeHidesToTray = trayMode;
}
public static void main(final String[] args) {
try {
final Main prg = new Main();
if (args.length == 1
&& (args[0].equals("-t") || args[0].equals("--tray"))) {
// dock to systray on startup
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
prg.createGUI();
prg.setTrayMode(true);
prg.hideToTray();
} catch (final MissingJdicException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
} catch (final Exception e) {
Tools.showError(e);
System.exit(1);
}
}
});
} else if (args.length >= 1) {
System.out
.println("Usage: java de.danielnaber.languagetool.gui.Main [-t|--tray]");
System.out
.println(" -t, --tray: dock LanguageTool to system tray on startup");
} else {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
prg.createGUI();
prg.showGUI();
} catch (final Exception e) {
Tools.showError(e);
}
}
});
}
} catch (final Exception e) {
Tools.showError(e);
}
}
//
// The System Tray stuff
//
class TrayActionRMBListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase(
StringTools.getLabel(messages.getString("guiMenuCheckClipboard")))) {
restoreFromTrayAndCheck();
} else if (e.getActionCommand().equalsIgnoreCase(
StringTools.getLabel(messages.getString("guiMenuShowMainWindow")))) {
restoreFromTray();
} else if (e.getActionCommand().equalsIgnoreCase(
StringTools.getLabel(messages.getString("guiMenuQuit")))) {
quit();
} else {
JOptionPane.showMessageDialog(null, "Unknown action: "
+ e.getActionCommand(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
class TrayActionListener implements ActionListener, MouseListener {
// for Java 1.5 / Jdic:
public void actionPerformed(@SuppressWarnings("unused")ActionEvent e) {
handleClick();
}
// Java 1.6:
public void mouseClicked(@SuppressWarnings("unused")MouseEvent e) {
handleClick();
}
private void handleClick() {
if (frame.isVisible() && frame.isActive()) {
frame.setVisible(false);
} else if (frame.isVisible() && !frame.isActive()) {
frame.toFront();
restoreFromTrayAndCheck();
} else {
restoreFromTrayAndCheck();
}
}
public void mouseEntered(@SuppressWarnings("unused") MouseEvent e) {
}
public void mouseExited(@SuppressWarnings("unused")MouseEvent e) {
}
public void mousePressed(@SuppressWarnings("unused")MouseEvent e) {
}
public void mouseReleased(@SuppressWarnings("unused")MouseEvent e) {
}
}
class CloseListener implements WindowListener {
public void windowClosing(@SuppressWarnings("unused")WindowEvent e) {
quitOrHide();
}
public void windowActivated(@SuppressWarnings("unused")WindowEvent e) {
}
public void windowClosed(@SuppressWarnings("unused")WindowEvent e) {
}
public void windowDeactivated(@SuppressWarnings("unused")WindowEvent e) {
}
public void windowDeiconified(@SuppressWarnings("unused")WindowEvent e) {
}
public void windowIconified(@SuppressWarnings("unused")WindowEvent e) {
}
public void windowOpened(@SuppressWarnings("unused")WindowEvent e) {
}
}
static class PlainTextFileFilter extends FileFilter {
@Override
public boolean accept(final File f) {
return f.getName().toLowerCase().endsWith(".txt");
}
@Override
public String getDescription() {
return "*.txt";
}
}
private class I18nLanguage implements Comparable<I18nLanguage> {
private final Language language;
I18nLanguage(Language language) {
this.language = language;
}
Language getLanguage() {
return language;
}
// used by the GUI:
@Override
public String toString() {
if (language.isExternal()) {
return language.getName() + " (ext.)";
} else {
return messages.getString(language.getShortName());
}
}
@Override
public int compareTo(I18nLanguage o) {
return toString().compareTo(o.toString());
}
}
}
| fix hang when giving wrong number of arguments - patch by Srinath Warrier
| trunk/JLanguageTool/src/java/de/danielnaber/languagetool/gui/Main.java | fix hang when giving wrong number of arguments - patch by Srinath Warrier | <ide><path>runk/JLanguageTool/src/java/de/danielnaber/languagetool/gui/Main.java
<ide> .println("Usage: java de.danielnaber.languagetool.gui.Main [-t|--tray]");
<ide> System.out
<ide> .println(" -t, --tray: dock LanguageTool to system tray on startup");
<add> prg.stopServer();
<ide> } else {
<ide> javax.swing.SwingUtilities.invokeLater(new Runnable() {
<ide> public void run() { |
|
Java | apache-2.0 | 3b3ba3d3ccd018ca5a90818defe3b11c858ac436 | 0 | alibaba/java-dns-cache-manipulator,alibaba/java-dns-cache-manipulator,alibaba/java-dns-cache-manipulator,alibaba/java-dns-cache-manipulator | package com.alibaba.dcm;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
/**
* @author Jerry Lee (oldratlee at gmail dot com)
* @see DnsCache
*/
@Immutable
public final class DnsCacheEntry implements Serializable {
private static final long serialVersionUID = -7476648934387757732L;
private final String host;
private final String[] ips;
private final long expiration;
public String getHost() {
return host;
}
@Nonnull
public String[] getIps() {
return ips.clone(); // defensive copy
}
public String getIp() {
return ips[0];
}
/**
* return value {@link Long#MAX_VALUE} means "never expiration".
*/
public Date getExpiration() {
return new Date(expiration);
}
/**
* @deprecated use {@link #DnsCacheEntry(String, String[], long)} instead
*/
@Deprecated
public DnsCacheEntry(String host,
@Nonnull @SuppressFBWarnings("EI_EXPOSE_REP2") String[] ips,
@Nonnull @SuppressFBWarnings("EI_EXPOSE_REP2") Date expiration) {
this.host = host;
this.ips = ips;
this.expiration = expiration.getTime();
}
/**
* @since 1.6.0
*/
public DnsCacheEntry(String host,
@Nonnull @SuppressFBWarnings("EI_EXPOSE_REP2") String[] ips,
long expiration) {
this.host = host;
this.ips = ips;
this.expiration = expiration;
}
@Override
public String toString() {
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return "DnsCacheEntry{" +
"host='" + host + '\'' +
", ips=" + Arrays.toString(ips) +
", expiration=" + dateFormat.format(expiration) +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DnsCacheEntry that = (DnsCacheEntry) o;
if (expiration != that.expiration) return false;
if (host != null ? !host.equals(that.host) : that.host != null) return false;
return Arrays.equals(ips, that.ips);
}
@Override
public int hashCode() {
int result = host != null ? host.hashCode() : 0;
result = 31 * result + Arrays.hashCode(ips);
result = 31 * result + (int) (expiration ^ (expiration >>> 32));
return result;
}
}
| library/src/main/java/com/alibaba/dcm/DnsCacheEntry.java | package com.alibaba.dcm;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
/**
* @author Jerry Lee (oldratlee at gmail dot com)
* @see DnsCache
*/
@Immutable
public final class DnsCacheEntry implements Serializable {
private static final long serialVersionUID = -7476648934387757732L;
private final String host;
private final String[] ips;
private final long expiration;
public String getHost() {
return host;
}
@Nonnull
public String[] getIps() {
String[] copy = new String[ips.length];
System.arraycopy(ips, 0, copy, 0, ips.length); // defensive copy
return copy;
}
public String getIp() {
return ips[0];
}
/**
* return value {@link Long#MAX_VALUE} means "never expiration".
*/
public Date getExpiration() {
// defensive copy
return new Date(expiration);
}
/**
* @deprecated use {@link #DnsCacheEntry(String, String[], long)} instead
*/
@Deprecated
public DnsCacheEntry(String host,
@Nonnull @SuppressFBWarnings("EI_EXPOSE_REP2") String[] ips,
@Nonnull @SuppressFBWarnings("EI_EXPOSE_REP2") Date expiration) {
this.host = host;
this.ips = ips;
this.expiration = expiration.getTime();
}
/**
* @since 1.6.0
*/
public DnsCacheEntry(String host,
@Nonnull @SuppressFBWarnings("EI_EXPOSE_REP2") String[] ips,
long expiration) {
this.host = host;
this.ips = ips;
this.expiration = expiration;
}
@Override
public String toString() {
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return "DnsCacheEntry{" +
"host='" + host + '\'' +
", ips=" + Arrays.toString(ips) +
", expiration=" + dateFormat.format(expiration) +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DnsCacheEntry that = (DnsCacheEntry) o;
if (expiration != that.expiration) return false;
if (host != null ? !host.equals(that.host) : that.host != null) return false;
return Arrays.equals(ips, that.ips);
}
@Override
public int hashCode() {
int result = host != null ? host.hashCode() : 0;
result = 31 * result + Arrays.hashCode(ips);
result = 31 * result + (int) (expiration ^ (expiration >>> 32));
return result;
}
}
| ! simplify code: use clone instead of explicit copy for String[]
| library/src/main/java/com/alibaba/dcm/DnsCacheEntry.java | ! simplify code: use clone instead of explicit copy for String[] | <ide><path>ibrary/src/main/java/com/alibaba/dcm/DnsCacheEntry.java
<ide>
<ide> @Nonnull
<ide> public String[] getIps() {
<del> String[] copy = new String[ips.length];
<del> System.arraycopy(ips, 0, copy, 0, ips.length); // defensive copy
<del> return copy;
<add> return ips.clone(); // defensive copy
<ide> }
<ide>
<ide> public String getIp() {
<ide> * return value {@link Long#MAX_VALUE} means "never expiration".
<ide> */
<ide> public Date getExpiration() {
<del> // defensive copy
<ide> return new Date(expiration);
<ide> }
<ide> |
|
Java | apache-2.0 | 4fcca68c854f392f88b9f09c35b76636a37f9501 | 0 | mikeb01/Aeron,mikeb01/Aeron,galderz/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,real-logic/Aeron,galderz/Aeron,galderz/Aeron,galderz/Aeron,mikeb01/Aeron,real-logic/Aeron | /*
* Copyright 2014-2017 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.aeron.driver;
import io.aeron.driver.buffer.RawLog;
import io.aeron.driver.media.SendChannelEndpoint;
import io.aeron.driver.status.SystemCounters;
import io.aeron.logbuffer.LogBufferDescriptor;
import io.aeron.logbuffer.LogBufferUnblocker;
import io.aeron.protocol.DataHeaderFlyweight;
import io.aeron.protocol.RttMeasurementFlyweight;
import io.aeron.protocol.SetupFlyweight;
import io.aeron.protocol.StatusMessageFlyweight;
import org.agrona.collections.ArrayUtil;
import org.agrona.concurrent.EpochClock;
import org.agrona.concurrent.NanoClock;
import org.agrona.concurrent.UnsafeBuffer;
import org.agrona.concurrent.status.AtomicCounter;
import org.agrona.concurrent.status.Position;
import org.agrona.concurrent.status.ReadablePosition;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import static io.aeron.Aeron.PUBLICATION_CONNECTION_TIMEOUT_MS;
import static io.aeron.driver.Configuration.*;
import static io.aeron.driver.status.SystemCounterDescriptor.*;
import static io.aeron.logbuffer.LogBufferDescriptor.*;
import static io.aeron.logbuffer.TermScanner.*;
class NetworkPublicationPadding1
{
@SuppressWarnings("unused")
protected long p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15;
}
class NetworkPublicationConductorFields extends NetworkPublicationPadding1
{
protected static final ReadablePosition[] EMPTY_POSITIONS = new ReadablePosition[0];
protected long cleanPosition = 0;
protected long timeOfLastActivityNs = 0;
protected long lastSenderPosition = 0;
protected int refCount = 0;
protected ReadablePosition[] spyPositions = EMPTY_POSITIONS;
}
class NetworkPublicationPadding2 extends NetworkPublicationConductorFields
{
@SuppressWarnings("unused")
protected long p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, p27, p28, p29, p30;
}
class NetworkPublicationSenderFields extends NetworkPublicationPadding2
{
protected long timeOfLastSendOrHeartbeatNs;
protected long timeOfLastSetupNs;
protected boolean trackSenderLimits = true;
protected boolean shouldSendSetupFrame = true;
}
class NetworkPublicationPadding3 extends NetworkPublicationSenderFields
{
@SuppressWarnings("unused")
protected long p31, p32, p33, p34, p35, p36, p37, p38, p39, p40, p41, p42, p43, p44, p45;
}
/**
* Publication to be sent to registered subscribers.
*/
public class NetworkPublication
extends NetworkPublicationPadding3
implements RetransmitSender, DriverManagedResource, Subscribable
{
public enum Status
{
ACTIVE, DRAINING, LINGER, CLOSING
}
private final long registrationId;
private final long unblockTimeoutNs;
private final int positionBitsToShift;
private final int initialTermId;
private final int termBufferLength;
private final int termLengthMask;
private final int mtuLength;
private final int termWindowLength;
private final int sessionId;
private final int streamId;
private final boolean isExclusive;
private volatile boolean isConnected;
private volatile boolean hasSenderReleased;
private volatile boolean isEndOfStream;
private Status status = Status.ACTIVE;
private final UnsafeBuffer[] termBuffers;
private final ByteBuffer[] sendBuffers;
private final Position publisherLimit;
private final Position senderPosition;
private final Position senderLimit;
private final SendChannelEndpoint channelEndpoint;
private final ByteBuffer heartbeatBuffer;
private final DataHeaderFlyweight heartbeatDataHeader;
private final ByteBuffer setupBuffer;
private final SetupFlyweight setupHeader;
private final ByteBuffer rttMeasurementBuffer;
private final RttMeasurementFlyweight rttMeasurementHeader;
private final FlowControl flowControl;
private final NanoClock nanoClock;
private final EpochClock epochClock;
private final RetransmitHandler retransmitHandler;
private final UnsafeBuffer metaDataBuffer;
private final RawLog rawLog;
private final AtomicCounter heartbeatsSent;
private final AtomicCounter retransmitsSent;
private final AtomicCounter senderFlowControlLimits;
private final AtomicCounter shortSends;
private final AtomicCounter unblockedPublications;
public NetworkPublication(
final long registrationId,
final SendChannelEndpoint channelEndpoint,
final NanoClock nanoClock,
final EpochClock epochClock,
final RawLog rawLog,
final Position publisherLimit,
final Position senderPosition,
final Position senderLimit,
final int sessionId,
final int streamId,
final int initialTermId,
final int mtuLength,
final SystemCounters systemCounters,
final FlowControl flowControl,
final RetransmitHandler retransmitHandler,
final NetworkPublicationThreadLocals threadLocals,
final long unblockTimeoutNs,
final boolean isExclusive)
{
this.registrationId = registrationId;
this.unblockTimeoutNs = unblockTimeoutNs;
this.channelEndpoint = channelEndpoint;
this.rawLog = rawLog;
this.nanoClock = nanoClock;
this.epochClock = epochClock;
this.senderPosition = senderPosition;
this.senderLimit = senderLimit;
this.flowControl = flowControl;
this.retransmitHandler = retransmitHandler;
this.publisherLimit = publisherLimit;
this.mtuLength = mtuLength;
this.initialTermId = initialTermId;
this.sessionId = sessionId;
this.streamId = streamId;
this.isExclusive = isExclusive;
metaDataBuffer = rawLog.metaData();
setupBuffer = threadLocals.setupBuffer();
setupHeader = threadLocals.setupHeader();
heartbeatBuffer = threadLocals.heartbeatBuffer();
heartbeatDataHeader = threadLocals.heartbeatDataHeader();
rttMeasurementBuffer = threadLocals.rttMeasurementBuffer();
rttMeasurementHeader = threadLocals.rttMeasurementHeader();
heartbeatsSent = systemCounters.get(HEARTBEATS_SENT);
shortSends = systemCounters.get(SHORT_SENDS);
retransmitsSent = systemCounters.get(RETRANSMITS_SENT);
senderFlowControlLimits = systemCounters.get(SENDER_FLOW_CONTROL_LIMITS);
unblockedPublications = systemCounters.get(UNBLOCKED_PUBLICATIONS);
termBuffers = rawLog.termBuffers();
sendBuffers = rawLog.sliceTerms();
final int termLength = rawLog.termLength();
termBufferLength = termLength;
termLengthMask = termLength - 1;
flowControl.initialize(initialTermId, termLength);
final long nowNs = nanoClock.nanoTime();
timeOfLastSendOrHeartbeatNs = nowNs - PUBLICATION_HEARTBEAT_TIMEOUT_NS - 1;
timeOfLastSetupNs = nowNs - PUBLICATION_SETUP_TIMEOUT_NS - 1;
positionBitsToShift = Integer.numberOfTrailingZeros(termLength);
termWindowLength = Configuration.publicationTermWindowLength(termLength);
lastSenderPosition = senderPosition.get();
cleanPosition = lastSenderPosition;
timeOfLastActivityNs = nowNs;
}
public void close()
{
publisherLimit.close();
senderPosition.close();
senderLimit.close();
for (final ReadablePosition position : spyPositions)
{
position.close();
}
rawLog.close();
}
public int mtuLength()
{
return mtuLength;
}
public long registrationId()
{
return registrationId;
}
public boolean isExclusive()
{
return isExclusive;
}
public int send(final long nowNs)
{
final long senderPosition = this.senderPosition.get();
final int activeTermId = computeTermIdFromPosition(senderPosition, positionBitsToShift, initialTermId);
final int termOffset = (int)senderPosition & termLengthMask;
if (shouldSendSetupFrame)
{
setupMessageCheck(nowNs, activeTermId, termOffset);
}
int bytesSent = sendData(nowNs, senderPosition, termOffset);
if (0 == bytesSent)
{
bytesSent = heartbeatMessageCheck(nowNs, activeTermId, termOffset);
senderLimit.setOrdered(flowControl.onIdle(nowNs, senderLimit.get()));
}
retransmitHandler.processTimeouts(nowNs, this);
return bytesSent;
}
public SendChannelEndpoint channelEndpoint()
{
return channelEndpoint;
}
public int sessionId()
{
return sessionId;
}
public int streamId()
{
return streamId;
}
public void resend(final int termId, final int termOffset, final int length)
{
final long senderPosition = this.senderPosition.get();
final long resendPosition = computePosition(termId, termOffset, positionBitsToShift, initialTermId);
if (resendPosition < senderPosition && resendPosition >= (senderPosition - rawLog.termLength()))
{
final int activeIndex = indexByPosition(resendPosition, positionBitsToShift);
final UnsafeBuffer termBuffer = termBuffers[activeIndex];
final ByteBuffer sendBuffer = sendBuffers[activeIndex];
int remainingBytes = length;
int bytesSent = 0;
int offset = termOffset;
do
{
offset += bytesSent;
final long scanOutcome = scanForAvailability(termBuffer, offset, Math.min(mtuLength, remainingBytes));
final int available = available(scanOutcome);
if (available <= 0)
{
break;
}
sendBuffer.limit(offset + available).position(offset);
if (available != channelEndpoint.send(sendBuffer))
{
shortSends.increment();
break;
}
bytesSent = available + padding(scanOutcome);
remainingBytes -= bytesSent;
}
while (remainingBytes > 0);
retransmitsSent.orderedIncrement();
}
}
public void triggerSendSetupFrame()
{
shouldSendSetupFrame = true;
}
public void addSubscriber(final ReadablePosition spyPosition)
{
spyPositions = ArrayUtil.add(spyPositions, spyPosition);
}
public void removeSubscriber(final ReadablePosition spyPosition)
{
spyPositions = ArrayUtil.remove(spyPositions, spyPosition);
spyPosition.close();
}
public void onNak(final int termId, final int termOffset, final int length)
{
retransmitHandler.onNak(termId, termOffset, length, termBufferLength, this);
}
public void onStatusMessage(final StatusMessageFlyweight msg, final InetSocketAddress srcAddress)
{
LogBufferDescriptor.timeOfLastStatusMessage(metaDataBuffer, epochClock.time());
if (!isConnected)
{
isConnected = true;
}
senderLimit.setOrdered(
flowControl.onStatusMessage(
msg,
srcAddress,
senderLimit.get(),
initialTermId,
positionBitsToShift,
nanoClock.nanoTime()));
}
public void onRttMeasurement(
final RttMeasurementFlyweight msg, @SuppressWarnings("unused") final InetSocketAddress srcAddress)
{
if (RttMeasurementFlyweight.REPLY_FLAG == (msg.flags() & RttMeasurementFlyweight.REPLY_FLAG))
{
// TODO: rate limit
rttMeasurementHeader
.receiverId(msg.receiverId())
.echoTimestampNs(msg.echoTimestampNs())
.receptionDelta(0)
.sessionId(sessionId)
.streamId(streamId)
.flags((short)0x0);
final int bytesSent = channelEndpoint.send(rttMeasurementBuffer);
if (RttMeasurementFlyweight.HEADER_LENGTH != bytesSent)
{
shortSends.increment();
}
}
// handling of RTT measurements would be done in an else clause here.
}
RawLog rawLog()
{
return rawLog;
}
int publisherLimitId()
{
return publisherLimit.id();
}
/**
* Update the publishers limit for flow control as part of the conductor duty cycle.
*
* @return 1 if the limit has been updated otherwise 0.
*/
int updatePublisherLimit()
{
int workCount = 0;
final long senderPosition = this.senderPosition.getVolatile();
if (isConnected)
{
long minConsumerPosition = senderPosition;
if (spyPositions.length > 0)
{
for (final ReadablePosition spyPosition : spyPositions)
{
minConsumerPosition = Math.min(minConsumerPosition, spyPosition.getVolatile());
}
}
final long proposedPublisherLimit = minConsumerPosition + termWindowLength;
if (publisherLimit.proposeMaxOrdered(proposedPublisherLimit))
{
cleanBuffer(proposedPublisherLimit);
workCount = 1;
}
}
else if (publisherLimit.get() > senderPosition)
{
publisherLimit.setOrdered(senderPosition);
}
return workCount;
}
boolean hasSpies()
{
return spyPositions.length > 0;
}
long spyJoinPosition()
{
long maxSpyPosition = producerPosition();
for (final ReadablePosition spyPosition : spyPositions)
{
maxSpyPosition = Math.max(maxSpyPosition, spyPosition.getVolatile());
}
return maxSpyPosition;
}
private int sendData(final long nowNs, final long senderPosition, final int termOffset)
{
int bytesSent = 0;
final int availableWindow = (int)(senderLimit.get() - senderPosition);
if (availableWindow > 0)
{
final int scanLimit = Math.min(availableWindow, mtuLength);
final int activeIndex = indexByPosition(senderPosition, positionBitsToShift);
final long scanOutcome = scanForAvailability(termBuffers[activeIndex], termOffset, scanLimit);
final int available = available(scanOutcome);
if (available > 0)
{
final ByteBuffer sendBuffer = sendBuffers[activeIndex];
sendBuffer.limit(termOffset + available).position(termOffset);
if (available == channelEndpoint.send(sendBuffer))
{
timeOfLastSendOrHeartbeatNs = nowNs;
trackSenderLimits = true;
bytesSent = available;
this.senderPosition.setOrdered(senderPosition + bytesSent + padding(scanOutcome));
}
else
{
shortSends.increment();
}
}
}
else if (trackSenderLimits)
{
trackSenderLimits = false;
senderFlowControlLimits.orderedIncrement();
}
return bytesSent;
}
private void setupMessageCheck(final long nowNs, final int activeTermId, final int termOffset)
{
if (nowNs > (timeOfLastSetupNs + PUBLICATION_SETUP_TIMEOUT_NS))
{
setupBuffer.clear();
setupHeader
.activeTermId(activeTermId)
.termOffset(termOffset)
.sessionId(sessionId)
.streamId(streamId)
.initialTermId(initialTermId)
.termLength(termBufferLength)
.mtuLength(mtuLength)
.ttl(channelEndpoint.multicastTtl());
final int bytesSent = channelEndpoint.send(setupBuffer);
if (SetupFlyweight.HEADER_LENGTH != bytesSent)
{
shortSends.increment();
}
timeOfLastSetupNs = nowNs;
timeOfLastSendOrHeartbeatNs = nowNs;
if (isConnected)
{
shouldSendSetupFrame = false;
}
}
}
private int heartbeatMessageCheck(final long nowNs, final int activeTermId, final int termOffset)
{
int bytesSent = 0;
if (nowNs > (timeOfLastSendOrHeartbeatNs + PUBLICATION_HEARTBEAT_TIMEOUT_NS))
{
heartbeatBuffer.clear();
heartbeatDataHeader
.sessionId(sessionId)
.streamId(streamId)
.termId(activeTermId)
.termOffset(termOffset);
if (isEndOfStream)
{
heartbeatDataHeader.flags((byte)DataHeaderFlyweight.BEGIN_END_AND_EOS_FLAGS);
}
else
{
heartbeatDataHeader.flags((byte)DataHeaderFlyweight.BEGIN_AND_END_FLAGS);
}
bytesSent = channelEndpoint.send(heartbeatBuffer);
if (DataHeaderFlyweight.HEADER_LENGTH != bytesSent)
{
shortSends.increment();
}
heartbeatsSent.orderedIncrement();
timeOfLastSendOrHeartbeatNs = nowNs;
}
return bytesSent;
}
private void cleanBuffer(final long publisherLimit)
{
final long cleanPosition = this.cleanPosition;
final long dirtyRange = publisherLimit - cleanPosition;
final int bufferCapacity = termBufferLength;
final int reservedRange = bufferCapacity * 2;
if (dirtyRange > reservedRange)
{
final UnsafeBuffer dirtyTerm = termBuffers[indexByPosition(cleanPosition, positionBitsToShift)];
final int termOffset = (int)cleanPosition & termLengthMask;
final int bytesForCleaning = (int)(dirtyRange - reservedRange);
final int length = Math.min(bytesForCleaning, bufferCapacity - termOffset);
dirtyTerm.setMemory(termOffset, length, (byte)0);
this.cleanPosition = cleanPosition + length;
}
}
private void checkForBlockedPublisher(final long timeNs, final long senderPosition)
{
if (senderPosition == lastSenderPosition && producerPosition() > senderPosition)
{
if (timeNs > (timeOfLastActivityNs + unblockTimeoutNs))
{
if (LogBufferUnblocker.unblock(termBuffers, metaDataBuffer, senderPosition))
{
unblockedPublications.orderedIncrement();
}
}
}
else
{
timeOfLastActivityNs = timeNs;
lastSenderPosition = senderPosition;
}
}
private boolean spiesFinishedConsuming(final DriverConductor conductor, final long eosPosition)
{
if (spyPositions.length > 0)
{
for (final ReadablePosition spyPosition : spyPositions)
{
if (spyPosition.getVolatile() < eosPosition)
{
return false;
}
}
conductor.cleanupSpies(this);
for (final ReadablePosition position : spyPositions)
{
position.close();
}
spyPositions = EMPTY_POSITIONS;
}
return true;
}
private void updateConnectedStatus(final long timeMs)
{
if (isConnected && timeMs > (timeOfLastStatusMessage(metaDataBuffer) + PUBLICATION_CONNECTION_TIMEOUT_MS))
{
isConnected = false;
}
}
public void onTimeEvent(final long timeNs, final long timeMs, final DriverConductor conductor)
{
updateConnectedStatus(timeMs);
switch (status)
{
case ACTIVE:
checkForBlockedPublisher(timeNs, consumerPosition());
break;
case DRAINING:
if (producerPosition() > consumerPosition())
{
if (LogBufferUnblocker.unblock(termBuffers, metaDataBuffer, consumerPosition()))
{
unblockedPublications.orderedIncrement();
timeOfLastActivityNs = timeNs;
break;
}
if (isConnected)
{
break;
}
}
else
{
isEndOfStream = true;
}
if (spiesFinishedConsuming(conductor, consumerPosition()))
{
timeOfLastActivityNs = timeNs;
status = Status.LINGER;
}
break;
case LINGER:
if (timeNs > (timeOfLastActivityNs + PUBLICATION_LINGER_NS))
{
conductor.cleanupPublication(this);
status = Status.CLOSING;
}
break;
}
}
public boolean hasReachedEndOfLife()
{
return hasSenderReleased;
}
public void timeOfLastStateChange(final long time)
{
}
public long timeOfLastStateChange()
{
return timeOfLastActivityNs;
}
public void delete()
{
close();
}
public int decRef()
{
final int count = --refCount;
if (0 == count)
{
status = Status.DRAINING;
channelEndpoint.decRef();
timeOfLastActivityNs = nanoClock.nanoTime();
if (consumerPosition() >= producerPosition())
{
isEndOfStream = true;
}
}
return count;
}
public int incRef()
{
return ++refCount;
}
Status status()
{
return status;
}
void senderRelease()
{
hasSenderReleased = true;
}
long producerPosition()
{
final long rawTail = rawTailVolatile(metaDataBuffer);
final int termOffset = termOffset(rawTail, termBufferLength);
return computePosition(termId(rawTail), termOffset, positionBitsToShift, initialTermId);
}
long consumerPosition()
{
return senderPosition.getVolatile();
}
}
| aeron-driver/src/main/java/io/aeron/driver/NetworkPublication.java | /*
* Copyright 2014-2017 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.aeron.driver;
import io.aeron.driver.buffer.RawLog;
import io.aeron.driver.media.SendChannelEndpoint;
import io.aeron.driver.status.SystemCounters;
import io.aeron.logbuffer.LogBufferDescriptor;
import io.aeron.logbuffer.LogBufferUnblocker;
import io.aeron.protocol.DataHeaderFlyweight;
import io.aeron.protocol.RttMeasurementFlyweight;
import io.aeron.protocol.SetupFlyweight;
import io.aeron.protocol.StatusMessageFlyweight;
import org.agrona.collections.ArrayUtil;
import org.agrona.concurrent.EpochClock;
import org.agrona.concurrent.NanoClock;
import org.agrona.concurrent.UnsafeBuffer;
import org.agrona.concurrent.status.AtomicCounter;
import org.agrona.concurrent.status.Position;
import org.agrona.concurrent.status.ReadablePosition;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import static io.aeron.Aeron.PUBLICATION_CONNECTION_TIMEOUT_MS;
import static io.aeron.driver.Configuration.*;
import static io.aeron.driver.status.SystemCounterDescriptor.*;
import static io.aeron.logbuffer.LogBufferDescriptor.*;
import static io.aeron.logbuffer.TermScanner.*;
class NetworkPublicationPadding1
{
@SuppressWarnings("unused")
protected long p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15;
}
class NetworkPublicationConductorFields extends NetworkPublicationPadding1
{
protected static final ReadablePosition[] EMPTY_POSITIONS = new ReadablePosition[0];
protected long cleanPosition = 0;
protected long timeOfLastActivityNs = 0;
protected long lastSenderPosition = 0;
protected int refCount = 0;
protected ReadablePosition[] spyPositions = EMPTY_POSITIONS;
}
class NetworkPublicationPadding2 extends NetworkPublicationConductorFields
{
@SuppressWarnings("unused")
protected long p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, p27, p28, p29, p30;
}
class NetworkPublicationSenderFields extends NetworkPublicationPadding2
{
protected long timeOfLastSendOrHeartbeatNs;
protected long timeOfLastSetupNs;
protected boolean trackSenderLimits = true;
protected boolean shouldSendSetupFrame = true;
}
class NetworkPublicationPadding3 extends NetworkPublicationSenderFields
{
@SuppressWarnings("unused")
protected long p31, p32, p33, p34, p35, p36, p37, p38, p39, p40, p41, p42, p43, p44, p45;
}
/**
* Publication to be sent to registered subscribers.
*/
public class NetworkPublication
extends NetworkPublicationPadding3
implements RetransmitSender, DriverManagedResource, Subscribable
{
public enum Status
{
ACTIVE, DRAINING, LINGER, CLOSING
}
private final long registrationId;
private final long unblockTimeoutNs;
private final int positionBitsToShift;
private final int initialTermId;
private final int termBufferLength;
private final int termLengthMask;
private final int mtuLength;
private final int termWindowLength;
private final int sessionId;
private final int streamId;
private final boolean isExclusive;
private volatile boolean isConnected;
private volatile boolean hasSenderReleased;
private volatile boolean isEndOfStream;
private Status status = Status.ACTIVE;
private final UnsafeBuffer[] termBuffers;
private final ByteBuffer[] sendBuffers;
private final Position publisherLimit;
private final Position senderPosition;
private final Position senderLimit;
private final SendChannelEndpoint channelEndpoint;
private final ByteBuffer heartbeatBuffer;
private final DataHeaderFlyweight heartbeatDataHeader;
private final ByteBuffer setupBuffer;
private final SetupFlyweight setupHeader;
private final ByteBuffer rttMeasurementBuffer;
private final RttMeasurementFlyweight rttMeasurementHeader;
private final FlowControl flowControl;
private final NanoClock nanoClock;
private final EpochClock epochClock;
private final RetransmitHandler retransmitHandler;
private final UnsafeBuffer metaDataBuffer;
private final RawLog rawLog;
private final AtomicCounter heartbeatsSent;
private final AtomicCounter retransmitsSent;
private final AtomicCounter senderFlowControlLimits;
private final AtomicCounter shortSends;
private final AtomicCounter unblockedPublications;
public NetworkPublication(
final long registrationId,
final SendChannelEndpoint channelEndpoint,
final NanoClock nanoClock,
final EpochClock epochClock,
final RawLog rawLog,
final Position publisherLimit,
final Position senderPosition,
final Position senderLimit,
final int sessionId,
final int streamId,
final int initialTermId,
final int mtuLength,
final SystemCounters systemCounters,
final FlowControl flowControl,
final RetransmitHandler retransmitHandler,
final NetworkPublicationThreadLocals threadLocals,
final long unblockTimeoutNs,
final boolean isExclusive)
{
this.registrationId = registrationId;
this.unblockTimeoutNs = unblockTimeoutNs;
this.channelEndpoint = channelEndpoint;
this.rawLog = rawLog;
this.nanoClock = nanoClock;
this.epochClock = epochClock;
this.senderPosition = senderPosition;
this.senderLimit = senderLimit;
this.flowControl = flowControl;
this.retransmitHandler = retransmitHandler;
this.publisherLimit = publisherLimit;
this.mtuLength = mtuLength;
this.initialTermId = initialTermId;
this.sessionId = sessionId;
this.streamId = streamId;
this.isExclusive = isExclusive;
metaDataBuffer = rawLog.metaData();
setupBuffer = threadLocals.setupBuffer();
setupHeader = threadLocals.setupHeader();
heartbeatBuffer = threadLocals.heartbeatBuffer();
heartbeatDataHeader = threadLocals.heartbeatDataHeader();
rttMeasurementBuffer = threadLocals.rttMeasurementBuffer();
rttMeasurementHeader = threadLocals.rttMeasurementHeader();
heartbeatsSent = systemCounters.get(HEARTBEATS_SENT);
shortSends = systemCounters.get(SHORT_SENDS);
retransmitsSent = systemCounters.get(RETRANSMITS_SENT);
senderFlowControlLimits = systemCounters.get(SENDER_FLOW_CONTROL_LIMITS);
unblockedPublications = systemCounters.get(UNBLOCKED_PUBLICATIONS);
termBuffers = rawLog.termBuffers();
sendBuffers = rawLog.sliceTerms();
final int termLength = rawLog.termLength();
termBufferLength = termLength;
termLengthMask = termLength - 1;
flowControl.initialize(initialTermId, termLength);
final long nowNs = nanoClock.nanoTime();
timeOfLastSendOrHeartbeatNs = nowNs - PUBLICATION_HEARTBEAT_TIMEOUT_NS - 1;
timeOfLastSetupNs = nowNs - PUBLICATION_SETUP_TIMEOUT_NS - 1;
positionBitsToShift = Integer.numberOfTrailingZeros(termLength);
termWindowLength = Configuration.publicationTermWindowLength(termLength);
lastSenderPosition = senderPosition.get();
cleanPosition = lastSenderPosition;
timeOfLastActivityNs = nowNs;
}
public void close()
{
publisherLimit.close();
senderPosition.close();
senderLimit.close();
for (final ReadablePosition position : spyPositions)
{
position.close();
}
rawLog.close();
}
public int mtuLength()
{
return mtuLength;
}
public long registrationId()
{
return registrationId;
}
public boolean isExclusive()
{
return isExclusive;
}
public int send(final long nowNs)
{
final long senderPosition = this.senderPosition.get();
final int activeTermId = computeTermIdFromPosition(senderPosition, positionBitsToShift, initialTermId);
final int termOffset = (int)senderPosition & termLengthMask;
if (shouldSendSetupFrame)
{
setupMessageCheck(nowNs, activeTermId, termOffset);
}
int bytesSent = sendData(nowNs, senderPosition, termOffset);
if (0 == bytesSent)
{
bytesSent = heartbeatMessageCheck(nowNs, activeTermId, termOffset);
senderLimit.setOrdered(flowControl.onIdle(nowNs, senderLimit.get()));
}
retransmitHandler.processTimeouts(nowNs, this);
return bytesSent;
}
public SendChannelEndpoint channelEndpoint()
{
return channelEndpoint;
}
public int sessionId()
{
return sessionId;
}
public int streamId()
{
return streamId;
}
public void resend(final int termId, final int termOffset, final int length)
{
final long senderPosition = this.senderPosition.get();
final long resendPosition = computePosition(termId, termOffset, positionBitsToShift, initialTermId);
if (resendPosition < senderPosition && resendPosition >= (senderPosition - rawLog.termLength()))
{
final int activeIndex = indexByPosition(resendPosition, positionBitsToShift);
final UnsafeBuffer termBuffer = termBuffers[activeIndex];
final ByteBuffer sendBuffer = sendBuffers[activeIndex];
int remainingBytes = length;
int bytesSent = 0;
int offset = termOffset;
do
{
offset += bytesSent;
final long scanOutcome = scanForAvailability(termBuffer, offset, Math.min(mtuLength, remainingBytes));
final int available = available(scanOutcome);
if (available <= 0)
{
break;
}
sendBuffer.limit(offset + available).position(offset);
if (available != channelEndpoint.send(sendBuffer))
{
shortSends.increment();
break;
}
bytesSent = available + padding(scanOutcome);
remainingBytes -= bytesSent;
}
while (remainingBytes > 0);
retransmitsSent.orderedIncrement();
}
}
public void triggerSendSetupFrame()
{
shouldSendSetupFrame = true;
}
public void addSubscriber(final ReadablePosition spyPosition)
{
spyPositions = ArrayUtil.add(spyPositions, spyPosition);
}
public void removeSubscriber(final ReadablePosition spyPosition)
{
spyPositions = ArrayUtil.remove(spyPositions, spyPosition);
spyPosition.close();
}
public void onNak(final int termId, final int termOffset, final int length)
{
retransmitHandler.onNak(termId, termOffset, length, termBufferLength, this);
}
public void onStatusMessage(final StatusMessageFlyweight msg, final InetSocketAddress srcAddress)
{
LogBufferDescriptor.timeOfLastStatusMessage(metaDataBuffer, epochClock.time());
if (!isConnected)
{
isConnected = true;
}
senderLimit.setOrdered(
flowControl.onStatusMessage(
msg,
srcAddress,
senderLimit.get(),
initialTermId,
positionBitsToShift,
nanoClock.nanoTime()));
}
public void onRttMeasurement(
final RttMeasurementFlyweight msg, @SuppressWarnings("unused") final InetSocketAddress srcAddress)
{
if (RttMeasurementFlyweight.REPLY_FLAG == (msg.flags() & RttMeasurementFlyweight.REPLY_FLAG))
{
// TODO: rate limit
rttMeasurementHeader
.receiverId(msg.receiverId())
.echoTimestampNs(msg.echoTimestampNs())
.receptionDelta(0)
.sessionId(sessionId)
.streamId(streamId)
.flags((short)0x0);
final int bytesSent = channelEndpoint.send(rttMeasurementBuffer);
if (RttMeasurementFlyweight.HEADER_LENGTH != bytesSent)
{
shortSends.increment();
}
}
// handling of RTT measurements would be done in an else clause here.
}
RawLog rawLog()
{
return rawLog;
}
int publisherLimitId()
{
return publisherLimit.id();
}
/**
* Update the publishers limit for flow control as part of the conductor duty cycle.
*
* @return 1 if the limit has been updated otherwise 0.
*/
int updatePublisherLimit()
{
int workCount = 0;
final long senderPosition = this.senderPosition.getVolatile();
if (isConnected)
{
long minConsumerPosition = senderPosition;
if (spyPositions.length > 0)
{
for (final ReadablePosition spyPosition : spyPositions)
{
minConsumerPosition = Math.min(minConsumerPosition, spyPosition.getVolatile());
}
}
final long proposedPublisherLimit = minConsumerPosition + termWindowLength;
if (publisherLimit.proposeMaxOrdered(proposedPublisherLimit))
{
cleanBuffer(proposedPublisherLimit);
workCount = 1;
}
}
else if (publisherLimit.get() > senderPosition)
{
publisherLimit.setOrdered(senderPosition);
}
return workCount;
}
boolean hasSpies()
{
return spyPositions.length > 0;
}
long spyJoinPosition()
{
long maxSpyPosition = producerPosition();
for (final ReadablePosition spyPosition : spyPositions)
{
maxSpyPosition = Math.max(maxSpyPosition, spyPosition.getVolatile());
}
return maxSpyPosition;
}
private int sendData(final long nowNs, final long senderPosition, final int termOffset)
{
int bytesSent = 0;
final int availableWindow = (int)(senderLimit.get() - senderPosition);
if (availableWindow > 0)
{
final int scanLimit = Math.min(availableWindow, mtuLength);
final int activeIndex = indexByPosition(senderPosition, positionBitsToShift);
final long scanOutcome = scanForAvailability(termBuffers[activeIndex], termOffset, scanLimit);
final int available = available(scanOutcome);
if (available > 0)
{
final ByteBuffer sendBuffer = sendBuffers[activeIndex];
sendBuffer.limit(termOffset + available).position(termOffset);
if (available == channelEndpoint.send(sendBuffer))
{
timeOfLastSendOrHeartbeatNs = nowNs;
trackSenderLimits = true;
bytesSent = available;
this.senderPosition.setOrdered(senderPosition + bytesSent + padding(scanOutcome));
}
else
{
shortSends.increment();
}
}
}
else if (trackSenderLimits)
{
trackSenderLimits = false;
senderFlowControlLimits.orderedIncrement();
}
return bytesSent;
}
private void setupMessageCheck(final long nowNs, final int activeTermId, final int termOffset)
{
if (nowNs > (timeOfLastSetupNs + PUBLICATION_SETUP_TIMEOUT_NS))
{
setupBuffer.clear();
setupHeader
.activeTermId(activeTermId)
.termOffset(termOffset)
.sessionId(sessionId)
.streamId(streamId)
.initialTermId(initialTermId)
.termLength(termBufferLength)
.mtuLength(mtuLength)
.ttl(channelEndpoint.multicastTtl());
final int bytesSent = channelEndpoint.send(setupBuffer);
if (SetupFlyweight.HEADER_LENGTH != bytesSent)
{
shortSends.increment();
}
timeOfLastSetupNs = nowNs;
timeOfLastSendOrHeartbeatNs = nowNs;
if (isConnected)
{
shouldSendSetupFrame = false;
}
}
}
private int heartbeatMessageCheck(final long nowNs, final int activeTermId, final int termOffset)
{
int bytesSent = 0;
if (nowNs > (timeOfLastSendOrHeartbeatNs + PUBLICATION_HEARTBEAT_TIMEOUT_NS))
{
heartbeatBuffer.clear();
heartbeatDataHeader
.sessionId(sessionId)
.streamId(streamId)
.termId(activeTermId)
.termOffset(termOffset);
if (isEndOfStream)
{
heartbeatDataHeader.flags((byte)DataHeaderFlyweight.BEGIN_END_AND_EOS_FLAGS);
}
else
{
heartbeatDataHeader.flags((byte)DataHeaderFlyweight.BEGIN_AND_END_FLAGS);
}
bytesSent = channelEndpoint.send(heartbeatBuffer);
if (DataHeaderFlyweight.HEADER_LENGTH != bytesSent)
{
shortSends.increment();
}
heartbeatsSent.orderedIncrement();
timeOfLastSendOrHeartbeatNs = nowNs;
}
return bytesSent;
}
private void cleanBuffer(final long publisherLimit)
{
final long cleanPosition = this.cleanPosition;
final long dirtyRange = publisherLimit - cleanPosition;
final int bufferCapacity = termBufferLength;
final int reservedRange = bufferCapacity * 2;
if (dirtyRange > reservedRange)
{
final UnsafeBuffer dirtyTerm = termBuffers[indexByPosition(cleanPosition, positionBitsToShift)];
final int termOffset = (int)cleanPosition & termLengthMask;
final int bytesForCleaning = (int)(dirtyRange - reservedRange);
final int length = Math.min(bytesForCleaning, bufferCapacity - termOffset);
dirtyTerm.setMemory(termOffset, length, (byte)0);
this.cleanPosition = cleanPosition + length;
}
}
private void checkForBlockedPublisher(final long timeNs, final long senderPosition)
{
if (senderPosition == lastSenderPosition && producerPosition() > senderPosition)
{
if (timeNs > (timeOfLastActivityNs + unblockTimeoutNs))
{
if (LogBufferUnblocker.unblock(termBuffers, metaDataBuffer, senderPosition))
{
unblockedPublications.orderedIncrement();
}
}
}
else
{
timeOfLastActivityNs = timeNs;
lastSenderPosition = senderPosition;
}
}
private boolean spiesFinishedConsuming(final DriverConductor conductor, final long eosPosition)
{
if (spyPositions.length > 0)
{
for (final ReadablePosition spyPosition : spyPositions)
{
if (spyPosition.getVolatile() < eosPosition)
{
return false;
}
}
conductor.cleanupSpies(NetworkPublication.this);
for (final ReadablePosition position : spyPositions)
{
position.close();
}
spyPositions = EMPTY_POSITIONS;
}
return true;
}
private void updateConnectedStatus(final long timeMs)
{
if (isConnected && timeMs > (timeOfLastStatusMessage(metaDataBuffer) + PUBLICATION_CONNECTION_TIMEOUT_MS))
{
isConnected = false;
}
}
public void onTimeEvent(final long timeNs, final long timeMs, final DriverConductor conductor)
{
updateConnectedStatus(timeMs);
switch (status)
{
case ACTIVE:
checkForBlockedPublisher(timeNs, senderPosition.getVolatile());
break;
case DRAINING:
if (producerPosition() > consumerPosition())
{
if (LogBufferUnblocker.unblock(termBuffers, metaDataBuffer, consumerPosition()))
{
unblockedPublications.orderedIncrement();
timeOfLastActivityNs = timeNs;
break;
}
if (isConnected)
{
break;
}
}
else
{
isEndOfStream = true;
}
if (spiesFinishedConsuming(conductor, consumerPosition()))
{
timeOfLastActivityNs = timeNs;
status = Status.LINGER;
}
break;
case LINGER:
if (timeNs > (timeOfLastActivityNs + PUBLICATION_LINGER_NS))
{
conductor.cleanupPublication(NetworkPublication.this);
status = Status.CLOSING;
}
break;
}
}
public boolean hasReachedEndOfLife()
{
return hasSenderReleased;
}
public void timeOfLastStateChange(final long time)
{
}
public long timeOfLastStateChange()
{
return timeOfLastActivityNs;
}
public void delete()
{
close();
}
public int decRef()
{
final int count = --refCount;
if (0 == count)
{
status = Status.DRAINING;
channelEndpoint.decRef();
timeOfLastActivityNs = nanoClock.nanoTime();
if (consumerPosition() >= producerPosition())
{
isEndOfStream = true;
}
}
return count;
}
public int incRef()
{
return ++refCount;
}
Status status()
{
return status;
}
void senderRelease()
{
hasSenderReleased = true;
}
long producerPosition()
{
final long rawTail = rawTailVolatile(metaDataBuffer);
final int termOffset = termOffset(rawTail, termBufferLength);
return computePosition(termId(rawTail), termOffset, positionBitsToShift, initialTermId);
}
long consumerPosition()
{
return senderPosition.getVolatile();
}
}
| [Java] Minor tidyup.
| aeron-driver/src/main/java/io/aeron/driver/NetworkPublication.java | [Java] Minor tidyup. | <ide><path>eron-driver/src/main/java/io/aeron/driver/NetworkPublication.java
<ide> }
<ide> }
<ide>
<del> conductor.cleanupSpies(NetworkPublication.this);
<add> conductor.cleanupSpies(this);
<ide> for (final ReadablePosition position : spyPositions)
<ide> {
<ide> position.close();
<ide> switch (status)
<ide> {
<ide> case ACTIVE:
<del> checkForBlockedPublisher(timeNs, senderPosition.getVolatile());
<add> checkForBlockedPublisher(timeNs, consumerPosition());
<ide> break;
<ide>
<ide> case DRAINING:
<ide> case LINGER:
<ide> if (timeNs > (timeOfLastActivityNs + PUBLICATION_LINGER_NS))
<ide> {
<del> conductor.cleanupPublication(NetworkPublication.this);
<add> conductor.cleanupPublication(this);
<ide> status = Status.CLOSING;
<ide> }
<ide> break; |
|
JavaScript | mpl-2.0 | 928c82436b5caeac5f8a3149c0196ba10a937e8b | 0 | schmite1/ReadMore,schmite1/ReadMore | // Name: Eric Schmitt
// Course: CSC 415
// Semester: Spring 2015
// Instructor: Dr. Pulimood
// Project name: ReadMore
// Description: A Mozilla Firefox add-on that prevents users from browsing certain sites denoted by a customizable blacklist, not by preventing site access entirely, but by redirecting to productive alternative sites for the user to explore.
// Filename: whitelist.js
// Description: Prototype WhiteList script. Basic functionality that randomly selects one of two URLs in an array to redirect the current webpage.
// Last modified on: 04/14/15
var random = Math.floor(Math.random()*2)
var whiteList = ["http://www.gutenberg.org/ebooks/search/?sort_order=downloads", "https://en.wikipedia.org/wiki/Special:Random"]
window.location.replace(whiteList[random]);
| data/whitelist.js | var random = Math.floor(Math.random()*2)
var whiteList = ["http://www.gutenberg.org/ebooks/search/?sort_order=downloads", "https://en.wikipedia.org/wiki/Special:Random"]
window.location.replace(whiteList[random]);
| Update header information
Added header for maintenance documentation | data/whitelist.js | Update header information | <ide><path>ata/whitelist.js
<add>// Name: Eric Schmitt
<add>// Course: CSC 415
<add>// Semester: Spring 2015
<add>// Instructor: Dr. Pulimood
<add>// Project name: ReadMore
<add>// Description: A Mozilla Firefox add-on that prevents users from browsing certain sites denoted by a customizable blacklist, not by preventing site access entirely, but by redirecting to productive alternative sites for the user to explore.
<add>// Filename: whitelist.js
<add>// Description: Prototype WhiteList script. Basic functionality that randomly selects one of two URLs in an array to redirect the current webpage.
<add>// Last modified on: 04/14/15
<add>
<ide> var random = Math.floor(Math.random()*2)
<ide> var whiteList = ["http://www.gutenberg.org/ebooks/search/?sort_order=downloads", "https://en.wikipedia.org/wiki/Special:Random"]
<ide> |
|
Java | mit | 47f5ed5eaec97a592d0a3d755f35b41a2275cb8e | 0 | JBYoshi/SpongeAPI,boomboompower/SpongeAPI,SpongePowered/SpongeAPI,modwizcode/SpongeAPI,kashike/SpongeAPI,AlphaModder/SpongeAPI,modwizcode/SpongeAPI,kashike/SpongeAPI,DDoS/SpongeAPI,SpongePowered/SpongeAPI,boomboompower/SpongeAPI,DDoS/SpongeAPI,JBYoshi/SpongeAPI,SpongePowered/SpongeAPI,AlphaModder/SpongeAPI | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.data.merge;
import static com.google.common.base.Preconditions.checkNotNull;
import org.spongepowered.api.data.value.BaseValue;
import org.spongepowered.api.data.value.ValueContainer;
import org.spongepowered.api.data.value.mutable.CompositeValueStore;
import java.util.function.Function;
import javax.annotation.Nullable;
/**
* Represents a unique form of {@link Function} that attempts to merge
* two separate {@link ValueContainer}s into a singular {@link ValueContainer}.
* A merge function is similar to a {@link Function} such that it can be reused
* for multiple purposes and should be "stateless" on its own.
*/
@FunctionalInterface
public interface MergeFunction {
/**
* Performs a merge of a type of {@link ValueContainer} such that a merge
* of the contained {@link BaseValue}s has been performed and the resulting
* merged {@link ValueContainer} is returned. It is suffice to say that
* only one of the {@link ValueContainer} containers may be {@code null},
* such that <pre> {@code
* if (original == null) {
* return checkNotNull(replacement);
* } else if (replacement == null) {
* return original;
* } else {
* // do something merging the necessary values
* }
* }</pre>
* It can be therefor discerned that both values are passed in as copies
* and therefor either one can be modified and returned.
*
* <p>Since
* {@link CompositeValueStore#copyFrom(CompositeValueStore, MergeFunction)}
* accepts only a single {@link MergeFunction}, and a
* {@link CompositeValueStore} may have multiple {@link ValueContainer}s,
* as provided by {@link CompositeValueStore#getContainers()}, the merge
* function may be called for every single number of {@link ValueContainer}.
* This way, a {@link MergeFunction} can be fully customized to merge
* specific {@link ValueContainer}s of matching types.</p>
*
* @param original The original {@link ValueContainer} from the value store
* @param replacement The replacing value container
* @param <C> The type of {@link ValueContainer}
* @return The "merged" {@link ValueContainer}
*/
<C extends ValueContainer<?>> C merge(@Nullable C original, @Nullable C replacement);
/**
* Creates a new {@link MergeFunction} chaining this current merge function
* with the provided merge function. The order of the merge is this
* performes {@link #merge(ValueContainer, ValueContainer)} then, the
* provided {@link MergeFunction} merges the returned merged
* {@link ValueContainer} and the {@code replacement}. This can be used to
* apply a custom merge strategy after a pre-defined {@link MergeFunction}
* is applied.
*
* @param that The {@link MergeFunction} to chain
* @return The new {@link MergeFunction}
*/
default MergeFunction andThen(final MergeFunction that) {
final MergeFunction self = this;
return new MergeFunction() {
@Override
public <C extends ValueContainer<?>> C merge(C original, C replacement) {
return that.merge(self.merge(original, replacement), replacement);
}
};
}
/**
* Represents a {@link MergeFunction} that ignores all merges and uses the
* replacement, or the original if the replacement is {@code null}.
*/
MergeFunction IGNORE_ALL = new MergeFunction() {
@Override
public <C extends ValueContainer<?>> C merge(@Nullable C original, @Nullable C replacement) {
return replacement == null ? checkNotNull(original, "Original and replacement cannot be null!") : replacement;
}
};
/**
* Represents a {@link MergeFunction} that forces no merges and uses the
* original, or proposed replacement if the original is {@code null}.
*/
MergeFunction FORCE_NOTHING = new MergeFunction() {
@Override
public <C extends ValueContainer<?>> C merge(@Nullable C original, @Nullable C replacement) {
return original == null ? checkNotNull(replacement, "Replacement and original cannot be null!") : original;
}
};
}
| src/main/java/org/spongepowered/api/data/merge/MergeFunction.java | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.data.merge;
import static com.google.common.base.Preconditions.checkNotNull;
import org.spongepowered.api.data.value.BaseValue;
import org.spongepowered.api.data.value.ValueContainer;
import org.spongepowered.api.data.value.mutable.CompositeValueStore;
import java.util.function.Function;
import javax.annotation.Nullable;
/**
* Represents a unique form of {@link Function} that attempts to merge
* two separate {@link ValueContainer}s into a singular {@link ValueContainer}.
* A merge function is similar to a {@link Function} such that it can be reused
* for multiple purposes and should be "stateless" on its own.
*/
@FunctionalInterface
public interface MergeFunction {
/**
* Performs a merge of a type of {@link ValueContainer} such that a merge
* of the contained {@link BaseValue}s has been performed and the resulting
* merged {@link ValueContainer} is returned. It is suffice to say that
* only one of the {@link ValueContainer} containers may be {@code null},
* such that <pre> {@code
* if (original == null) {
* return checkNotNull(replacement);
* } else if (replacement == null) {
* return original;
* } else {
* // do something merging the necessary values
* }
* }</pre>
* It can be therefor discerned that both values are passed in as copies
* and therefor either one can be modified and returned.
*
* <p>Since
* {@link CompositeValueStore#copyFrom(CompositeValueStore, MergeFunction)}
* accepts only a single {@link MergeFunction}, and a
* {@link CompositeValueStore} may have multiple {@link ValueContainer}s,
* as provided by {@link CompositeValueStore#getContainers()}, the merge
* function may be called for every single number of {@link ValueContainer}.
* This way, a {@link MergeFunction} can be fully customized to merge
* specific {@link ValueContainer}s of matching types.</p>
*
* @param original The original {@link ValueContainer} from the value store
* @param replacement The replacing value container
* @param <C> The type of {@link ValueContainer}
* @return The "merged" {@link ValueContainer}
*/
<C extends ValueContainer<?>> C merge(@Nullable C original, @Nullable C replacement);
/**
* Creates a new {@link MergeFunction} chaining this current merge function
* with the provided merge function. The order of the merge is this
* performes {@link #merge(ValueContainer, ValueContainer)} then, the
* provided {@link MergeFunction} merges the returned merged
* {@link ValueContainer} and the {@code replacement}. This can be used to
* apply a custom merge strategy after a pre-defined {@link MergeFunction}
* is applied.
*
* @param that The {@link MergeFunction} to chain
* @return The new {@link MergeFunction}
*/
default MergeFunction andThen(final MergeFunction that) {
final MergeFunction self = this;
return new MergeFunction() {
@Override
public <C extends ValueContainer<?>> C merge(C original, C replacement) {
return that.merge(self.merge(original, replacement), replacement);
}
};
}
/**
* Represents a {@link MergeFunction} that ignores all merges and uses the
* replacement, or the original if the replacement is {@code null}.
*/
MergeFunction IGNORE_ALL = new MergeFunction() {
@Override
public <C extends ValueContainer<?>> C merge(@Nullable C original, @Nullable C replacement) {
return replacement == null ? checkNotNull(original) : replacement;
}
};
/**
* Represents a {@link MergeFunction} that forces no merges and uses the
* original, or proposed replacement if the original is {@code null}.
*/
MergeFunction FORCE_NOTHING = new MergeFunction() {
@Override
public <C extends ValueContainer<?>> C merge(@Nullable C original, @Nullable C replacement) {
return original == null ? checkNotNull(replacement) : original;
}
};
}
| Add some helpful error messages from MergeFunction.
Signed-off-by: Gabriel Harris-Rouquette <[email protected]>
| src/main/java/org/spongepowered/api/data/merge/MergeFunction.java | Add some helpful error messages from MergeFunction. | <ide><path>rc/main/java/org/spongepowered/api/data/merge/MergeFunction.java
<ide> MergeFunction IGNORE_ALL = new MergeFunction() {
<ide> @Override
<ide> public <C extends ValueContainer<?>> C merge(@Nullable C original, @Nullable C replacement) {
<del> return replacement == null ? checkNotNull(original) : replacement;
<add> return replacement == null ? checkNotNull(original, "Original and replacement cannot be null!") : replacement;
<ide> }
<ide> };
<ide>
<ide> MergeFunction FORCE_NOTHING = new MergeFunction() {
<ide> @Override
<ide> public <C extends ValueContainer<?>> C merge(@Nullable C original, @Nullable C replacement) {
<del> return original == null ? checkNotNull(replacement) : original;
<add> return original == null ? checkNotNull(replacement, "Replacement and original cannot be null!") : original;
<ide> }
<ide> };
<ide> |
|
Java | apache-2.0 | 1b017520be5a84e1f1e134b05d347edb1acc6e0e | 0 | echsylon/kraken | package com.echsylon.kraken;
import android.net.Uri;
import com.echsylon.blocks.callback.DefaultRequest;
import com.echsylon.blocks.callback.Request;
import com.echsylon.blocks.network.NetworkClient;
import com.echsylon.blocks.network.OkHttpNetworkClient;
import com.echsylon.kraken.dto.Asset;
import com.echsylon.kraken.dto.AssetPair;
import com.echsylon.kraken.dto.Depth;
import com.echsylon.kraken.dto.Ledger;
import com.echsylon.kraken.dto.Ohlc;
import com.echsylon.kraken.dto.Order;
import com.echsylon.kraken.dto.OrderCancelState;
import com.echsylon.kraken.dto.OrderReceipt;
import com.echsylon.kraken.dto.Position;
import com.echsylon.kraken.dto.Spread;
import com.echsylon.kraken.dto.Ticker;
import com.echsylon.kraken.dto.Time;
import com.echsylon.kraken.dto.Trade;
import com.echsylon.kraken.dto.TradeBalance;
import com.echsylon.kraken.dto.TradeHistory;
import com.echsylon.kraken.dto.TradeVolume;
import com.echsylon.kraken.exception.KrakenRequestException;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.echsylon.kraken.Utils.asBytes;
import static com.echsylon.kraken.Utils.asString;
import static com.echsylon.kraken.Utils.base64Decode;
import static com.echsylon.kraken.Utils.base64Encode;
import static com.echsylon.kraken.Utils.concat;
import static com.echsylon.kraken.Utils.hmacSha512;
import static com.echsylon.kraken.Utils.join;
import static com.echsylon.kraken.Utils.sha256;
/**
* This class describes the Kraken API.
* <p>
* For further technical details see Kraken API documentation at:
* https://www.kraken.com/help/api
*/
public class Kraken {
private static final String BASE_URL = "https://api.kraken.com";
/**
* Initiates the Kraken API Client local cache metrics.
*
* @param cacheDirectory The location on disk to save the cache in.
* @param cacheSizeBytes The max number of bytes to allocate to caching.
*/
public static void setup(final File cacheDirectory, final int cacheSizeBytes) {
OkHttpNetworkClient.settings(
new OkHttpNetworkClient.Settings(
cacheDirectory,
cacheSizeBytes,
false, // Follow http -> http redirects
false)); // Follow https -> http redirects
}
private String baseUrl;
private String key;
private byte[] secret;
/**
* Allows test cases to redirect requests to a test environment. Protected
* to keep false assumptions away.
*
* @param baseUrl The base url to the test environment.
*/
Kraken(String baseUrl) {
this.baseUrl = baseUrl;
}
/**
* Initializes an instance of the Kraken API Client that's only capable of
* accessing the public Kraken API.
*/
public Kraken() {
this(null, null);
}
/**
* Initializes an instance of the Kraken API Client that's capable of
* executing private API requests (given that the provided credentials are
* valid).
*
* @param apiKey The Kraken API key for the targeted account.
* @param apiSecret The corresponding key secret.
*/
public Kraken(String apiKey, String apiSecret) {
baseUrl = BASE_URL;
key = apiKey;
secret = base64Decode(apiSecret);
}
/**
* Retrieves the current server time. This is to aid in approximating the
* skew time between the server and client.
*
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<Time> getServerTime() {
return getRequestBuilder("/0/public/Time", "get");
}
/**
* Retrieves information about supported currency assets. See API
* documentation on supported asset formats.
*
* @param info The level of information to get.
* @param assetClass The type of the asset.
* @param assets The assets to get info on.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<List<Asset>> getAssetInfo(final String info,
final String assetClass,
final String... assets) {
return getRequestBuilder(
new AssetTypeAdapter(),
"/0/public/Assets",
"get",
"info", info,
"aclass", assetClass,
"assets", join(assets));
}
/**
* Retrieves information about tradable asset pairs. Not providing any
* specific asset pairs will return info for all known assets.
* <p>
* See API documentation on supported asset pair formats.
*
* @param info The level of information to get. Options: "info" (all,
* default), "leverage", "fees", "margin"
* @param pairs The currencies to fetch information for.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<AssetPair> getTradableAssetPairs(final String info,
final String... pairs) {
return getRequestBuilder(
"/0/public/AssetPairs",
"get",
"info", info,
"pair", join(pairs));
}
/**
* Retrieves information about the ticker state for tradable asset pairs.
*
* @param pairs The asset pairs to fetch information on. At least one must
* be given or the server will fail.
* @return A request builder object to configure any client side cache *
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<Map<String, Ticker>> getTickerInformation(final String... pairs) {
return getRequestBuilder(
new TickerTypeAdapter(),
"/0/public/Ticker",
"get",
"pair", join(pairs));
}
/**
* Retrieves information about the Open/High/Low/Close state for a tradable
* asset pair.
*
* @param pair The single asset pair to get information for.
* @param interval The time span base (in minutes) for the OHLC data.
* Options: 1 (default), 5, 15, 30, 60, 240, 1440, 10080,
* 21600
* @param since The exclusive epoch describing how far back in time to
* get OHLC data from.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Ohlc>> getOhlcData(final String pair,
final Integer interval,
final String since) {
return getRequestBuilder(
new OhlcTypeAdapter(),
"/0/public/OHLC",
"get",
"pair", pair,
"interval", asString(interval),
"since", since);
}
/**
* Retrieves the market depth for tradable asset pairs.
*
* @param pair The asset pair to get market depth for.
* @param count The maximum number of asks or bids. Optional.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<Depth> getOrderBook(final String pair, final Integer count) {
return getRequestBuilder(
new DepthTypeAdapter(),
"/0/public/Depth",
"get",
"pair", pair,
"count", asString(count));
}
/**
* Retrieves recent trades on the market.
*
* @param pair The asset pair to get data for.
* @param since The trade id of the previous poll. Optional. Exclusive.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Trade>> getRecentTrades(final String pair,
final String since) {
return getRequestBuilder(
new TradeTypeAdapter(),
"/0/public/Trades",
"get",
"pair", pair,
"since", since);
}
/**
* Retrieves information about recent spread data for a tradable asset pair.
*
* @param pair The asset pair to get information for.
* @param since The spread id of the previous poll. Optional. Inclusive.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Spread>> getRecentSpreadData(final String pair,
final String since) {
return getRequestBuilder(
new SpreadTypeAdapter(),
"/0/public/Spread",
"get",
"pair", pair,
"since", since);
}
// Private user data API
/**
* Retrieves the account balance for all associated assets.
*
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<Map<String, String>> getAccountBalance() {
return getRequestBuilder("/0/private/Balance", "post");
}
/**
* Retrieves the trade balance of an asset.
*
* @param assetClass The type of asset. Defaults to "currency".
* @param baseAsset The base asset to use when determining the balance.
* Defaults to "ZUSD"
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<TradeBalance> getTradeBalance(final String assetClass,
final String baseAsset) {
return getRequestBuilder(
"/0/private/TradeBalance",
"post",
"aclass", assetClass,
"asset", baseAsset);
}
/**
* Retrieves information about any open orders.
*
* @param includeTrades Whether to include trades. Defaults to false.
* @param userReferenceId Restrict results to given user reference id.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Order>> getOpenOrders(final Boolean includeTrades,
final String userReferenceId) {
return getRequestBuilder(
new OrderTypeAdapter(),
"/0/private/OpenOrders",
"post",
"trades", asString(includeTrades),
"userref", userReferenceId);
}
/**
* Retrieves information about any closed orders.
*
* @param includeTrades Whether to include trades. Defaults to false.
* @param userReferenceId Restrict results to user reference id. Optional.
* @param start Starting time or order transaction id of results.
* Optional. Exclusive.
* @param end Ending time or order transaction id of results.
* Optional. Inclusive.
* @param offset Result offset.
* @param closeTime Which time to use. Options: "open", "close",
* "both" (default).
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Order>> getClosedOrders(final Boolean includeTrades,
final String userReferenceId,
final String start,
final String end,
final Integer offset,
final String closeTime) {
return getRequestBuilder(
new OrderTypeAdapter(),
"/0/private/ClosedOrders",
"post",
"trades", asString(includeTrades),
"userref", userReferenceId,
"start", start,
"end", end,
"ofs", asString(offset),
"closetime", closeTime);
}
/**
* Retrieves information about any particular order(s)
*
* @param includeTrades Whether to include trades.
* @param userReferenceId Restrict results to user reference id. Optional.
* @param transactionId Transaction ids of the orders to get info about.
* 20 max, at least one is required.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Order>> queryOrdersInfo(final Boolean includeTrades,
final String userReferenceId,
final String... transactionId) {
return getRequestBuilder(
new OrderTypeAdapter(),
"/0/private/QueryOrders",
"post",
"trades", asString(includeTrades),
"userref", userReferenceId,
"txid", join(transactionId));
}
/**
* Retrieves trades history
*
* @param type The type of trades to get. Options: "all" (default),
* "any position", "closed position", "closing
* position", "no position".
* @param includeTrades Whether to include trades related to position.
* @param start Starting time or trade transaction id of results.
* Optional. Exclusive.
* @param end Ending time or trade transaction id of results.
* Optional. Inclusive.
* @param offset Result offset.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<TradeHistory>> getTradesHistory(final String type,
final Boolean includeTrades,
final String start,
final String end,
final Integer offset) {
return getRequestBuilder(
new TradeHistoryTypeAdapter(),
"/0/private/TradesHistory",
"post",
"type", type,
"trades", asString(includeTrades),
"start", start,
"end", end,
"ofs", asString(offset));
}
/**
* Retrieves information about any particular trades(s)
*
* @param includePositionTrades Whether to include trades related to
* position. Defaults to false.
* @param transactionId Transaction ids of the orders to get info
* about. 20 max, at least one is required.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<TradeHistory>> queryTradesInfo(final Boolean includePositionTrades,
final String... transactionId) {
return getRequestBuilder(
new TradeHistoryTypeAdapter(),
"/0/private/QueryTrades",
"post",
"trades", asString(includePositionTrades),
"txid", join(transactionId));
}
/**
* Retrieves information about any open positions
*
* @param performCalculations Whether to include profit/loss calculations.
* Defaults to false.
* @param transactionId Transaction ids to restrict the result to.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Position>> getOpenPositions(final Boolean performCalculations,
final String... transactionId) {
return getRequestBuilder(
new PositionTypeAdapter(),
"/0/private/OpenPositions",
"post",
"docalcs", asString(performCalculations),
"txid", join(transactionId));
}
/**
* Retrieves information about the ledgers.
*
* @param assetClass The type of asset. Defaults to "currency".
* @param ledgerType Type of ledger to get. Options: "all" (default),
* "deposit", "withdrawal", "trade", "margin"
* @param start Starting time or ledger id of results. Optional.
* Exclusive.
* @param end Ending time or ledger id of results. Optional.
* Inclusive.
* @param offset Result offset.
* @param asset Assets to restrict result to. Defaults to all.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Ledger>> getLedgersInfo(final String assetClass,
final String ledgerType,
final String start,
final String end,
final Integer offset,
final String... asset) {
return getRequestBuilder(
new LedgerTypeAdapter(),
"/0/private/Ledgers",
"post",
"aclass", assetClass,
"type", ledgerType,
"start", start,
"end", end,
"ofs", asString(offset),
"asset", join(asset));
}
/**
* Retrieves information about any particular ledger(s).
*
* @param ledgerId Id of ledgers to get. 20 max, at least one is required.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Ledger>> queryLedgers(final String... ledgerId) {
return getRequestBuilder(
new LedgerTypeAdapter(),
"/0/private/QueryLedgers",
"post",
"id", join(ledgerId));
}
/**
* Retrieves information about the current trade volumes.
*
* @param includeFeeInfo Whether to include fee info. Defaults to false.
* @param feeInfoAssetPair The fee info asset pairs. Defaults to "ZUSD".
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<TradeVolume> getTradeVolume(final Boolean includeFeeInfo,
final String... feeInfoAssetPair) {
return getRequestBuilder(
"/0/private/TradeVolume",
"post",
"fee-info", asString(includeFeeInfo),
"pair", join(feeInfoAssetPair));
}
// Private user trading
/**
* Adds a regular sell or buy order
*
* @param pair Asset pair of the new order.
* @param type Nature of the order. Options: "buy", "sell".
* @param orderType The type of the order. Options: "market",
* "limit", "stop-loss", "take-profit",
* "stop-loss-profit", "stop-loss-profit-limit",
* "stop-loss-limit", "take-profit-limit",
* "trailing-stop", "trailing-stop-limit",
* "stop-loss-and-limit", "settle-position".
* @param price Price (depends on orderType). Optional.
* @param secondaryPrice Price2 (depends on orderType). Optional.
* @param volume Order volume in lots.
* @param leverage Amount of desired leverage. Defaults to none.
* @param startTime Scheduled start time as epoch seconds.
* Options: 0 (default), +[n], [n]. Optional.
* @param expireTime Expiration time expressed in epoch seconds.
* Options: 0 (no exp. default), +[n], [n].
* Optional.
* @param userReference User reference id. 32-bit, signed. Optional.
* @param closeOrderType Closing order type. Optional.
* @param closePrice Closing order price. Optional.
* @param closeSecondaryPrice Closing order secondary price. Optional.
* @param validateOnly Validate only, do not submit order. Optional.
* @param flags Order flags. Options: "viqc", "fcib", "fciq",
* "nompp", "post". Optional.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<OrderReceipt> addStandardOrder(final String pair,
final String type,
final String orderType,
final String price,
final String secondaryPrice,
final String volume,
final String leverage,
final String startTime,
final String expireTime,
final String userReference,
final String closeOrderType,
final String closePrice,
final String closeSecondaryPrice,
final Boolean validateOnly,
final String... flags) {
return getRequestBuilder(
"/0/private/AddOrder",
"post",
"pair", pair,
"type", type,
"ordertype", orderType,
"price", price,
"price2", secondaryPrice,
"volume", volume,
"leverage", leverage,
"oflags", join(flags),
"starttm", startTime,
"expiretm", expireTime,
"userref", userReference,
"validate", asString(validateOnly),
"close[ordertype]", closeOrderType,
"close[price]", closePrice,
"close[price2]", closeSecondaryPrice);
}
/**
* Cancels an open order.
*
* @param id The transaction or user reference id of the order(s) to close.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<OrderCancelState> cancelOpenOrder(final String id) {
return getRequestBuilder("/0/private/CancelOrder", "post", "txid", id);
}
// Private boilerplate
/**
* Decorates and enqueues a new Kraken request.
*
* @param path The path of the url to request.
* @param method The HTTP method of the request.
* @param data The optional key/value entries to pass along. Even
* positions are treated as keys and odd positions as values.
* Any trailing keys will be ignored.
* @param <V> The type definition of the result Java class.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
private <V> KrakenRequestBuilder<V> getRequestBuilder(final String path,
final String method,
final String... data) {
return getRequestBuilder(null, path, method, data);
}
/**
* Decorates and enqueues a new Kraken request.
*
* @param typeAdapter JSON adapter to parse non-default data structures.
* @param path The path of the url to request.
* @param method The HTTP method of the request.
* @param data The optional key/value entries to pass along. Even
* positions are treated as keys and odd positions as
* values. Any trailing keys will be ignored.
* @param <V> The type definition of the result Java class.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
private <V> KrakenRequestBuilder<V> getRequestBuilder(final TypeAdapter<V> typeAdapter,
final String path,
final String method,
final String... data) {
return new KrakenRequestBuilder<V>() {
@Override
public Request<V> enqueue() {
return new DefaultRequest<>(() -> {
// Perform coarse API key+secret validation
if (isPrivateRequest(path) && (key == null || secret == null))
throw new IllegalStateException(
"An API key and secret is required for this request");
// Everything's peachy: prepare the Kraken request decoration
String nonce = generateNonce(path);
String message = composeMessage(nonce, data);
List<NetworkClient.Header> headers = generateSignature(path, nonce, message);
// Prepare the HTTP metrics depending on "get" or "post" method.
boolean isGetMethod = "get".equals(method.toLowerCase());
byte[] payload = isGetMethod ? null : asBytes(message);
String mime = isGetMethod ? null : "application/x-www-form-urlencoded";
String uri = isGetMethod ?
String.format("%s%s?%s", baseUrl, path, message) :
String.format("%s%s", baseUrl, path);
// Perform the actual request (the network client stems from
// CachedRequestBuilder (extended by KrakenRequestBuilder).
byte[] responseBytes = okHttpNetworkClient.execute(uri, method, headers, payload, mime);
String responseJson = asString(responseBytes);
// Parse the response JSON
Type type = new TypeToken<KrakenResponse<V>>() {}.getType();
KrakenResponse<V> response = new GsonBuilder()
.registerTypeAdapter(type, new KrakenTypeAdapter<>(typeAdapter))
.create()
.fromJson(responseJson, type);
// Throw exception if has error (to trigger error callbacks)...
if (response.error != null)
throw new KrakenRequestException(response.error);
// ...or deliver result.
return response.result;
});
}
};
}
/**
* Checks whether a given url is targeting a private endpoint in the Kraken
* API.
*
* @param url The url to check.
* @return Boolean true if targeting a private endpoint, false otherwise.
*/
private boolean isPrivateRequest(final String url) {
return url.contains("/private/");
}
/**
* Generates a nonce for private requests, or null for public requests.
*
* @return The nonce or null.
*/
private String generateNonce(final String url) {
return url != null && isPrivateRequest(url) ?
String.format("%-16s", System.currentTimeMillis())
.replace(" ", "0") :
null;
}
/**
* Constructs an encoded request message that Kraken will understand. See
* Kraken API documentation for details.
*
* @param nonce The request nonce. Ignored if null.
* @param data The actual key value pairs to build the message from. Even
* positions are treated as keys and odd positions as values.
* Any null pointer key or value will render the key/value pair
* invalid and hence ignored. Any trailing keys will also be
* ignored.
* @return The prepared and encoded Kraken message.
*/
private String composeMessage(final String nonce, final String... data) {
Uri.Builder builder = new Uri.Builder();
if (nonce != null)
builder.appendQueryParameter("nonce", nonce);
if (data != null && data.length > 1)
for (int i = 0; i < data.length; i += 2)
if (data[i] != null && data[i + 1] != null)
builder.appendQueryParameter(data[i], data[i + 1]);
return builder.build().getEncodedQuery();
}
/**
* Generates the message signature headers. See Kraken API documentation for
* details.
*
* @param path The request path.
* @param nonce The request nonce that was used for the message.
* @param message The request message
* @return The Kraken request signature headers. Null if no path is given or
* an empty list if no nonce is given.
*/
private List<NetworkClient.Header> generateSignature(final String path,
final String nonce,
final String message) {
if (key == null || secret == null)
return null;
if (path == null)
return null;
if (nonce == null)
return null;
byte[] data = sha256(asBytes(nonce + message));
if (data == null)
return null;
byte[] input = concat(asBytes(path), data);
byte[] signature = hmacSha512(input, secret);
if (signature == null)
return null;
List<NetworkClient.Header> headers = new ArrayList<>(2);
headers.add(new NetworkClient.Header("API-Key", key));
headers.add(new NetworkClient.Header("API-Sign", base64Encode(signature)));
return headers;
}
}
| library/src/main/java/com/echsylon/kraken/Kraken.java | package com.echsylon.kraken;
import android.net.Uri;
import com.echsylon.blocks.callback.DefaultRequest;
import com.echsylon.blocks.callback.Request;
import com.echsylon.blocks.network.NetworkClient;
import com.echsylon.blocks.network.OkHttpNetworkClient;
import com.echsylon.kraken.dto.Asset;
import com.echsylon.kraken.dto.AssetPair;
import com.echsylon.kraken.dto.Depth;
import com.echsylon.kraken.dto.Ledger;
import com.echsylon.kraken.dto.Ohlc;
import com.echsylon.kraken.dto.Order;
import com.echsylon.kraken.dto.OrderCancelState;
import com.echsylon.kraken.dto.OrderReceipt;
import com.echsylon.kraken.dto.Position;
import com.echsylon.kraken.dto.Spread;
import com.echsylon.kraken.dto.Ticker;
import com.echsylon.kraken.dto.Time;
import com.echsylon.kraken.dto.Trade;
import com.echsylon.kraken.dto.TradeBalance;
import com.echsylon.kraken.dto.TradeHistory;
import com.echsylon.kraken.dto.TradeVolume;
import com.echsylon.kraken.exception.KrakenRequestException;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.echsylon.kraken.Utils.asBytes;
import static com.echsylon.kraken.Utils.asString;
import static com.echsylon.kraken.Utils.base64Decode;
import static com.echsylon.kraken.Utils.base64Encode;
import static com.echsylon.kraken.Utils.concat;
import static com.echsylon.kraken.Utils.hmacSha512;
import static com.echsylon.kraken.Utils.join;
import static com.echsylon.kraken.Utils.sha256;
/**
* This class describes the Kraken API.
* <p>
* For further technical details see Kraken API documentation at:
* https://www.kraken.com/help/api
*/
public class Kraken {
private static final String BASE_URL = "https://api.kraken.com";
/**
* Initiates the Kraken API Client local cache metrics.
*
* @param cacheDirectory The location on disk to save the cache in.
* @param cacheSizeBytes The max number of bytes to allocate to caching.
*/
public static void setup(final File cacheDirectory, final int cacheSizeBytes) {
OkHttpNetworkClient.settings(
new OkHttpNetworkClient.Settings(
cacheDirectory,
cacheSizeBytes,
false, // Follow http -> http redirects
false)); // Follow https -> http redirects
}
private String baseUrl;
private String key;
private byte[] secret;
/**
* Allows test cases to redirect requests to a test environment. Protected
* to keep false assumptions away.
*
* @param baseUrl The base url to the test environment.
*/
Kraken(String baseUrl) {
this.baseUrl = baseUrl;
}
/**
* Initializes an instance of the Kraken API Client that's only capable of
* accessing the public Kraken API.
*/
public Kraken() {
this(null, null);
}
/**
* Initializes an instance of the Kraken API Client that's capable of
* executing private API requests (given that the provided credentials are
* valid).
*
* @param apiKey The Kraken API key for the targeted account.
* @param apiSecret The corresponding key secret.
*/
public Kraken(String apiKey, String apiSecret) {
baseUrl = BASE_URL;
key = apiKey;
secret = base64Decode(apiSecret);
}
/**
* Retrieves the current server time. This is to aid in approximating the
* skew time between the server and client.
*
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<Time> getServerTime() {
return getRequestBuilder("/0/public/Time", "get");
}
/**
* Retrieves information about supported currency assets. See API
* documentation on supported asset formats.
*
* @param info The level of information to get.
* @param assetClass The type of the asset.
* @param assets The assets to get info on.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<List<Asset>> getAssetInfo(final String info,
final String assetClass,
final String... assets) {
return getRequestBuilder(
new AssetTypeAdapter(),
"/0/public/Assets",
"get",
"info", info,
"aclass", assetClass,
"assets", join(assets));
}
/**
* Retrieves information about tradable asset pairs. Not providing any
* specific asset pairs will return info for all known assets.
* <p>
* See API documentation on supported asset pair formats.
*
* @param info The level of information to get. Options: "info" (all,
* default), "leverage", "fees", "margin"
* @param pairs The currencies to fetch information for.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<AssetPair> getTradableAssetPairs(final String info,
final String... pairs) {
return getRequestBuilder(
"/0/public/AssetPairs",
"get",
"info", info,
"pair", join(pairs));
}
/**
* Retrieves information about the ticker state for tradable asset pairs.
*
* @param pairs The asset pairs to fetch information on. At least one must
* be given or the server will fail.
* @return A request builder object to configure any client side cache *
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<Map<String, Ticker>> getTickerInformation(final String... pairs) {
return getRequestBuilder(
new TickerTypeAdapter(),
"/0/public/Ticker",
"get",
"pair", join(pairs));
}
/**
* Retrieves information about the Open/High/Low/Close state for a tradable
* asset pair.
*
* @param pair The single asset pair to get information for.
* @param interval The time span base (in minutes) for the OHLC data.
* Options: 1 (default), 5, 15, 30, 60, 240, 1440, 10080,
* 21600
* @param since The exclusive epoch describing how far back in time to
* get OHLC data from.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Ohlc>> getOhlcData(final String pair,
final Integer interval,
final String since) {
return getRequestBuilder(
new OhlcTypeAdapter(),
"/0/public/OHLC",
"get",
"pair", pair,
"interval", asString(interval),
"since", since);
}
/**
* Retrieves the market depth for tradable asset pairs.
*
* @param pair The asset pair to get market depth for.
* @param count The maximum number of asks or bids. Optional.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<Depth> getOrderBook(final String pair, final Integer count) {
return getRequestBuilder(
new DepthTypeAdapter(),
"/0/public/Depth",
"get",
"pair", pair,
"count", asString(count));
}
/**
* Retrieves recent trades on the market.
*
* @param pair The asset pair to get data for.
* @param since The trade id of the previous poll. Optional. Exclusive.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Trade>> getRecentTrades(final String pair,
final String since) {
return getRequestBuilder(
new TradeTypeAdapter(),
"/0/public/Trades",
"get",
"pair", pair,
"since", since);
}
/**
* Retrieves information about recent spread data for a tradable asset pair.
*
* @param pair The asset pair to get information for.
* @param since The spread id of the previous poll. Optional. Inclusive.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Spread>> getRecentSpreadData(final String pair,
final String since) {
return getRequestBuilder(
new SpreadTypeAdapter(),
"/0/public/Spread",
"get",
"pair", pair,
"since", since);
}
// Private user data API
/**
* Retrieves the account balance for all associated assets.
*
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<Map<String, String>> getAccountBalance() {
return getRequestBuilder("/0/private/Balance", "post");
}
/**
* Retrieves the trade balance of an asset.
*
* @param assetClass The type of asset. Defaults to "currency".
* @param baseAsset The base asset to use when determining the balance.
* Defaults to "ZUSD"
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<TradeBalance> getTradeBalance(final String assetClass,
final String baseAsset) {
return getRequestBuilder(
"/0/private/TradeBalance",
"post",
"aclass", assetClass,
"asset", baseAsset);
}
/**
* Retrieves information about any open orders.
*
* @param includeTrades Whether to include trades. Defaults to false.
* @param userReferenceId Restrict results to given user reference id.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Order>> getOpenOrders(final Boolean includeTrades,
final String userReferenceId) {
return getRequestBuilder(
new OrderTypeAdapter(),
"/0/private/OpenOrders",
"post",
"trades", asString(includeTrades),
"userref", userReferenceId);
}
/**
* Retrieves information about any closed orders.
*
* @param includeTrades Whether to include trades. Defaults to false.
* @param userReferenceId Restrict results to user reference id. Optional.
* @param start Starting time or order transaction id of results.
* Optional. Exclusive.
* @param end Ending time or order transaction id of results.
* Optional. Inclusive.
* @param offset Result offset.
* @param closeTime Which time to use. Options: "open", "close",
* "both" (default).
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Order>> getClosedOrders(final Boolean includeTrades,
final String userReferenceId,
final String start,
final String end,
final Integer offset,
final String closeTime) {
return getRequestBuilder(
new OrderTypeAdapter(),
"/0/private/ClosedOrders",
"post",
"trades", asString(includeTrades),
"userref", userReferenceId,
"start", start,
"end", end,
"ofs", asString(offset),
"closetime", closeTime);
}
/**
* Retrieves information about any particular order(s)
*
* @param includeTrades Whether to include trades.
* @param userReferenceId Restrict results to user reference id. Optional.
* @param transactionId Transaction ids of the orders to get info about.
* 20 max, at least one is required.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Order>> queryOrdersInfo(final Boolean includeTrades,
final String userReferenceId,
final String... transactionId) {
return getRequestBuilder(
new OrderTypeAdapter(),
"/0/private/QueryOrders",
"post",
"trades", asString(includeTrades),
"userref", userReferenceId,
"txid", join(transactionId));
}
/**
* Retrieves trades history
*
* @param type The type of trades to get. Options: "all" (default),
* "any position", "closed position", "closing
* position", "no position".
* @param includeTrades Whether to include trades related to position.
* @param start Starting time or trade transaction id of results.
* Optional. Exclusive.
* @param end Ending time or trade transaction id of results.
* Optional. Inclusive.
* @param offset Result offset.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<TradeHistory>> getTradesHistory(final String type,
final Boolean includeTrades,
final String start,
final String end,
final Integer offset) {
return getRequestBuilder(
new TradeHistoryTypeAdapter(),
"/0/private/TradesHistory",
"post",
"type", type,
"trades", asString(includeTrades),
"start", start,
"end", end,
"ofs", asString(offset));
}
/**
* Retrieves information about any particular trades(s)
*
* @param includePositionTrades Whether to include trades related to
* position. Defaults to false.
* @param transactionId Transaction ids of the orders to get info
* about. 20 max, at least one is required.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<TradeHistory>> queryTradesInfo(final Boolean includePositionTrades,
final String... transactionId) {
return getRequestBuilder(
new TradeHistoryTypeAdapter(),
"/0/private/QueryTrades",
"post",
"trades", asString(includePositionTrades),
"txid", join(transactionId));
}
/**
* Retrieves information about any open positions
*
* @param performCalculations Whether to include profit/loss calculations.
* Defaults to false.
* @param transactionId Transaction ids to restrict the result to.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Position>> getOpenPositions(final Boolean performCalculations,
final String... transactionId) {
return getRequestBuilder(
new PositionTypeAdapter(),
"/0/private/OpenPositions",
"post",
"docalcs", asString(performCalculations),
"txid", join(transactionId));
}
/**
* Retrieves information about the ledgers.
*
* @param assetClass The type of asset. Defaults to "currency".
* @param ledgerType Type of ledger to get. Options: "all" (default),
* "deposit", "withdrawal", "trade", "margin"
* @param start Starting time or ledger id of results. Optional.
* Exclusive.
* @param end Ending time or ledger id of results. Optional.
* Inclusive.
* @param offset Result offset.
* @param asset Assets to restrict result to. Defaults to all.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Ledger>> getLedgersInfo(final String assetClass,
final String ledgerType,
final String start,
final String end,
final Integer offset,
final String... asset) {
return getRequestBuilder(
new LedgerTypeAdapter(),
"/0/private/Ledgers",
"post",
"aclass", assetClass,
"type", ledgerType,
"start", start,
"end", end,
"ofs", asString(offset),
"asset", join(asset));
}
/**
* Retrieves information about any particular ledger(s).
*
* @param ledgerId Id of ledgers to get. 20 max, at least one is required.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<KrakenList<Ledger>> queryLedgers(final String... ledgerId) {
return getRequestBuilder(
new LedgerTypeAdapter(),
"/0/private/QueryLedgers",
"post",
"id", join(ledgerId));
}
/**
* Retrieves information about the current trade volumes.
*
* @param includeFeeInfo Whether to include fee info. Defaults to false.
* @param feeInfoAssetPair The fee info asset pairs. Defaults to "ZUSD".
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<TradeVolume> getTradeVolume(final Boolean includeFeeInfo,
final String... feeInfoAssetPair) {
return getRequestBuilder(
"/0/private/TradeVolume",
"post",
"fee-info", asString(includeFeeInfo),
"pair", join(feeInfoAssetPair));
}
// Private user trading
/**
* Adds a regular sell or buy order
*
* @param pair Asset pair of the new order.
* @param type Nature of the order. Options: "buy", "sell".
* @param orderType The type of the order. Options: "market",
* "limit", "stop-loss", "take-profit",
* "stop-loss-profit", "stop-loss-profit-limit",
* "stop-loss-limit", "take-profit-limit",
* "trailing-stop", "trailing-stop-limit",
* "stop-loss-and-limit", "settle-position".
* @param price Price (depends on orderType). Optional.
* @param secondaryPrice Price2 (depends on orderType). Optional.
* @param volume Order volume in lots.
* @param leverage Amount of desired leverage. Defaults to none.
* @param startTime Scheduled start time as epoch seconds.
* Options: 0 (default), +[n], [n]. Optional.
* @param expireTime Expiration time expressed in epoch seconds.
* Options: 0 (no exp. default), +[n], [n].
* Optional.
* @param userReference User reference id. 32-bit, signed. Optional.
* @param closeOrderType Closing order type. Optional.
* @param closePrice Closing order price. Optional.
* @param closeSecondaryPrice Closing order secondary price. Optional.
* @param validateOnly Validate only, do not submit order. Optional.
* @param flags Order flags. Options: "viqc", "fcib", "fciq",
* "nompp", "post". Optional.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<OrderReceipt> addStandardOrder(final String pair,
final String type,
final String orderType,
final String price,
final String secondaryPrice,
final String volume,
final String leverage,
final String startTime,
final String expireTime,
final String userReference,
final String closeOrderType,
final String closePrice,
final String closeSecondaryPrice,
final Boolean validateOnly,
final String... flags) {
return getRequestBuilder(
"/0/private/AddOrder",
"post",
"pair", pair,
"type", type,
"ordertype", orderType,
"price", price,
"price2", secondaryPrice,
"volume", volume,
"leverage", leverage,
"oflags", join(flags),
"starttm", startTime,
"expiretm", expireTime,
"userref", userReference,
"validate", asString(validateOnly),
"close[ordertype]", closeOrderType,
"close[price]", closePrice,
"close[price2]", closeSecondaryPrice);
}
/**
* Cancels an open order.
*
* @param id The transaction or user reference id of the order(s) to close.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
public KrakenRequestBuilder<OrderCancelState> cancelOpenOrder(final String id) {
return getRequestBuilder("/0/private/CancelOrder", "post", "txid", id);
}
// Private boilerplate
/**
* Decorates and enqueues a new Kraken request.
*
* @param path The path of the url to request.
* @param method The HTTP method of the request.
* @param data The optional key/value entries to pass along. Even
* positions are treated as keys and odd positions as values.
* Any trailing keys will be ignored.
* @param <V> The type definition of the result Java class.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
private <V> KrakenRequestBuilder<V> getRequestBuilder(final String path,
final String method,
final String... data) {
return getRequestBuilder(null, path, method, data);
}
/**
* Decorates and enqueues a new Kraken request.
*
* @param typeAdapter JSON adapter to parse non-default data structures.
* @param path The path of the url to request.
* @param method The HTTP method of the request.
* @param data The optional key/value entries to pass along. Even
* positions are treated as keys and odd positions as
* values. Any trailing keys will be ignored.
* @param <V> The type definition of the result Java class.
* @return A request builder object to configure any client side cache
* metrics with and to attach any callback implementations to.
*/
private <V> KrakenRequestBuilder<V> getRequestBuilder(final TypeAdapter<V> typeAdapter,
final String path,
final String method,
final String... data) {
return new KrakenRequestBuilder<V>() {
@Override
public Request<V> enqueue() {
return new DefaultRequest<>(() -> {
// Perform coarse API key+secret validation
if (isPrivateRequest(path) && (key == null || secret == null))
throw new IllegalStateException(
"An API key and secret is required for this request");
// Everything's peachy: prepare the Kraken request decoration
String nonce = generateNonce(path);
String message = composeMessage(nonce, data);
List<NetworkClient.Header> headers = generateSignature(path, nonce, message);
// Prepare the HTTP metrics depending on "get" or "post" method.
boolean isGetMethod = "get".equals(method.toLowerCase());
byte[] payload = isGetMethod ? null : asBytes(message);
String mime = isGetMethod ? null : "application/x-www-form-urlencoded";
String uri = isGetMethod ?
String.format("%s%s?%s", baseUrl, path, message) :
String.format("%s%s", baseUrl, path);
// Perform the actual request (the network client stems from
// CachedRequestBuilder (extended by KrakenRequestBuilder).
byte[] responseBytes = okHttpNetworkClient.execute(uri, method, headers, payload, mime);
String responseJson = asString(responseBytes);
// Parse the response JSON
Type type = new TypeToken<KrakenResponse<V>>() {}.getType();
KrakenResponse<V> response = new GsonBuilder()
.registerTypeAdapter(type, new KrakenTypeAdapter<>(typeAdapter))
.create()
.fromJson(responseJson, type);
// Throw exception if has error (to trigger error callbacks)...
if (response.error.length > 0)
throw new KrakenRequestException(response.error);
// ...or deliver result.
return response.result;
});
}
};
}
/**
* Checks whether a given url is targeting a private endpoint in the Kraken
* API.
*
* @param url The url to check.
* @return Boolean true if targeting a private endpoint, false otherwise.
*/
private boolean isPrivateRequest(final String url) {
return url.contains("/private/");
}
/**
* Generates a nonce for private requests, or null for public requests.
*
* @return The nonce or null.
*/
private String generateNonce(final String url) {
return url != null && isPrivateRequest(url) ?
String.format("%-16s", System.currentTimeMillis())
.replace(" ", "0") :
null;
}
/**
* Constructs an encoded request message that Kraken will understand. See
* Kraken API documentation for details.
*
* @param nonce The request nonce. Ignored if null.
* @param data The actual key value pairs to build the message from. Even
* positions are treated as keys and odd positions as values.
* Any null pointer key or value will render the key/value pair
* invalid and hence ignored. Any trailing keys will also be
* ignored.
* @return The prepared and encoded Kraken message.
*/
private String composeMessage(final String nonce, final String... data) {
Uri.Builder builder = new Uri.Builder();
if (nonce != null)
builder.appendQueryParameter("nonce", nonce);
if (data != null && data.length > 1)
for (int i = 0; i < data.length; i += 2)
if (data[i] != null && data[i + 1] != null)
builder.appendQueryParameter(data[i], data[i + 1]);
return builder.build().getEncodedQuery();
}
/**
* Generates the message signature headers. See Kraken API documentation for
* details.
*
* @param path The request path.
* @param nonce The request nonce that was used for the message.
* @param message The request message
* @return The Kraken request signature headers. Null if no path is given or
* an empty list if no nonce is given.
*/
private List<NetworkClient.Header> generateSignature(final String path,
final String nonce,
final String message) {
if (key == null || secret == null)
return null;
if (path == null)
return null;
if (nonce == null)
return null;
byte[] data = sha256(asBytes(nonce + message));
if (data == null)
return null;
byte[] input = concat(asBytes(path), data);
byte[] signature = hmacSha512(input, secret);
if (signature == null)
return null;
List<NetworkClient.Header> headers = new ArrayList<>(2);
headers.add(new NetworkClient.Header("API-Key", key));
headers.add(new NetworkClient.Header("API-Sign", base64Encode(signature)));
return headers;
}
}
| Fix Kraken error response trigger
| library/src/main/java/com/echsylon/kraken/Kraken.java | Fix Kraken error response trigger | <ide><path>ibrary/src/main/java/com/echsylon/kraken/Kraken.java
<ide> .fromJson(responseJson, type);
<ide>
<ide> // Throw exception if has error (to trigger error callbacks)...
<del> if (response.error.length > 0)
<add> if (response.error != null)
<ide> throw new KrakenRequestException(response.error);
<ide>
<ide> // ...or deliver result. |
|
Java | bsd-3-clause | 83b1433c24d564aee9e9ee2d92c3159e6d24746e | 0 | aic-sri-international/aic-expresso,aic-sri-international/aic-expresso | /*
* Copyright (c) 2016, SRI International
* All rights reserved.
* Licensed under the The BSD 3-Clause License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the aic-expresso nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sri.ai.expresso.type;
import static com.sri.ai.expresso.helper.Expressions.apply;
import static com.sri.ai.expresso.helper.Expressions.makeSymbol;
import static com.sri.ai.expresso.helper.Expressions.parse;
import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.CARTESIAN_PRODUCT;
import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.FUNCTION_TYPE;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.annotations.Beta;
import com.sri.ai.expresso.api.Expression;
import com.sri.ai.expresso.api.Type;
import com.sri.ai.expresso.helper.Expressions;
import com.sri.ai.grinder.api.Registry;
import com.sri.ai.grinder.helper.AssignmentsIterator;
import com.sri.ai.grinder.sgdpllt.core.DefaultRegistry;
import com.sri.ai.util.Util;
import com.sri.ai.util.collect.FunctionIterator;
import com.sri.ai.util.math.Rational;
/**
* Represents function types.
*
* @author oreilly
*
*/
@Beta
public class FunctionType implements Type, Serializable {
private static final long serialVersionUID = 1L;
private Type codomain;
private List<Type> argumentTypes;
//
private String cachedString;
// NOTE: Following used for iteration logic
private Registry cachedIterateRegistry;
private List<Expression> codomainVariables;
private String genericLambda;
public FunctionType(Type codomain, Type... argumentTypes) {
this.codomain = codomain;
this.argumentTypes = Collections.unmodifiableList(Arrays.asList(argumentTypes));
}
public Type getCodomain() {
return codomain;
}
public int getArity() {
return getArgumentTypes().size();
}
public List<Type> getArgumentTypes() {
return argumentTypes;
}
@Override
public String getName() {
return toString();
}
@Override
public Iterator<Expression> iterator() {
if (!(getCodomain().isDiscrete() && getArgumentTypes().stream().allMatch(Type::isFinite))) {
throw new Error("Only function types with finite argument types and a discrete codomain can be enumerated.");
}
if (cachedIterateRegistry == null) {
// Pre-compute
cachedIterateRegistry = new DefaultRegistry();
int numCodomainValues = argumentTypes.stream()
.map(Type::cardinality)
.map(Expression::rationalValue)
.reduce(Rational.ONE, Rational::multiply)
.intValue();
Expression codomainTypeExpression = parse(getCodomain().getName());
codomainVariables = new ArrayList<>(numCodomainValues);
Map<Expression, Expression> symbolsAndTypes = new LinkedHashMap<>();
for (int i = 0; i < numCodomainValues; i++) {
Expression coDomainVariableI = makeSymbol("C" + (i + 1));
codomainVariables.add(coDomainVariableI);
cachedIterateRegistry = cachedIterateRegistry.add(getCodomain());
symbolsAndTypes.put(coDomainVariableI, codomainTypeExpression);
}
List<Expression> argVariables = new ArrayList<>();
for (int i = 0; i < getArgumentTypes().size(); i++) {
cachedIterateRegistry = cachedIterateRegistry.add(getArgumentTypes().get(i));
argVariables.add(makeSymbol("A" + (i + 1)));
symbolsAndTypes.put(argVariables.get(i), parse(getArgumentTypes().get(i).getName()));
}
cachedIterateRegistry = cachedIterateRegistry.setSymbolsAndTypes(symbolsAndTypes);
StringJoiner lambdaApplicationPrefix = new StringJoiner(", ", "(lambda ", " : ");
for (Expression argVar : argVariables) {
lambdaApplicationPrefix.add(argVar + " in " + symbolsAndTypes.get(argVar));
}
AssignmentsIterator assignmentsIterator = new AssignmentsIterator(argVariables, cachedIterateRegistry);
StringJoiner lambdaApplicationBody = new StringJoiner(" else ", "", ")");
AtomicInteger counter = new AtomicInteger(0);
assignmentsIterator.forEachRemaining(assignment -> {
if (counter.incrementAndGet() != numCodomainValues) {
StringJoiner condition = new StringJoiner(" and ", "if ", " then C" + counter);
for (int i = 0; i < argVariables.size(); i++) {
Expression argVariable = argVariables.get(i);
condition.add(argVariable + " = " + assignment.get(argVariable));
}
lambdaApplicationBody.add(condition.toString());
}
else {
lambdaApplicationBody.add("C" + numCodomainValues);
}
});
genericLambda = lambdaApplicationPrefix.toString() + lambdaApplicationBody.toString();
}
return FunctionIterator.functionIterator(new AssignmentsIterator(codomainVariables, cachedIterateRegistry), assignment -> {
String lambda = genericLambda;
for (int i = 0; i < codomainVariables.size(); i++) {
Expression codomainVariable = codomainVariables.get(i);
lambda = lambda.replace(codomainVariable.toString(), assignment.get(codomainVariable).toString());
}
return parse(lambda);
});
}
@Override
public boolean contains(Expression uniquelyNamedConstant) {
// Function types do not contain uniquely named constants.
return false;
}
@Override
public Expression sampleUniquelyNamedConstant(Random random) {
throw new Error("Cannot sample uniquely named constant from function type that is infinite and/or defined by variables: " + getName());
}
@Override
public Expression cardinality() {
if (isFinite()) {
Rational cardinality = codomain.cardinality()
.rationalValue()
.pow(argumentTypes.stream()
.map(Type::cardinality)
.map(Expression::rationalValue)
.reduce(Rational.ONE, Rational::multiply).intValue()
);
return makeSymbol(cardinality);
}
return Expressions.INFINITY;
}
@Override
public boolean isDiscrete() {
return codomain.isDiscrete() && argumentTypes.stream().allMatch(Type::isDiscrete);
}
@Override
public boolean isFinite() {
return codomain.isFinite() && argumentTypes.stream().allMatch(Type::isFinite);
}
@Override
public String toString() {
if (cachedString == null) {
if (getArgumentTypes().size() == 0) {
cachedString = apply(FUNCTION_TYPE, getCodomain()).toString();
} else {
cachedString = apply(FUNCTION_TYPE, apply(CARTESIAN_PRODUCT, getArgumentTypes()), getCodomain())
.toString();
}
}
return cachedString;
}
/**
* Make a function type expression.
*
* @param codomainType
* the codomain type of the function type.
* @param argumentTypes
* 0 or more argument types to the function type.
* @return a function type expression.
*/
public static Expression make(Expression codomainType, Expression... argumentTypes) {
Expression result = make(codomainType, Arrays.asList(argumentTypes));
return result;
}
/**
* Make a function type expression.
*
* @param codomainType
* the codomain type of the function type.
* @param argumentTypes
* 0 or more argument types to the function type.
* @return a function type expression.
*/
public static Expression make(Expression codomainType, List<Expression> argumentTypes) {
Expression result;
if (argumentTypes.size() == 0) {
result = apply(FUNCTION_TYPE, codomainType);
} else {
result = apply(FUNCTION_TYPE, apply(CARTESIAN_PRODUCT, argumentTypes), codomainType);
}
return result;
}
/**
* Get the codomain type expression from the function type.
*
* @param functionTypeExpression
* the function type expression whose codomain is to be
* retrieved.
*
* @return the codomain type expression for the given function type
* expression.
*/
public static Expression getCodomain(Expression functionTypeExpression) {
assertFunctionType(functionTypeExpression);
Expression result;
if (functionTypeExpression.numberOfArguments() == 1) {
result = functionTypeExpression.get(0);
} else {
result = functionTypeExpression.get(1);
}
return result;
}
/**
* Get the given function type expression's argument type expression list.
*
* @param functionTypeExpression
* the function type expression list whose argument type
* expressions are to be retrieved.
* @return the argument type expressions of the given function type
* expression.
*/
public static List<Expression> getArgumentList(Expression functionTypeExpression) {
assertFunctionType(functionTypeExpression);
List<Expression> result = new ArrayList<>();
// If arity is 2 then we have argument types defined
if (functionTypeExpression.numberOfArguments() == 2) {
result.addAll(functionTypeExpression.get(0).getArguments());
}
return result;
}
/**
* Determine if a given expression is a function type expression.
*
* @param expression
* the expresison to be tested.
* @return true if the given expression is a function type, false otherwise.
*/
public static boolean isFunctionType(Expression expression) {
boolean result = false;
if (expression.hasFunctor(FUNCTION_TYPE)) {
// A Nullary function, with a codomain defined
if (expression.numberOfArguments() == 1) {
result = true;
} else if (expression.numberOfArguments() == 2) {
Expression cartesianProductFunctionApplication = expression.get(0);
if (cartesianProductFunctionApplication.hasFunctor(CARTESIAN_PRODUCT)) {
result = true;
}
}
}
return result;
}
/**
* Assert that the give expression represents a function type application.
*
* @param expression
* the expression to be tested.
*/
public static void assertFunctionType(Expression expression) {
Util.myAssert(expression.hasFunctor(FUNCTION_TYPE), () -> "Functor in expression " + expression
+ " should be a functional type (that is, have functor '->')");
Util.myAssert(expression.numberOfArguments() == 1 || expression.numberOfArguments() == 2,
() -> "Function type has illegal number of arguments (should be 1 or 2), has "
+ expression.numberOfArguments() + " for " + expression);
if (expression.numberOfArguments() == 2) {
// First argument must be a cartesian product function application,
// which describes the arguments of the function
Expression cartesianProductFunctionApplication = expression.get(0);
Util.myAssert(cartesianProductFunctionApplication.hasFunctor(CARTESIAN_PRODUCT),
() -> "First argument of two must be a cartesian product function application, given instead " + expression);
}
}
// NOTE: Only to be used under testing conditions.
protected void updateTestArgumentTypes(List<Type> updatedArgumentTypes) {
if (updatedArgumentTypes.size() != getArity()) {
throw new IllegalArgumentException("Update arguments #= " + updatedArgumentTypes.size()
+ " does not match function types arity of " + getArity());
}
this.argumentTypes = Collections.unmodifiableList(new ArrayList<>(updatedArgumentTypes));
this.cachedString = null; // re-calculate just in case.
}
} | src/main/java/com/sri/ai/expresso/type/FunctionType.java | /*
* Copyright (c) 2016, SRI International
* All rights reserved.
* Licensed under the The BSD 3-Clause License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the aic-expresso nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sri.ai.expresso.type;
import static com.sri.ai.expresso.helper.Expressions.apply;
import static com.sri.ai.expresso.helper.Expressions.makeSymbol;
import static com.sri.ai.expresso.helper.Expressions.parse;
import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.CARTESIAN_PRODUCT;
import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.FUNCTION_TYPE;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.annotations.Beta;
import com.sri.ai.expresso.api.Expression;
import com.sri.ai.expresso.api.Type;
import com.sri.ai.expresso.helper.Expressions;
import com.sri.ai.grinder.api.Registry;
import com.sri.ai.grinder.helper.AssignmentsIterator;
import com.sri.ai.grinder.sgdpllt.core.DefaultRegistry;
import com.sri.ai.util.Util;
import com.sri.ai.util.collect.FunctionIterator;
import com.sri.ai.util.math.Rational;
/**
* Represents function types.
*
* @author oreilly
*
*/
@Beta
public class FunctionType implements Type, Serializable {
private static final long serialVersionUID = 1L;
private Type codomain;
private List<Type> argumentTypes;
//
private String cachedString;
// NOTE: Following used for iteration logic
private Registry cachedIterateRegistry;
private List<Expression> codomainVariables;
private String genericLambda;
public FunctionType(Type codomain, Type... argumentTypes) {
this.codomain = codomain;
this.argumentTypes = Collections.unmodifiableList(Arrays.asList(argumentTypes));
}
public Type getCodomain() {
return codomain;
}
public int getArity() {
return getArgumentTypes().size();
}
public List<Type> getArgumentTypes() {
return argumentTypes;
}
@Override
public String getName() {
return toString();
}
@Override
public Iterator<Expression> iterator() {
if (!(getCodomain().isDiscrete() && getArgumentTypes().stream().allMatch(Type::isFinite))) {
throw new Error("Only function types with finite argument types and a discrete codomain can be enumerated.");
}
if (cachedIterateRegistry == null) {
// Pre-compute
cachedIterateRegistry = new DefaultRegistry();
int numCodomainValues = argumentTypes.stream()
.map(Type::cardinality)
.map(Expression::rationalValue)
.reduce(Rational.ONE, Rational::multiply)
.intValue();
Expression codomainTypeExpression = parse(getCodomain().getName());
codomainVariables = new ArrayList<>(numCodomainValues);
Map<Expression, Expression> symbolsAndTypes = new LinkedHashMap<>();
for (int i = 0; i < numCodomainValues; i++) {
Expression coDomainVariableI = makeSymbol("C"+(i+1));
codomainVariables.add(coDomainVariableI);
cachedIterateRegistry = cachedIterateRegistry.add(getCodomain());
symbolsAndTypes.put(coDomainVariableI, codomainTypeExpression);
}
List<Expression> argVariables = new ArrayList<>();
for (int i = 0; i < getArgumentTypes().size(); i++) {
cachedIterateRegistry = cachedIterateRegistry.add(getArgumentTypes().get(i));
argVariables.add(makeSymbol("A"+(i+1)));
symbolsAndTypes.put(argVariables.get(i), parse(getArgumentTypes().get(i).getName()));
}
cachedIterateRegistry = cachedIterateRegistry.setSymbolsAndTypes(symbolsAndTypes);
StringJoiner lambdaApplicationPrefix = new StringJoiner(", ", "(lambda ", " : ");
for (Expression argVar : argVariables) {
lambdaApplicationPrefix.add(argVar + " in " + symbolsAndTypes.get(argVar));
}
AssignmentsIterator assignmentsIterator = new AssignmentsIterator(argVariables, cachedIterateRegistry);
StringJoiner lambdaApplicationBody = new StringJoiner(" else ", "", ")");
AtomicInteger cnt = new AtomicInteger(0);
assignmentsIterator.forEachRemaining(assignment -> {
if (cnt.incrementAndGet() != numCodomainValues) {
StringJoiner condition = new StringJoiner(" and ", "if ", " then C"+cnt);
for (int i = 0; i < argVariables.size(); i++) {
Expression argVariable = argVariables.get(i);
condition.add(argVariable+" = "+assignment.get(argVariable));
}
lambdaApplicationBody.add(condition.toString());
}
else {
lambdaApplicationBody.add("C"+numCodomainValues);
}
});
genericLambda = lambdaApplicationPrefix.toString() + lambdaApplicationBody.toString();
}
return FunctionIterator.functionIterator(new AssignmentsIterator(codomainVariables, cachedIterateRegistry), assignment -> {
String lambda = genericLambda;
for (int i = 0; i < codomainVariables.size(); i++) {
Expression codomainVariable = codomainVariables.get(i);
lambda = lambda.replace(codomainVariable.toString(), assignment.get(codomainVariable).toString());
}
return parse(lambda);
});
}
@Override
public boolean contains(Expression uniquelyNamedConstant) {
// Function types do not contain uniquely named constants.
return false;
}
@Override
public Expression sampleUniquelyNamedConstant(Random random) {
throw new Error("Cannot sample uniquely named constant from function type that is infinite and/or defined by variables: " + getName());
}
@Override
public Expression cardinality() {
if (isFinite()) {
Rational cardinality = codomain.cardinality()
.rationalValue()
.pow(argumentTypes.stream()
.map(Type::cardinality)
.map(Expression::rationalValue)
.reduce(Rational.ONE, Rational::multiply).intValue()
);
return makeSymbol(cardinality);
}
return Expressions.INFINITY;
}
@Override
public boolean isDiscrete() {
return codomain.isDiscrete() && argumentTypes.stream().allMatch(Type::isDiscrete);
}
@Override
public boolean isFinite() {
return codomain.isFinite() && argumentTypes.stream().allMatch(Type::isFinite);
}
@Override
public String toString() {
if (cachedString == null) {
if (getArgumentTypes().size() == 0) {
cachedString = apply(FUNCTION_TYPE, getCodomain()).toString();
} else {
cachedString = apply(FUNCTION_TYPE, apply(CARTESIAN_PRODUCT, getArgumentTypes()), getCodomain())
.toString();
}
}
return cachedString;
}
/**
* Make a function type expression.
*
* @param codomainType
* the codomain type of the function type.
* @param argumentTypes
* 0 or more argument types to the function type.
* @return a function type expression.
*/
public static Expression make(Expression codomainType, Expression... argumentTypes) {
Expression result = make(codomainType, Arrays.asList(argumentTypes));
return result;
}
/**
* Make a function type expression.
*
* @param codomainType
* the codomain type of the function type.
* @param argumentTypes
* 0 or more argument types to the function type.
* @return a function type expression.
*/
public static Expression make(Expression codomainType, List<Expression> argumentTypes) {
Expression result;
if (argumentTypes.size() == 0) {
result = apply(FUNCTION_TYPE, codomainType);
} else {
result = apply(FUNCTION_TYPE, apply(CARTESIAN_PRODUCT, argumentTypes), codomainType);
}
return result;
}
/**
* Get the codomain type expression from the function type.
*
* @param functionTypeExpression
* the function type expression whose codomain is to be
* retrieved.
*
* @return the codomain type expression for the given function type
* expression.
*/
public static Expression getCodomain(Expression functionTypeExpression) {
assertFunctionType(functionTypeExpression);
Expression result;
if (functionTypeExpression.numberOfArguments() == 1) {
result = functionTypeExpression.get(0);
} else {
result = functionTypeExpression.get(1);
}
return result;
}
/**
* Get the given function type expression's argument type expression list.
*
* @param functionTypeExpression
* the function type expression list whose argument type
* expressions are to be retrieved.
* @return the argument type expressions of the given function type
* expression.
*/
public static List<Expression> getArgumentList(Expression functionTypeExpression) {
assertFunctionType(functionTypeExpression);
List<Expression> result = new ArrayList<>();
// If arity is 2 then we have argument types defined
if (functionTypeExpression.numberOfArguments() == 2) {
result.addAll(functionTypeExpression.get(0).getArguments());
}
return result;
}
/**
* Determine if a given expression is a function type expression.
*
* @param expression
* the expresison to be tested.
* @return true if the given expression is a function type, false otherwise.
*/
public static boolean isFunctionType(Expression expression) {
boolean result = false;
if (expression.hasFunctor(FUNCTION_TYPE)) {
// A Nullary function, with a codomain defined
if (expression.numberOfArguments() == 1) {
result = true;
} else if (expression.numberOfArguments() == 2) {
Expression cartesianProductFunctionApplication = expression.get(0);
if (cartesianProductFunctionApplication.hasFunctor(CARTESIAN_PRODUCT)) {
result = true;
}
}
}
return result;
}
/**
* Assert that the give expression represents a function type application.
*
* @param expression
* the expression to be tested.
*/
public static void assertFunctionType(Expression expression) {
Util.myAssert(expression.hasFunctor(FUNCTION_TYPE), () -> "Functor in expression " + expression
+ " should be a functional type (that is, have functor '->')");
Util.myAssert(expression.numberOfArguments() == 1 || expression.numberOfArguments() == 2,
() -> "Function type has illegal number of arguments (should be 1 or 2), has "
+ expression.numberOfArguments() + " for " + expression);
if (expression.numberOfArguments() == 2) {
// First argument must be a cartesian product function application,
// which describes the arguments of the function
Expression cartesianProductFunctionApplication = expression.get(0);
Util.myAssert(cartesianProductFunctionApplication.hasFunctor(CARTESIAN_PRODUCT),
() -> "First argument of two must be a cartesian product function application, given instead " + expression);
}
}
// NOTE: Only to be used under testing conditions.
protected void updateTestArgumentTypes(List<Type> updatedArgumentTypes) {
if (updatedArgumentTypes.size() != getArity()) {
throw new IllegalArgumentException("Update arguments #= " + updatedArgumentTypes.size()
+ " does not match function types arity of " + getArity());
}
this.argumentTypes = Collections.unmodifiableList(new ArrayList<>(updatedArgumentTypes));
this.cachedString = null; // re-calculate just in case.
}
} | - minor changes | src/main/java/com/sri/ai/expresso/type/FunctionType.java | - minor changes | <ide><path>rc/main/java/com/sri/ai/expresso/type/FunctionType.java
<ide> codomainVariables = new ArrayList<>(numCodomainValues);
<ide> Map<Expression, Expression> symbolsAndTypes = new LinkedHashMap<>();
<ide> for (int i = 0; i < numCodomainValues; i++) {
<del> Expression coDomainVariableI = makeSymbol("C"+(i+1));
<add> Expression coDomainVariableI = makeSymbol("C" + (i + 1));
<ide> codomainVariables.add(coDomainVariableI);
<ide> cachedIterateRegistry = cachedIterateRegistry.add(getCodomain());
<ide> symbolsAndTypes.put(coDomainVariableI, codomainTypeExpression);
<ide> List<Expression> argVariables = new ArrayList<>();
<ide> for (int i = 0; i < getArgumentTypes().size(); i++) {
<ide> cachedIterateRegistry = cachedIterateRegistry.add(getArgumentTypes().get(i));
<del> argVariables.add(makeSymbol("A"+(i+1)));
<add> argVariables.add(makeSymbol("A" + (i + 1)));
<ide> symbolsAndTypes.put(argVariables.get(i), parse(getArgumentTypes().get(i).getName()));
<ide> }
<ide> cachedIterateRegistry = cachedIterateRegistry.setSymbolsAndTypes(symbolsAndTypes);
<ide>
<ide> AssignmentsIterator assignmentsIterator = new AssignmentsIterator(argVariables, cachedIterateRegistry);
<ide> StringJoiner lambdaApplicationBody = new StringJoiner(" else ", "", ")");
<del> AtomicInteger cnt = new AtomicInteger(0);
<add> AtomicInteger counter = new AtomicInteger(0);
<ide> assignmentsIterator.forEachRemaining(assignment -> {
<del> if (cnt.incrementAndGet() != numCodomainValues) {
<del> StringJoiner condition = new StringJoiner(" and ", "if ", " then C"+cnt);
<add> if (counter.incrementAndGet() != numCodomainValues) {
<add> StringJoiner condition = new StringJoiner(" and ", "if ", " then C" + counter);
<ide> for (int i = 0; i < argVariables.size(); i++) {
<ide> Expression argVariable = argVariables.get(i);
<del> condition.add(argVariable+" = "+assignment.get(argVariable));
<add> condition.add(argVariable + " = " + assignment.get(argVariable));
<ide> }
<ide> lambdaApplicationBody.add(condition.toString());
<ide> }
<ide> else {
<del> lambdaApplicationBody.add("C"+numCodomainValues);
<add> lambdaApplicationBody.add("C" + numCodomainValues);
<ide> }
<ide> });
<ide> |
|
JavaScript | mit | f3584141bbd5d59cec90250669fb94f2ef6b5048 | 0 | kanso/underscore,kanso/underscore | /*global $: false */
var session = require('kanso/session'),
templates = require('kanso/templates'),
events = require('kanso/events'),
utils = require('./utils');
exports.options = {
include_design: true
};
exports.rewrites = [
{from: '/static/*', to: 'static/*'},
{from: '/', to: '_list/applist/apps'},
{from: '/:app', to: '_show/types'},
{from: '/:app/types/:type/add', to: '_show/addtype', method: 'GET'},
{from: '/:app/types/:type/add', to: '_update/addtype', method: 'POST'},
{from: '/:app/types/:type', to: '_list/typelist/types', query: {
startkey: [':type'],
endkey: [':type', {}],
include_docs: true,
limit: 10
}},
{from: '/:app/view/:id', to: '_show/viewtype/:id', method: 'GET'},
{from: '/:app/edit/:id', to: '_show/edittype/:id', method: 'GET'},
{from: '/:app/edit/:id', to: '_update/updatetype/:id', method: 'POST'},
{from: '/:app/delete/:id', to: '_update/deletetype/:id', method: 'POST'},
{from: '/:app/views/:view', to: '_show/viewlist', query: {
limit: 10
}}
];
exports.views = require('./views');
exports.lists = require('./lists');
exports.shows = require('./shows');
exports.updates = require('./updates');
exports.bindSessionControls = function () {
$('#session .logout a').click(function (ev) {
ev.preventDefault();
session.logout();
return false;
});
$('#session .login a').click(function (ev) {
ev.preventDefault();
var div = $('<div><h2>Login</h2></div>');
div.append('<form id="login_form" action="/_session" method="POST">' +
'<div class="general_errors"></div>' +
'<div class="username field">' +
'<label for="id_name">Username</label>' +
'<input id="id_name" name="name" type="text" />' +
'<div class="errors"></div>' +
'</div>' +
'<div class="password field">' +
'<label for="id_password">Password</label>' +
'<input id="id_password" name="password" type="password" />' +
'<div class="errors"></div>' +
'</div>' +
'<div class="actions">' +
'<input type="submit" id="id_login" value="Login" />' +
'<input type="button" id="id_cancel" value="Cancel" />' +
'</div>' +
'</form>');
$('#id_cancel', div).click(function () {
$.modal.close();
});
$('form', div).submit(function (ev) {
ev.preventDefault();
var username = $('input[name="name"]', div).val();
var password = $('input[name="password"]', div).val();
console.log($('.username .errors', div));
$('.username .errors', div).text(
username ? '': 'Please enter a username'
);
$('.password .errors', div).text(
password ? '': 'Please enter a password'
);
utils.resizeModal(div);
if (username && password) {
session.login(username, password, function (err) {
$('.general_errors', div).text(err ? err.toString(): '');
utils.resizeModal(div);
if (!err) {
$(div).fadeOut('slow', function () {
$.modal.close();
});
}
});
}
return false;
});
div.modal({autoResize: true, overlayClose: true});
return false;
});
$('#session .signup a').click(function (ev) {
ev.preventDefault();
var div = $('<div><h2>Create account</h2></div>');
div.append('<form id="signup_form" action="/_session" method="POST">' +
'<div class="general_errors"></div>' +
'<div class="username field">' +
'<label for="id_name">Username</label>' +
'<input id="id_name" name="name" type="text" />' +
'<div class="errors"></div>' +
'</div>' +
'<div class="password field">' +
'<label for="id_password">Password</label>' +
'<input id="id_password" name="password" type="password" />' +
'<div class="errors"></div>' +
'</div>' +
'<div class="actions">' +
'<input type="submit" id="id_create" value="Create" />' +
'<input type="button" id="id_cancel" value="Cancel" />' +
'</div>' +
'</form>');
$('#id_cancel', div).click(function () {
$.modal.close();
});
$('form', div).submit(function (ev) {
ev.preventDefault();
var username = $('input[name="name"]', div).val();
var password = $('input[name="password"]', div).val();
console.log($('.username .errors', div));
$('.username .errors', div).text(
username ? '': 'Please enter a username'
);
$('.password .errors', div).text(
password ? '': 'Please enter a password'
);
utils.resizeModal(div);
if (username && password) {
session.signup(username, password, function (err) {
$('.general_errors', div).text(err ? err.toString(): '');
utils.resizeModal(div);
if (!err) {
session.login(username, password, function (err) {
$('.general_errors', div).text(err ? err.toString(): '');
utils.resizeModal(div);
$(div).fadeOut('slow', function () {
$.modal.close();
});
});
}
});
}
return false;
});
div.modal({autoResize: true, overlayClose: true});
return false;
});
};
events.on('init', function () {
exports.bindSessionControls();
});
events.on('sessionChange', function (userCtx, req) {
$('#session').replaceWith(templates.render('session.html', req, userCtx));
exports.bindSessionControls();
});
| admin/lib/app.js | /*global $: false */
var session = require('kanso/session'),
templates = require('kanso/templates'),
utils = require('./utils');
exports.options = {
include_design: true
};
exports.rewrites = [
{from: '/static/*', to: 'static/*'},
{from: '/', to: '_list/applist/apps'},
{from: '/:app', to: '_show/types'},
{from: '/:app/types/:type/add', to: '_show/addtype', method: 'GET'},
{from: '/:app/types/:type/add', to: '_update/addtype', method: 'POST'},
{from: '/:app/types/:type', to: '_list/typelist/types', query: {
startkey: [':type'],
endkey: [':type', {}],
include_docs: true,
limit: 10
}},
{from: '/:app/view/:id', to: '_show/viewtype/:id', method: 'GET'},
{from: '/:app/edit/:id', to: '_show/edittype/:id', method: 'GET'},
{from: '/:app/edit/:id', to: '_update/updatetype/:id', method: 'POST'},
{from: '/:app/delete/:id', to: '_update/deletetype/:id', method: 'POST'},
{from: '/:app/views/:view', to: '_show/viewlist', query: {
limit: 10
}}
];
exports.views = require('./views');
exports.lists = require('./lists');
exports.shows = require('./shows');
exports.updates = require('./updates');
exports.bindSessionControls = function () {
$('#session .logout a').click(function (ev) {
ev.preventDefault();
session.logout();
return false;
});
$('#session .login a').click(function (ev) {
ev.preventDefault();
var div = $('<div><h2>Login</h2></div>');
div.append('<form id="login_form" action="/_session" method="POST">' +
'<div class="general_errors"></div>' +
'<div class="username field">' +
'<label for="id_name">Username</label>' +
'<input id="id_name" name="name" type="text" />' +
'<div class="errors"></div>' +
'</div>' +
'<div class="password field">' +
'<label for="id_password">Password</label>' +
'<input id="id_password" name="password" type="password" />' +
'<div class="errors"></div>' +
'</div>' +
'<div class="actions">' +
'<input type="submit" id="id_login" value="Login" />' +
'<input type="button" id="id_cancel" value="Cancel" />' +
'</div>' +
'</form>');
$('#id_cancel', div).click(function () {
$.modal.close();
});
$('form', div).submit(function (ev) {
ev.preventDefault();
var username = $('input[name="name"]', div).val();
var password = $('input[name="password"]', div).val();
console.log($('.username .errors', div));
$('.username .errors', div).text(
username ? '': 'Please enter a username'
);
$('.password .errors', div).text(
password ? '': 'Please enter a password'
);
utils.resizeModal(div);
if (username && password) {
session.login(username, password, function (err) {
$('.general_errors', div).text(err ? err.toString(): '');
utils.resizeModal(div);
if (!err) {
$(div).fadeOut('slow', function () {
$.modal.close();
});
}
});
}
return false;
});
div.modal({autoResize: true, overlayClose: true});
return false;
});
$('#session .signup a').click(function (ev) {
ev.preventDefault();
var div = $('<div><h2>Create account</h2></div>');
div.append('<form id="signup_form" action="/_session" method="POST">' +
'<div class="general_errors"></div>' +
'<div class="username field">' +
'<label for="id_name">Username</label>' +
'<input id="id_name" name="name" type="text" />' +
'<div class="errors"></div>' +
'</div>' +
'<div class="password field">' +
'<label for="id_password">Password</label>' +
'<input id="id_password" name="password" type="password" />' +
'<div class="errors"></div>' +
'</div>' +
'<div class="actions">' +
'<input type="submit" id="id_create" value="Create" />' +
'<input type="button" id="id_cancel" value="Cancel" />' +
'</div>' +
'</form>');
$('#id_cancel', div).click(function () {
$.modal.close();
});
$('form', div).submit(function (ev) {
ev.preventDefault();
var username = $('input[name="name"]', div).val();
var password = $('input[name="password"]', div).val();
console.log($('.username .errors', div));
$('.username .errors', div).text(
username ? '': 'Please enter a username'
);
$('.password .errors', div).text(
password ? '': 'Please enter a password'
);
utils.resizeModal(div);
if (username && password) {
session.signup(username, password, function (err) {
$('.general_errors', div).text(err ? err.toString(): '');
utils.resizeModal(div);
if (!err) {
session.login(username, password, function (err) {
$('.general_errors', div).text(err ? err.toString(): '');
utils.resizeModal(div);
$(div).fadeOut('slow', function () {
$.modal.close();
});
});
}
});
}
return false;
});
div.modal({autoResize: true, overlayClose: true});
return false;
});
};
exports.init = function () {
exports.bindSessionControls();
};
exports.sessionChange = function (userCtx, req) {
$('#session').replaceWith(templates.render('session.html', req, userCtx));
exports.bindSessionControls();
};
| update admin app to use new events api
| admin/lib/app.js | update admin app to use new events api | <ide><path>dmin/lib/app.js
<ide>
<ide> var session = require('kanso/session'),
<ide> templates = require('kanso/templates'),
<add> events = require('kanso/events'),
<ide> utils = require('./utils');
<ide>
<ide>
<ide> });
<ide> };
<ide>
<del>exports.init = function () {
<add>events.on('init', function () {
<ide> exports.bindSessionControls();
<del>};
<add>});
<ide>
<del>exports.sessionChange = function (userCtx, req) {
<add>events.on('sessionChange', function (userCtx, req) {
<ide> $('#session').replaceWith(templates.render('session.html', req, userCtx));
<ide> exports.bindSessionControls();
<del>};
<add>}); |
|
Java | mit | 5e8ca141e8719021c1c806606c897051b59b14bc | 0 | ngageoint/geopackage-core-java | package mil.nga.geopackage.extension.properties;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import mil.nga.geopackage.GeoPackageCore;
/**
* Properties Manager Core using the Properties Extension on a group of cached
* GeoPackages
*
* @author osbornb
*
* @param <T>
* templated GeoPackage object
* @since 3.0.2
*/
public abstract class PropertiesManagerCore<T extends GeoPackageCore> {
/**
* GeoPackage name to properties extension map
*/
private final Map<String, PropertiesCoreExtension<T, ?, ?, ?>> propertiesMap = new HashMap<>();
/**
* Constructor
*/
protected PropertiesManagerCore() {
}
/**
* Constructor
*
* @param geoPackage
* GeoPackage
*/
protected PropertiesManagerCore(T geoPackage) {
add(geoPackage);
}
/**
* Constructor
*
* @param geoPackages
* collection of GeoPackages
*/
protected PropertiesManagerCore(Collection<T> geoPackages) {
add(geoPackages);
}
/**
* Create a properties extension from the GeoPackage
*
* @param geoPackage
* GeoPackage
* @return properties extension
*/
protected abstract PropertiesCoreExtension<T, ?, ?, ?> getPropertiesExtension(
T geoPackage);
/**
* Get the GeoPackage names
*
* @return names
*/
public Set<String> getNames() {
return propertiesMap.keySet();
}
/**
* Get the GeoPackage for the GeoPackage name
*
* @param name
* GeoPackage name
* @return GeoPackage
*/
public T getGeoPackage(String name) {
T geoPackage = null;
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(name);
if (properties != null) {
geoPackage = properties.getGeoPackage();
}
return geoPackage;
}
/**
* Add a collection of GeoPackages
*
* @param geoPackages
* GeoPackages
*/
public void add(Collection<T> geoPackages) {
for (T geoPackage : geoPackages) {
add(geoPackage);
}
}
/**
* Add GeoPackage
*
* @param geoPackage
* GeoPackage
*/
public void add(T geoPackage) {
PropertiesCoreExtension<T, ?, ?, ?> propertiesExtension = getPropertiesExtension(geoPackage);
propertiesMap.put(geoPackage.getName(), propertiesExtension);
}
/**
* Get the number of unique properties
*
* @return property count
*/
public int numProperties() {
return getProperties().size();
}
/**
* Get the unique properties
*
* @return set of properties
*/
public Set<String> getProperties() {
Set<String> allProperties = new HashSet<>();
for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
.values()) {
if (properties.has()) {
allProperties.addAll(properties.getProperties());
}
}
return allProperties;
}
/**
* Get the GeoPackages with the property name
*
* @param property
* property name
* @return GeoPackages
*/
public List<T> hasProperty(String property) {
List<T> geoPackages = new ArrayList<>();
for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
.values()) {
if (properties.has() && properties.hasProperty(property)) {
geoPackages.add(properties.getGeoPackage());
}
}
return geoPackages;
}
/**
* Get the GeoPackages missing the property name
*
* @param property
* property name
* @return GeoPackages
*/
public List<T> missingProperty(String property) {
List<T> geoPackages = new ArrayList<>();
for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
.values()) {
if (!properties.has() || !properties.hasProperty(property)) {
geoPackages.add(properties.getGeoPackage());
}
}
return geoPackages;
}
/**
* Get the number of unique values for the property
*
* @param property
* property name
* @return number of values
*/
public int numValues(String property) {
return getValues(property).size();
}
/**
* Check if the property has any values
*
* @param property
* property name
* @return true if has any values
*/
public boolean hasValues(String property) {
return numValues(property) > 0;
}
/**
* Get the unique values for the property
*
* @param property
* property name
* @return set of values
*/
public Set<String> getValues(String property) {
Set<String> allValues = new HashSet<>();
for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
.values()) {
if (properties.has()) {
allValues.addAll(properties.getValues(property));
}
}
return allValues;
}
/**
* Get the GeoPackages with the property name and value
*
* @param property
* property name
* @param value
* property value
* @return GeoPackages
*/
public List<T> hasValue(String property, String value) {
List<T> geoPackages = new ArrayList<>();
for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
.values()) {
if (properties.has() && properties.hasValue(property, value)) {
geoPackages.add(properties.getGeoPackage());
}
}
return geoPackages;
}
/**
* Get the GeoPackages missing the property name and value
*
* @param property
* property name
* @param value
* property value
* @return GeoPackages
*/
public List<T> missingValue(String property, String value) {
List<T> geoPackages = new ArrayList<>();
for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
.values()) {
if (!properties.has() || !properties.hasValue(property, value)) {
geoPackages.add(properties.getGeoPackage());
}
}
return geoPackages;
}
/**
* Add a property value to all GeoPackages
*
* @param property
* property name
* @param value
* value
* @return number of GeoPackages added to
*/
public int addValue(String property, String value) {
int count = 0;
for (String geoPackage : propertiesMap.keySet()) {
if (addValue(geoPackage, property, value)) {
count++;
}
}
return count;
}
/**
* Add a property value to a specified GeoPackage
*
* @param geoPackage
* GeoPackage name
* @param property
* property name
* @param value
* value
* @return true if added
*/
public boolean addValue(String geoPackage, String property, String value) {
boolean added = false;
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(geoPackage);
if (properties != null) {
properties.getOrCreate();
added = properties.addValue(property, value);
}
return added;
}
/**
* Delete the property and values from all GeoPackages
*
* @param property
* property name
* @return number of GeoPackages deleted from
*/
public int deleteProperty(String property) {
int count = 0;
for (String geoPackage : propertiesMap.keySet()) {
if (deleteProperty(geoPackage, property)) {
count++;
}
}
return count;
}
/**
* Delete the property and values from a specified GeoPackage
*
* @param geoPackage
* GeoPackage name
* @param property
* property name
* @return true if deleted
*/
public boolean deleteProperty(String geoPackage, String property) {
boolean deleted = false;
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(geoPackage);
if (properties != null && properties.has()) {
deleted = properties.deleteProperty(property) > 0;
}
return deleted;
}
/**
* Delete the property value from all GeoPackages
*
* @param property
* property name
* @param value
* property value
* @return number of GeoPackages deleted from
*/
public int deleteValue(String property, String value) {
int count = 0;
for (String geoPackage : propertiesMap.keySet()) {
if (deleteValue(geoPackage, property, value)) {
count++;
}
}
return count;
}
/**
* Delete the property value from a specified GeoPackage
*
* @param geoPackage
* GeoPackage name
* @param property
* property name
* @param value
* property value
* @return true if deleted
*/
public boolean deleteValue(String geoPackage, String property, String value) {
boolean deleted = false;
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(geoPackage);
if (properties != null && properties.has()) {
deleted = properties.deleteValue(property, value) > 0;
}
return deleted;
}
/**
* Delete all properties and values from all GeoPackages
*
* @return number of GeoPackages deleted from
*/
public int deleteAll() {
int count = 0;
for (String geoPackage : propertiesMap.keySet()) {
if (deleteAll(geoPackage)) {
count++;
}
}
return count;
}
/**
* Delete all properties and values from a specified GeoPackage
*
* @param geoPackage
* GeoPackage name
* @return true if any deleted
*/
public boolean deleteAll(String geoPackage) {
boolean deleted = false;
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(geoPackage);
if (properties != null && properties.has()) {
deleted = properties.deleteAll() > 0;
}
return deleted;
}
/**
* Remove the extension from all GeoPackages
*/
public void removeExtension() {
for (String geoPackage : propertiesMap.keySet()) {
removeExtension(geoPackage);
}
}
/**
* Remove the extension from a specified GeoPackage
*
* @param geoPackage
* GeoPackage name
*/
public void removeExtension(String geoPackage) {
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(geoPackage);
if (properties != null) {
properties.removeExtension();
}
}
}
| src/main/java/mil/nga/geopackage/extension/properties/PropertiesManagerCore.java | package mil.nga.geopackage.extension.properties;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import mil.nga.geopackage.GeoPackageCore;
/**
* Properties Manager Core using the Properties Extension on a group of cached
* GeoPackages
*
* @author osbornb
*
* @param <T>
* templated GeoPackage object
* @since 3.0.2
*/
public abstract class PropertiesManagerCore<T extends GeoPackageCore> {
/**
* GeoPackage name to properties extension map
*/
private final Map<String, PropertiesCoreExtension<T, ?, ?, ?>> propertiesMap = new HashMap<>();
/**
* Constructor
*/
protected PropertiesManagerCore() {
}
/**
* Constructor
*
* @param geoPackage
* GeoPackage
*/
protected PropertiesManagerCore(T geoPackage) {
add(geoPackage);
}
/**
* Constructor
*
* @param geoPackages
* collection of GeoPackages
*/
protected PropertiesManagerCore(Collection<T> geoPackages) {
add(geoPackages);
}
/**
* Create a properties extension from the GeoPackage
*
* @param geoPackage
* GeoPackage
* @return properties extension
*/
protected abstract PropertiesCoreExtension<T, ?, ?, ?> getPropertiesExtension(
T geoPackage);
/**
* Get the GeoPackage names
*
* @return names
*/
public Set<String> getNames() {
return propertiesMap.keySet();
}
/**
* Get the GeoPackage for the GeoPackage name
*
* @param name
* GeoPackage name
* @return GeoPackage
*/
public T getGeoPackage(String name) {
T geoPackage = null;
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(name);
if (properties != null) {
geoPackage = properties.getGeoPackage();
}
return geoPackage;
}
/**
* Add a collection of GeoPackages
*
* @param geoPackages
* GeoPackages
*/
public void add(Collection<T> geoPackages) {
for (T geoPackage : geoPackages) {
add(geoPackage);
}
}
/**
* Add GeoPackage
*
* @param geoPackage
* GeoPackage
*/
public void add(T geoPackage) {
PropertiesCoreExtension<T, ?, ?, ?> propertiesExtension = getPropertiesExtension(geoPackage);
propertiesMap.put(geoPackage.getName(), propertiesExtension);
}
/**
* Get the number of unique properties
*
* @return property count
*/
public int numProperties() {
return getProperties().size();
}
/**
* Get the unique properties
*
* @return set of properties
*/
public Set<String> getProperties() {
Set<String> allProperties = new HashSet<>();
for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
.values()) {
if (properties.has()) {
allProperties.addAll(properties.getProperties());
}
}
return allProperties;
}
/**
* Get the GeoPackages with the property name
*
* @param property
* property name
* @return GeoPackages
*/
public List<T> hasProperty(String property) {
List<T> geoPackages = new ArrayList<>();
for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
.values()) {
if (properties.has() && properties.hasProperty(property)) {
geoPackages.add(properties.getGeoPackage());
}
}
return geoPackages;
}
/**
* Get the number of unique values for the property
*
* @param property
* property name
* @return number of values
*/
public int numValues(String property) {
return getValues(property).size();
}
/**
* Check if the property has any values
*
* @param property
* property name
* @return true if has any values
*/
public boolean hasValues(String property) {
return numValues(property) > 0;
}
/**
* Get the unique values for the property
*
* @param property
* property name
* @return set of values
*/
public Set<String> getValues(String property) {
Set<String> allValues = new HashSet<>();
for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
.values()) {
if (properties.has()) {
allValues.addAll(properties.getValues(property));
}
}
return allValues;
}
/**
* Get the GeoPackages with the property name and value
*
* @param property
* property name
* @param value
* property value
* @return GeoPackages
*/
public List<T> hasValue(String property, String value) {
List<T> geoPackages = new ArrayList<>();
for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
.values()) {
if (properties.has() && properties.hasValue(property, value)) {
geoPackages.add(properties.getGeoPackage());
}
}
return geoPackages;
}
/**
* Add a property value to all GeoPackages
*
* @param property
* property name
* @param value
* value
* @return number of GeoPackages added to
*/
public int addValue(String property, String value) {
int count = 0;
for (String geoPackage : propertiesMap.keySet()) {
if (addValue(geoPackage, property, value)) {
count++;
}
}
return count;
}
/**
* Add a property value to a specified GeoPackage
*
* @param geoPackage
* GeoPackage name
* @param property
* property name
* @param value
* value
* @return true if added
*/
public boolean addValue(String geoPackage, String property, String value) {
boolean added = false;
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(geoPackage);
if (properties != null) {
properties.getOrCreate();
added = properties.addValue(property, value);
}
return added;
}
/**
* Delete the property and values from all GeoPackages
*
* @param property
* property name
* @return number of GeoPackages deleted from
*/
public int deleteProperty(String property) {
int count = 0;
for (String geoPackage : propertiesMap.keySet()) {
if (deleteProperty(geoPackage, property)) {
count++;
}
}
return count;
}
/**
* Delete the property and values from a specified GeoPackage
*
* @param geoPackage
* GeoPackage name
* @param property
* property name
* @return true if deleted
*/
public boolean deleteProperty(String geoPackage, String property) {
boolean deleted = false;
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(geoPackage);
if (properties != null && properties.has()) {
deleted = properties.deleteProperty(property) > 0;
}
return deleted;
}
/**
* Delete the property value from all GeoPackages
*
* @param property
* property name
* @param value
* property value
* @return number of GeoPackages deleted from
*/
public int deleteValue(String property, String value) {
int count = 0;
for (String geoPackage : propertiesMap.keySet()) {
if (deleteValue(geoPackage, property, value)) {
count++;
}
}
return count;
}
/**
* Delete the property value from a specified GeoPackage
*
* @param geoPackage
* GeoPackage name
* @param property
* property name
* @param value
* property value
* @return true if deleted
*/
public boolean deleteValue(String geoPackage, String property, String value) {
boolean deleted = false;
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(geoPackage);
if (properties != null && properties.has()) {
deleted = properties.deleteValue(property, value) > 0;
}
return deleted;
}
/**
* Delete all properties and values from all GeoPackages
*
* @return number of GeoPackages deleted from
*/
public int deleteAll() {
int count = 0;
for (String geoPackage : propertiesMap.keySet()) {
if (deleteAll(geoPackage)) {
count++;
}
}
return count;
}
/**
* Delete all properties and values from a specified GeoPackage
*
* @param geoPackage
* GeoPackage name
* @return true if any deleted
*/
public boolean deleteAll(String geoPackage) {
boolean deleted = false;
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(geoPackage);
if (properties != null && properties.has()) {
deleted = properties.deleteAll() > 0;
}
return deleted;
}
/**
* Remove the extension from all GeoPackages
*/
public void removeExtension() {
for (String geoPackage : propertiesMap.keySet()) {
removeExtension(geoPackage);
}
}
/**
* Remove the extension from a specified GeoPackage
*
* @param geoPackage
* GeoPackage name
*/
public void removeExtension(String geoPackage) {
PropertiesCoreExtension<T, ?, ?, ?> properties = propertiesMap
.get(geoPackage);
if (properties != null) {
properties.removeExtension();
}
}
}
| GeoPackage retrieval from missing property and missing value
| src/main/java/mil/nga/geopackage/extension/properties/PropertiesManagerCore.java | GeoPackage retrieval from missing property and missing value | <ide><path>rc/main/java/mil/nga/geopackage/extension/properties/PropertiesManagerCore.java
<ide> }
<ide>
<ide> /**
<add> * Get the GeoPackages missing the property name
<add> *
<add> * @param property
<add> * property name
<add> * @return GeoPackages
<add> */
<add> public List<T> missingProperty(String property) {
<add> List<T> geoPackages = new ArrayList<>();
<add> for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
<add> .values()) {
<add> if (!properties.has() || !properties.hasProperty(property)) {
<add> geoPackages.add(properties.getGeoPackage());
<add> }
<add> }
<add> return geoPackages;
<add> }
<add>
<add> /**
<ide> * Get the number of unique values for the property
<ide> *
<ide> * @param property
<ide> for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
<ide> .values()) {
<ide> if (properties.has() && properties.hasValue(property, value)) {
<add> geoPackages.add(properties.getGeoPackage());
<add> }
<add> }
<add> return geoPackages;
<add> }
<add>
<add> /**
<add> * Get the GeoPackages missing the property name and value
<add> *
<add> * @param property
<add> * property name
<add> * @param value
<add> * property value
<add> * @return GeoPackages
<add> */
<add> public List<T> missingValue(String property, String value) {
<add> List<T> geoPackages = new ArrayList<>();
<add> for (PropertiesCoreExtension<T, ?, ?, ?> properties : propertiesMap
<add> .values()) {
<add> if (!properties.has() || !properties.hasValue(property, value)) {
<ide> geoPackages.add(properties.getGeoPackage());
<ide> }
<ide> } |
|
Java | apache-2.0 | 3648f80acea2e7d29bb808402ac816b788ec383b | 0 | jorgebay/tinkerpop,apache/incubator-tinkerpop,pluradj/incubator-tinkerpop,apache/incubator-tinkerpop,jorgebay/tinkerpop,pluradj/incubator-tinkerpop,krlohnes/tinkerpop,robertdale/tinkerpop,robertdale/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,jorgebay/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,artem-aliev/tinkerpop,pluradj/incubator-tinkerpop,artem-aliev/tinkerpop,apache/incubator-tinkerpop,robertdale/tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,artem-aliev/tinkerpop,robertdale/tinkerpop,robertdale/tinkerpop,jorgebay/tinkerpop,apache/tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.python.jsr223;
import org.apache.commons.configuration.ConfigurationConverter;
import org.apache.tinkerpop.gremlin.process.traversal.Bytecode;
import org.apache.tinkerpop.gremlin.process.traversal.Operator;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.SackFunctions;
import org.apache.tinkerpop.gremlin.process.traversal.Translator;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalOptionParent;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.TraversalStrategyProxy;
import org.apache.tinkerpop.gremlin.process.traversal.util.ConnectiveP;
import org.apache.tinkerpop.gremlin.process.traversal.util.OrP;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.util.function.Lambda;
import org.apache.tinkerpop.gremlin.util.iterator.ArrayIterator;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class PythonTranslator implements Translator.ScriptTranslator {
private static final boolean IS_TESTING = Boolean.valueOf(System.getProperty("is.testing", "false"));
private static final Set<String> STEP_NAMES = Stream.of(GraphTraversal.class.getMethods()).filter(method -> Traversal.class.isAssignableFrom(method.getReturnType())).map(Method::getName).collect(Collectors.toSet());
private static final Set<String> NO_STATIC = Stream.of(T.values(), Operator.values())
.flatMap(arg -> IteratorUtils.stream(new ArrayIterator<>(arg)))
.map(arg -> ((Enum) arg).name())
.collect(Collectors.toCollection(() -> new HashSet<>(Collections.singleton("not"))));
private final String traversalSource;
private final boolean importStatics;
PythonTranslator(final String traversalSource, final boolean importStatics) {
this.traversalSource = traversalSource;
this.importStatics = importStatics;
}
public static PythonTranslator of(final String traversalSource, final boolean importStatics) {
return new PythonTranslator(traversalSource, importStatics);
}
public static PythonTranslator of(final String traversalSource) {
return new PythonTranslator(traversalSource, false);
}
@Override
public String getTraversalSource() {
return this.traversalSource;
}
@Override
public String translate(final Bytecode bytecode) {
return this.internalTranslate(this.traversalSource, bytecode);
}
@Override
public String getTargetLanguage() {
return "gremlin-python";
}
@Override
public String toString() {
return StringFactory.translatorString(this);
}
///////
private String internalTranslate(final String start, final Bytecode bytecode) {
final StringBuilder traversalScript = new StringBuilder(start);
for (final Bytecode.Instruction instruction : bytecode.getInstructions()) {
final String methodName = instruction.getOperator();
final Object[] arguments = instruction.getArguments();
if (IS_TESTING &&
instruction.getOperator().equals(TraversalSource.Symbols.withStrategies) &&
instruction.getArguments()[0].toString().contains("TranslationStrategy"))
continue;
else if (0 == arguments.length)
traversalScript.append(".").append(SymbolHelper.toPython(methodName)).append("()");
else if (methodName.equals("range") && 2 == arguments.length)
traversalScript.append("[").append(arguments[0]).append(":").append(arguments[1]).append("]");
else if (methodName.equals("limit") && 1 == arguments.length)
traversalScript.append("[0:").append(arguments[0]).append("]");
else if (methodName.equals("values") && 1 == arguments.length && traversalScript.length() > 3 && !STEP_NAMES.contains(arguments[0].toString()))
traversalScript.append(".").append(arguments[0]);
else {
traversalScript.append(".");
String temp = SymbolHelper.toPython(methodName) + "(";
for (final Object object : arguments) {
temp = temp + convertToString(object) + ",";
}
traversalScript.append(temp.substring(0, temp.length() - 1)).append(")");
}
// clip off __.
if (this.importStatics && traversalScript.substring(0, 3).startsWith("__.")
&& !NO_STATIC.stream().filter(name -> traversalScript.substring(3).startsWith(SymbolHelper.toPython(name))).findAny().isPresent()) {
traversalScript.delete(0, 3);
}
}
return traversalScript.toString();
}
private String convertToString(final Object object) {
if (object instanceof Bytecode.Binding)
return ((Bytecode.Binding) object).variable();
else if (object instanceof Bytecode)
return this.internalTranslate("__", (Bytecode) object);
else if (object instanceof Traversal)
return convertToString(((Traversal) object).asAdmin().getBytecode());
else if (object instanceof String)
return ((String) object).contains("\"") ? "\"\"\"" + object + "\"\"\"" : "\"" + object + "\"";
else if (object instanceof Set) {
final Set<String> set = new LinkedHashSet<>(((Set) object).size());
for (final Object item : (Set) object) {
set.add(convertToString(item));
}
return "set(" + set.toString() + ")";
} else if (object instanceof List) {
final List<String> list = new ArrayList<>(((List) object).size());
for (final Object item : (List) object) {
list.add(convertToString(item));
}
return list.toString();
} else if (object instanceof Map) {
final StringBuilder map = new StringBuilder("{");
for (final Map.Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
map.append(convertToString(entry.getKey())).
append(":").
append(convertToString(entry.getValue())).
append(",");
}
return map.length() > 1 ? map.substring(0, map.length() - 1) + "}" : map.append("}").toString();
} else if (object instanceof Long)
return object + "L";
else if (object instanceof TraversalStrategyProxy) {
final TraversalStrategyProxy proxy = (TraversalStrategyProxy) object;
if (proxy.getConfiguration().isEmpty())
return "TraversalStrategy(\"" + proxy.getStrategyClass().getSimpleName() + "\")";
else
return "TraversalStrategy(\"" + proxy.getStrategyClass().getSimpleName() + "\"," + convertToString(ConfigurationConverter.getMap(proxy.getConfiguration())) + ")";
} else if (object instanceof TraversalStrategy) {
return convertToString(new TraversalStrategyProxy((TraversalStrategy) object));
} else if (object instanceof Boolean)
return object.equals(Boolean.TRUE) ? "True" : "False";
else if (object instanceof Class)
return ((Class) object).getCanonicalName();
else if (object instanceof VertexProperty.Cardinality)
return "Cardinality." + SymbolHelper.toPython(object.toString());
else if (object instanceof SackFunctions.Barrier)
return "Barrier." + SymbolHelper.toPython(object.toString());
else if (object instanceof TraversalOptionParent.Pick)
return "Pick." + SymbolHelper.toPython(object.toString());
else if (object instanceof Enum)
return convertStatic(((Enum) object).getDeclaringClass().getSimpleName() + ".") + SymbolHelper.toPython(object.toString());
else if (object instanceof P)
return convertPToString((P) object, new StringBuilder()).toString();
else if (object instanceof Element) {
if (object instanceof Vertex) {
final Vertex vertex = (Vertex) object;
return "Vertex(" + convertToString(vertex.id()) + "," + convertToString(vertex.label()) + ")";
} else if (object instanceof Edge) {
final Edge edge = (Edge) object;
return "Edge(" + convertToString(edge.id()) + "," +
convertToString(edge.outVertex()) + "," +
convertToString(edge.label()) + "," +
convertToString(edge.inVertex()) + ")";
} else { // VertexProperty
final VertexProperty vertexProperty = (VertexProperty) object;
return "VertexProperty(" + convertToString(vertexProperty.id()) + "," +
convertToString(vertexProperty.label()) + "," +
convertToString(vertexProperty.value()) + ")";
}
} else if (object instanceof Lambda)
return convertLambdaToString((Lambda) object);
else
return null == object ? "None" : object.toString();
}
private String convertStatic(final String name) {
return this.importStatics ? "" : name;
}
private StringBuilder convertPToString(final P p, final StringBuilder current) {
if (p instanceof ConnectiveP) {
final List<P<?>> list = ((ConnectiveP) p).getPredicates();
for (int i = 0; i < list.size(); i++) {
convertPToString(list.get(i), current);
if (i < list.size() - 1)
current.append(p instanceof OrP ? ".or_(" : ".and_(");
}
current.append(")");
} else
current.append(convertStatic("P.")).append(p.getBiPredicate().toString()).append("(").append(convertToString(p.getValue())).append(")");
return current;
}
protected String convertLambdaToString(final Lambda lambda) {
final String lambdaString = lambda.getLambdaScript().trim();
return lambdaString.startsWith("lambda") ? lambdaString : "lambda " + lambdaString;
}
}
| gremlin-python/src/main/java/org/apache/tinkerpop/gremlin/python/jsr223/PythonTranslator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.python.jsr223;
import org.apache.commons.configuration.ConfigurationConverter;
import org.apache.tinkerpop.gremlin.process.traversal.Bytecode;
import org.apache.tinkerpop.gremlin.process.traversal.Operator;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.SackFunctions;
import org.apache.tinkerpop.gremlin.process.traversal.Translator;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalOptionParent;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.TraversalStrategyProxy;
import org.apache.tinkerpop.gremlin.process.traversal.util.ConnectiveP;
import org.apache.tinkerpop.gremlin.process.traversal.util.OrP;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.util.function.Lambda;
import org.apache.tinkerpop.gremlin.util.iterator.ArrayIterator;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class PythonTranslator implements Translator.ScriptTranslator {
private static final boolean IS_TESTING = Boolean.valueOf(System.getProperty("is.testing", "false"));
private static final Set<String> STEP_NAMES = Stream.of(GraphTraversal.class.getMethods()).filter(method -> Traversal.class.isAssignableFrom(method.getReturnType())).map(Method::getName).collect(Collectors.toSet());
private static final Set<String> NO_STATIC = Stream.of(T.values(), Operator.values())
.flatMap(arg -> IteratorUtils.stream(new ArrayIterator<>(arg)))
.map(arg -> ((Enum) arg).name())
.collect(Collectors.toCollection(() -> new HashSet<>(Collections.singleton("not"))));
private final String traversalSource;
private final boolean importStatics;
PythonTranslator(final String traversalSource, final boolean importStatics) {
this.traversalSource = traversalSource;
this.importStatics = importStatics;
}
public static PythonTranslator of(final String traversalSource, final boolean importStatics) {
return new PythonTranslator(traversalSource, importStatics);
}
public static PythonTranslator of(final String traversalSource) {
return new PythonTranslator(traversalSource, false);
}
@Override
public String getTraversalSource() {
return this.traversalSource;
}
@Override
public String translate(final Bytecode bytecode) {
return this.internalTranslate(this.traversalSource, bytecode);
}
@Override
public String getTargetLanguage() {
return "gremlin-python";
}
@Override
public String toString() {
return StringFactory.translatorString(this);
}
///////
private String internalTranslate(final String start, final Bytecode bytecode) {
final StringBuilder traversalScript = new StringBuilder(start);
for (final Bytecode.Instruction instruction : bytecode.getInstructions()) {
final String methodName = instruction.getOperator();
final Object[] arguments = instruction.getArguments();
if (IS_TESTING &&
instruction.getOperator().equals(TraversalSource.Symbols.withStrategies) &&
instruction.getArguments()[0].toString().contains("TranslationStrategy"))
continue;
else if (0 == arguments.length)
traversalScript.append(".").append(SymbolHelper.toPython(methodName)).append("()");
else if (methodName.equals("range") && 2 == arguments.length)
traversalScript.append("[").append(arguments[0]).append(":").append(arguments[1]).append("]");
else if (methodName.equals("limit") && 1 == arguments.length)
traversalScript.append("[0:").append(arguments[0]).append("]");
else if (methodName.equals("values") && 1 == arguments.length && traversalScript.length() > 3 && !STEP_NAMES.contains(arguments[0].toString()))
traversalScript.append(".").append(arguments[0]);
else {
traversalScript.append(".");
String temp = SymbolHelper.toPython(methodName) + "(";
for (final Object object : arguments) {
temp = temp + convertToString(object) + ",";
}
traversalScript.append(temp.substring(0, temp.length() - 1)).append(")");
}
// clip off __.
if (this.importStatics && traversalScript.substring(0, 3).startsWith("__.")
&& !NO_STATIC.stream().filter(name -> traversalScript.substring(3).startsWith(SymbolHelper.toPython(name))).findAny().isPresent()) {
traversalScript.delete(0, 3);
}
}
return traversalScript.toString();
}
private String convertToString(final Object object) {
if (object instanceof Bytecode.Binding)
return ((Bytecode.Binding) object).variable();
else if (object instanceof Bytecode)
return this.internalTranslate("__", (Bytecode) object);
else if (object instanceof Traversal)
return convertToString(((Traversal) object).asAdmin().getBytecode());
else if (object instanceof String)
return ((String) object).contains("\"") ? "\"\"\"" + object + "\"\"\"" : "\"" + object + "\"";
else if (object instanceof Set) {
final Set<String> set = new LinkedHashSet<>(((Set) object).size());
for (final Object item : (Set) object) {
set.add(convertToString(item));
}
return "set(" + set.toString() + ")";
} else if (object instanceof List) {
final List<String> list = new ArrayList<>(((List) object).size());
for (final Object item : (List) object) {
list.add(convertToString(item));
}
return list.toString();
} else if (object instanceof Map) {
final StringBuilder map = new StringBuilder("{");
for (final Map.Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
map.append(convertToString(entry.getKey())).
append(":").
append(convertToString(entry.getValue())).
append(",");
}
return map.length() > 1 ? map.substring(0, map.length() - 1) + "}" : map.append("}").toString();
} else if (object instanceof Long)
return object + "L";
else if (object instanceof TraversalStrategyProxy) {
final TraversalStrategyProxy proxy = (TraversalStrategyProxy) object;
if (proxy.getConfiguration().isEmpty())
return "TraversalStrategy(\"" + proxy.getStrategyClass().getSimpleName() + "\")";
else
return "TraversalStrategy(\"" + proxy.getStrategyClass().getSimpleName() + "\"," + convertToString(ConfigurationConverter.getMap(proxy.getConfiguration())) + ")";
} else if (object instanceof TraversalStrategy) {
return convertToString(new TraversalStrategyProxy((TraversalStrategy) object));
} else if (object instanceof Boolean)
return object.equals(Boolean.TRUE) ? "True" : "False";
else if (object instanceof Class)
return ((Class) object).getCanonicalName();
else if (object instanceof VertexProperty.Cardinality)
return "Cardinality." + SymbolHelper.toPython(object.toString());
else if (object instanceof SackFunctions.Barrier)
return "Barrier." + SymbolHelper.toPython(object.toString());
else if (object instanceof TraversalOptionParent.Pick)
return "Pick." + SymbolHelper.toPython(object.toString());
else if (object instanceof Enum)
return convertStatic(((Enum) object).getDeclaringClass().getSimpleName() + ".") + SymbolHelper.toPython(object.toString());
else if (object instanceof P)
return convertPToString((P) object, new StringBuilder()).toString();
else if (object instanceof Element) {
if (object instanceof Vertex) {
final Vertex vertex = (Vertex) object;
return "Vertex(" + convertToString(vertex.id()) + "," + convertToString(vertex.label()) + ")";
} else if (object instanceof Edge) {
final Edge edge = (Edge) object;
return "Edge(" + convertToString(edge.id()) + ", " +
"Vertex(" + convertToString(edge.outVertex().id()) + ")," +
convertToString(edge.label()) +
",Vertex(" + convertToString(edge.inVertex().id()) + "))";
} else { // VertexProperty
final VertexProperty vertexProperty = (VertexProperty) object;
return "VertexProperty(" + convertToString(vertexProperty.id()) + "," +
convertToString(vertexProperty.label()) + "," +
convertToString(vertexProperty.value()) + ")";
}
} else if (object instanceof Lambda)
return convertLambdaToString((Lambda) object);
else
return null == object ? "None" : object.toString();
}
private String convertStatic(final String name) {
return this.importStatics ? "" : name;
}
private StringBuilder convertPToString(final P p, final StringBuilder current) {
if (p instanceof ConnectiveP) {
final List<P<?>> list = ((ConnectiveP) p).getPredicates();
for (int i = 0; i < list.size(); i++) {
convertPToString(list.get(i), current);
if (i < list.size() - 1)
current.append(p instanceof OrP ? ".or_(" : ".and_(");
}
current.append(")");
} else
current.append(convertStatic("P.")).append(p.getBiPredicate().toString()).append("(").append(convertToString(p.getValue())).append(")");
return current;
}
protected String convertLambdaToString(final Lambda lambda) {
final String lambdaString = lambda.getLambdaScript().trim();
return lambdaString.startsWith("lambda") ? lambdaString : "lambda " + lambdaString;
}
}
| I had to tweak master/ on the last merge and the tweak I did was more clever than what I have in tp32/. Thus, back porting it. CTR.
| gremlin-python/src/main/java/org/apache/tinkerpop/gremlin/python/jsr223/PythonTranslator.java | I had to tweak master/ on the last merge and the tweak I did was more clever than what I have in tp32/. Thus, back porting it. CTR. | <ide><path>remlin-python/src/main/java/org/apache/tinkerpop/gremlin/python/jsr223/PythonTranslator.java
<ide> return "Vertex(" + convertToString(vertex.id()) + "," + convertToString(vertex.label()) + ")";
<ide> } else if (object instanceof Edge) {
<ide> final Edge edge = (Edge) object;
<del> return "Edge(" + convertToString(edge.id()) + ", " +
<del> "Vertex(" + convertToString(edge.outVertex().id()) + ")," +
<del> convertToString(edge.label()) +
<del> ",Vertex(" + convertToString(edge.inVertex().id()) + "))";
<add> return "Edge(" + convertToString(edge.id()) + "," +
<add> convertToString(edge.outVertex()) + "," +
<add> convertToString(edge.label()) + "," +
<add> convertToString(edge.inVertex()) + ")";
<ide> } else { // VertexProperty
<ide> final VertexProperty vertexProperty = (VertexProperty) object;
<ide> return "VertexProperty(" + convertToString(vertexProperty.id()) + "," + |
|
Java | apache-2.0 | 5980d1e8e0cb60c66b58c3872c4f2291b3c7904c | 0 | helyho/Voovan,helyho/Voovan,helyho/Voovan | package org.voovan.tools.buffer;
import org.voovan.Global;
import org.voovan.tools.*;
import org.voovan.tools.collection.ThreadObjectPool;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import sun.misc.Unsafe;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
/**
* ByteBuffer 工具类
*
* @author helyho
*
* Java Framework.
* WebSite: https://github.com/helyho/Voovan
* Licence: Apache v2 License
*/
public class TByteBuffer {
public final static Unsafe UNSAFE = TUnsafe.getUnsafe();
public final static int DEFAULT_BYTE_BUFFER_SIZE = TEnv.getSystemProperty("ByteBufferSize", 1024*8);
public final static int THREAD_BUFFER_POOL_SIZE = TEnv.getSystemProperty("ThreadBufferPoolSize", 64);
public final static ThreadObjectPool<ByteBuffer> THREAD_BYTE_BUFFER_POOL = new ThreadObjectPool<ByteBuffer>(THREAD_BUFFER_POOL_SIZE, ()->allocateManualReleaseBuffer(DEFAULT_BYTE_BUFFER_SIZE));
static {
System.out.println("[BUFFER] ThreadBufferPoolSize: \t" + THREAD_BYTE_BUFFER_POOL.getThreadPoolSize());
System.out.println("[BUFFER] BufferSize: \t\t" + DEFAULT_BYTE_BUFFER_SIZE);
}
public final static ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocateDirect(0);
public final static Class DIRECT_BYTE_BUFFER_CLASS = EMPTY_BYTE_BUFFER.getClass();
public final static Field addressField = ByteBufferField("address");
public final static Long addressFieldOffset = TUnsafe.getFieldOffset(addressField);
public final static Field capacityField = ByteBufferField("capacity");
public final static Long capacityFieldOffset = TUnsafe.getFieldOffset(capacityField);
public final static Field attField = ByteBufferField("att");
public final static Long attFieldOffset = TUnsafe.getFieldOffset(attField);
private static Field ByteBufferField(String fieldName){
Field field = TReflect.findField(DIRECT_BYTE_BUFFER_CLASS, fieldName);
field.setAccessible(true);
return field;
}
/**
* 分配可能手工进行释放的 ByteBuffer
* @param capacity 容量
* @return ByteBuffer 对象
*/
protected static ByteBuffer allocateManualReleaseBuffer(int capacity){
try {
long address = (UNSAFE.allocateMemory(capacity));
Deallocator deallocator = new Deallocator(address, capacity);
ByteBuffer byteBuffer = (ByteBuffer) TUnsafe.getUnsafe().allocateInstance(DIRECT_BYTE_BUFFER_CLASS);
setAddress(byteBuffer, address);
setCapacity(byteBuffer, capacity);
setAttr(byteBuffer, deallocator);
Cleaner.create(byteBuffer, deallocator);
ByteBufferAnalysis.malloc(capacity);
return byteBuffer;
} catch (Exception e) {
Logger.error("Allocate ByteBuffer error. ", e);
return null;
}
}
/**
* 根据框架的非堆内存配置, 分配 ByteBuffer
* @return ByteBuffer 对象
*/
public static ByteBuffer allocateDirect() {
return allocateDirect(DEFAULT_BYTE_BUFFER_SIZE);
}
/**
* 根据框架的非堆内存配置, 分配 ByteBuffer
* @param capacity 容量
* @return ByteBuffer 对象
*/
public static ByteBuffer allocateDirect(int capacity) {
ByteBuffer byteBuffer = null;
while (byteBuffer == null) {
byteBuffer = THREAD_BYTE_BUFFER_POOL.get(() -> allocateManualReleaseBuffer(capacity));
try {
if (capacity <= byteBuffer.capacity()) {
byteBuffer.limit(capacity);
} else {
reallocate(byteBuffer, capacity);
}
byteBuffer.position(0);
byteBuffer.limit(capacity);
} catch (Exception e) {
byteBuffer = null;
if(byteBuffer!=null) {
TByteBuffer.release(byteBuffer);
}
}
}
return byteBuffer;
}
/**
* 重新分配 byteBuffer 中的空间大小
* @param byteBuffer byteBuffer对象
* @param newSize 重新分配的空间大小
* @return true:成功, false:失败
*/
public static boolean reallocate(ByteBuffer byteBuffer, int newSize) {
if(isReleased(byteBuffer)) {
return false;
}
try {
int oldCapacity = byteBuffer.capacity();
if(oldCapacity > newSize){
byteBuffer.limit(newSize);
return true;
}
if(!byteBuffer.hasArray()) {
if(getAtt(byteBuffer) == null){
throw new UnsupportedOperationException("JDK's ByteBuffer can't reallocate");
}
long address = getAddress(byteBuffer);
long newAddress = UNSAFE.reallocateMemory(address, newSize);
setAddress(byteBuffer, newAddress);
}else{
byte[] hb = byteBuffer.array();
byte[] newHb = Arrays.copyOf(hb, newSize);
TReflect.setFieldValue(byteBuffer, "hb", newHb);
}
//重置容量
capacityField.set(byteBuffer, newSize);
ByteBufferAnalysis.realloc(oldCapacity, newSize);
return true;
}catch (ReflectiveOperationException e){
Logger.error("TByteBuffer.reallocate() Error. ", e);
}
return false;
}
/**
* 移动 Bytebuffer 中的数据
* 以Bytebuffer.position()为原点,移动 offset 个位置
* @param byteBuffer byteBuffer对象
* @param offset 相对当前 ByteBuffer.position 的偏移量
* @return true:成功, false:失败
*/
public static boolean move(ByteBuffer byteBuffer, int offset) {
try {
if(!byteBuffer.hasRemaining()) {
byteBuffer.position(0);
byteBuffer.limit(0);
return true;
}
if(offset==0){
return true;
}
int newPosition = byteBuffer.position() + offset;
int newLimit = byteBuffer.limit() + offset;
if(newPosition < 0){
return false;
}
if(newLimit > byteBuffer.capacity()){
reallocate(byteBuffer, newLimit);
}
if(!byteBuffer.hasArray()) {
long address = getAddress(byteBuffer);
if(address!=0) {
long startAddress = address + byteBuffer.position();
long targetAddress = address + newPosition;
if (address > targetAddress) {
targetAddress = address;
}
UNSAFE.copyMemory(startAddress, targetAddress, byteBuffer.remaining());
}
}else{
byte[] hb = byteBuffer.array();
System.arraycopy(hb, byteBuffer.position(), hb, newPosition, byteBuffer.remaining());
}
byteBuffer.limit(newLimit);
byteBuffer.position(newPosition);
return true;
}catch (ReflectiveOperationException e){
Logger.error("TByteBuffer.moveData() Error.", e);
}
return false;
}
/**
* 复制一个 Bytebuffer 对象
* @param byteBuffer 原 ByteBuffer 对象
* @return 复制出的对象
* @throws ReflectiveOperationException 反射错误
*/
public static ByteBuffer copy(ByteBuffer byteBuffer) throws ReflectiveOperationException {
ByteBuffer newByteBuffer = TByteBuffer.allocateDirect(byteBuffer.capacity());
if(byteBuffer.hasRemaining()) {
long address = getAddress(byteBuffer);
long newAddress = getAddress(newByteBuffer);
UNSAFE.copyMemory(address, newAddress + byteBuffer.position(), byteBuffer.remaining());
}
newByteBuffer.position(byteBuffer.position());
newByteBuffer.limit(byteBuffer.limit());
return newByteBuffer;
}
/**
* 在 srcBuffer 后追加 appendBuffer;
* @param srcBuffer 被追加数据的 srcBuffer
* @param srcPosition 被追加数据的位置
* @param appendBuffer 追加的内容
* @param appendPosition 追加的数据起始位置
* @param length 追加数据的长度
* @return 返回被追加数据的 srcBuffer
*/
public static ByteBuffer append(ByteBuffer srcBuffer, int srcPosition, ByteBuffer appendBuffer, int appendPosition, int length) {
try {
int appendSize = appendBuffer.limit() < length ? appendBuffer.limit() : length;
long srcAddress = getAddress(srcBuffer) + srcPosition;
long appendAddress = getAddress(appendBuffer) + appendPosition;
int availableSize = srcBuffer.capacity() - srcBuffer.limit();
if (availableSize < appendSize) {
int newSize = srcBuffer.capacity() + appendSize;
reallocate(srcBuffer, newSize);
}
UNSAFE.copyMemory(appendAddress, srcAddress, appendSize);
srcBuffer.limit(srcPosition + appendSize);
srcBuffer.position(srcBuffer.limit());
return srcBuffer;
} catch (ReflectiveOperationException e){
Logger.error("TByteBuffer.moveData() Error.", e);
}
return null;
}
/**
* 释放byteBuffer
* 释放对外的 bytebuffer
* @param byteBuffer bytebuffer 对象
*/
public static void release(ByteBuffer byteBuffer) {
if(byteBuffer == null){
return;
}
if (byteBuffer != null) {
if(THREAD_BYTE_BUFFER_POOL.getPool().avaliable() > 0 &&
byteBuffer.capacity() > DEFAULT_BYTE_BUFFER_SIZE){
reallocate(byteBuffer, DEFAULT_BYTE_BUFFER_SIZE);
return;
}
THREAD_BYTE_BUFFER_POOL.release(byteBuffer, (buffer)->{
try {
long address = TByteBuffer.getAddress(byteBuffer);
Object att = getAtt(byteBuffer);
if (address!=0 && att!=null && att.getClass() == Deallocator.class) {
if(address!=0) {
byteBuffer.clear();
synchronized (byteBuffer) {
setAddress(byteBuffer, 0);
UNSAFE.freeMemory(address);
ByteBufferAnalysis.free(byteBuffer.capacity());
}
}
}
} catch (ReflectiveOperationException e) {
Logger.error(e);
}
});
}
}
/**
* 判断是否已经释放
* @param byteBuffer ByteBuffer 对象
* @return true: 已释放, false: 未释放
*/
public static boolean isReleased(ByteBuffer byteBuffer){
if(byteBuffer==null){
return true;
}
try {
return getAddress(byteBuffer) == 0;
}catch (ReflectiveOperationException e){
return true;
}
}
/**
* 将ByteBuffer转换成 byte 数组
* @param bytebuffer ByteBuffer 对象
* @return byte 数组
*/
public static byte[] toArray(ByteBuffer bytebuffer){
if(!bytebuffer.hasArray()) {
if(isReleased(bytebuffer)) {
return new byte[0];
}
bytebuffer.mark();
int position = bytebuffer.position();
int limit = bytebuffer.limit();
byte[] buffers = new byte[limit-position];
bytebuffer.get(buffers);
bytebuffer.reset();
return buffers;
}else{
return Arrays.copyOfRange(bytebuffer.array(), 0, bytebuffer.limit());
}
}
/**
* 将 Bytebuffer 转换成 字符串
* @param bytebuffer Bytebuffer 对象
* @param charset 字符集
* @return 字符串对象
*/
public static String toString(ByteBuffer bytebuffer,String charset) {
try {
return new String(toArray(bytebuffer), charset);
} catch (UnsupportedEncodingException e) {
Logger.error(charset+" is not supported",e);
return null;
}
}
/**
* 将 Bytebuffer 转换成 字符串
* @param bytebuffer Bytebuffer 对象
* @return 字符串对象
*/
public static String toString(ByteBuffer bytebuffer) {
return toString(bytebuffer, "UTF-8");
}
/**
* 查找特定 byte 标识的位置
* byte 标识数组第一个字节的索引位置
* @param byteBuffer Bytebuffer 对象
* @param mark byte 标识数组
* @return 第一个字节的索引位置
*/
public static int indexOf(ByteBuffer byteBuffer, byte[] mark){
if(isReleased(byteBuffer)) {
return -1;
}
if(byteBuffer.remaining() == 0){
return -1;
}
int originPosition = byteBuffer.position();
int length = byteBuffer.remaining();
if(length < mark.length){
return -1;
}
int index = -1;
int i = byteBuffer.position();
int j = 0;
while(i <= (byteBuffer.limit() - mark.length + j ) ){
if(byteBuffer.get(i) != mark[j] ){
if(i == (byteBuffer.limit() - mark.length + j )){
break;
}
int pos = TByte.byteIndexOf(mark, byteBuffer.get(i+mark.length-j));
if( pos== -1){
i = i + mark.length + 1 - j;
j = 0 ;
}else{
i = i + mark.length - pos - j;
j = 0;
}
}else{
if(j == (mark.length - 1)){
i = i - j + 1 ;
j = 0;
index = i-j - 1;
break;
}else{
i++;
j++;
}
}
}
byteBuffer.position(originPosition);
return index;
}
/**
* 获取内存地址
* @param byteBuffer bytebuffer 对象
* @return 内存地址
* @throws ReflectiveOperationException 反射异常
*/
public static Long getAddress(ByteBuffer byteBuffer) throws ReflectiveOperationException {
return UNSAFE.getLong(byteBuffer, addressFieldOffset);
}
/**
* 设置内存地址
* @param byteBuffer bytebuffer 对象
* @param address 内存地址
* @throws ReflectiveOperationException 反射异常
*/
public static void setAddress(ByteBuffer byteBuffer, long address) throws ReflectiveOperationException {
UNSAFE.putLong(byteBuffer, addressFieldOffset, address);
Object att = getAtt(byteBuffer);
if(att!=null && att instanceof Deallocator){
((Deallocator) att).setAddress(address);
}
}
/**
* 获取附加对象
* @param byteBuffer bytebuffer 对象
* @return 附加对象
* @throws ReflectiveOperationException 反射异常
*/
public static Object getAtt(ByteBuffer byteBuffer) throws ReflectiveOperationException {
return UNSAFE.getObject(byteBuffer, attFieldOffset);
}
/**
* 设置附加对象
* @param byteBuffer bytebuffer 对象
* @param attr 附加对象
* @throws ReflectiveOperationException 反射异常
*/
public static void setAttr(ByteBuffer byteBuffer, Object attr) throws ReflectiveOperationException {
UNSAFE.putObject(byteBuffer, attFieldOffset, attr);
}
/**
* 设置内存地址
* @param byteBuffer bytebuffer 对象
* @param capacity 容量
* @throws ReflectiveOperationException 反射异常
*/
public static void setCapacity(ByteBuffer byteBuffer, int capacity) throws ReflectiveOperationException {
UNSAFE.putInt(byteBuffer, capacityFieldOffset, capacity);
Object att = getAtt(byteBuffer);
if(att!=null && att instanceof Deallocator){
((Deallocator) att).setCapacity(capacity);
}
}
}
| Common/src/main/java/org/voovan/tools/buffer/TByteBuffer.java | package org.voovan.tools.buffer;
import org.voovan.Global;
import org.voovan.tools.*;
import org.voovan.tools.collection.ThreadObjectPool;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import sun.misc.Unsafe;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
/**
* ByteBuffer 工具类
*
* @author helyho
*
* Java Framework.
* WebSite: https://github.com/helyho/Voovan
* Licence: Apache v2 License
*/
public class TByteBuffer {
public final static Unsafe UNSAFE = TUnsafe.getUnsafe();
public final static int DEFAULT_BYTE_BUFFER_SIZE = TEnv.getSystemProperty("ByteBufferSize", 1024*8);
public final static int THREAD_BUFFER_POOL_SIZE = TEnv.getSystemProperty("ThreadBufferPoolSize", 64);
public final static ThreadObjectPool<ByteBuffer> THREAD_BYTE_BUFFER_POOL = new ThreadObjectPool<ByteBuffer>(THREAD_BUFFER_POOL_SIZE, ()->allocateManualReleaseBuffer(DEFAULT_BYTE_BUFFER_SIZE));
static {
System.out.println("[BUFFER] ThreadBufferPoolSize: \t" + THREAD_BYTE_BUFFER_POOL.getThreadPoolSize());
System.out.println("[BUFFER] BufferSize: \t\t" + DEFAULT_BYTE_BUFFER_SIZE);
}
public final static ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocateDirect(0);
public final static Class DIRECT_BYTE_BUFFER_CLASS = EMPTY_BYTE_BUFFER.getClass();
public final static Field addressField = ByteBufferField("address");
public final static Long addressFieldOffset = TUnsafe.getFieldOffset(addressField);
public final static Field capacityField = ByteBufferField("capacity");
public final static Long capacityFieldOffset = TUnsafe.getFieldOffset(capacityField);
public final static Field attField = ByteBufferField("att");
public final static Long attFieldOffset = TUnsafe.getFieldOffset(attField);
private static Field ByteBufferField(String fieldName){
Field field = TReflect.findField(DIRECT_BYTE_BUFFER_CLASS, fieldName);
field.setAccessible(true);
return field;
}
/**
* 分配可能手工进行释放的 ByteBuffer
* @param capacity 容量
* @return ByteBuffer 对象
*/
protected static ByteBuffer allocateManualReleaseBuffer(int capacity){
try {
long address = (UNSAFE.allocateMemory(capacity));
Deallocator deallocator = new Deallocator(address, capacity);
ByteBuffer byteBuffer = null;
byteBuffer = (ByteBuffer) TUnsafe.getUnsafe().allocateInstance(DIRECT_BYTE_BUFFER_CLASS);
setAddress(byteBuffer, address);
setCapacity(byteBuffer, capacity);
setAttr(byteBuffer, deallocator);
Cleaner.create(byteBuffer, deallocator);
ByteBufferAnalysis.malloc(capacity);
return byteBuffer;
} catch (Exception e) {
Logger.error("Allocate ByteBuffer error. ", e);
return null;
}
}
/**
* 根据框架的非堆内存配置, 分配 ByteBuffer
* @return ByteBuffer 对象
*/
public static ByteBuffer allocateDirect() {
return allocateDirect(DEFAULT_BYTE_BUFFER_SIZE);
}
/**
* 根据框架的非堆内存配置, 分配 ByteBuffer
* @param capacity 容量
* @return ByteBuffer 对象
*/
public static ByteBuffer allocateDirect(int capacity) {
ByteBuffer byteBuffer = null;
while (byteBuffer == null) {
byteBuffer = THREAD_BYTE_BUFFER_POOL.get(() -> allocateManualReleaseBuffer(capacity));
try {
if (capacity <= byteBuffer.capacity()) {
byteBuffer.limit(capacity);
} else {
reallocate(byteBuffer, capacity);
}
byteBuffer.position(0);
byteBuffer.limit(capacity);
} catch (Exception e) {
byteBuffer = null;
if(byteBuffer!=null) {
TByteBuffer.release(byteBuffer);
}
}
}
return byteBuffer;
}
/**
* 重新分配 byteBuffer 中的空间大小
* @param byteBuffer byteBuffer对象
* @param newSize 重新分配的空间大小
* @return true:成功, false:失败
*/
public static boolean reallocate(ByteBuffer byteBuffer, int newSize) {
if(isReleased(byteBuffer)) {
return false;
}
try {
int oldCapacity = byteBuffer.capacity();
if(oldCapacity > newSize){
byteBuffer.limit(newSize);
return true;
}
if(!byteBuffer.hasArray()) {
if(getAtt(byteBuffer) == null){
throw new UnsupportedOperationException("JDK's ByteBuffer can't reallocate");
}
long address = getAddress(byteBuffer);
long newAddress = UNSAFE.reallocateMemory(address, newSize);
setAddress(byteBuffer, newAddress);
}else{
byte[] hb = byteBuffer.array();
byte[] newHb = Arrays.copyOf(hb, newSize);
TReflect.setFieldValue(byteBuffer, "hb", newHb);
}
//重置容量
capacityField.set(byteBuffer, newSize);
ByteBufferAnalysis.realloc(oldCapacity, newSize);
return true;
}catch (ReflectiveOperationException e){
Logger.error("TByteBuffer.reallocate() Error. ", e);
}
return false;
}
/**
* 移动 Bytebuffer 中的数据
* 以Bytebuffer.position()为原点,移动 offset 个位置
* @param byteBuffer byteBuffer对象
* @param offset 相对当前 ByteBuffer.position 的偏移量
* @return true:成功, false:失败
*/
public static boolean move(ByteBuffer byteBuffer, int offset) {
try {
if(!byteBuffer.hasRemaining()) {
byteBuffer.position(0);
byteBuffer.limit(0);
return true;
}
if(offset==0){
return true;
}
int newPosition = byteBuffer.position() + offset;
int newLimit = byteBuffer.limit() + offset;
if(newPosition < 0){
return false;
}
if(newLimit > byteBuffer.capacity()){
reallocate(byteBuffer, newLimit);
}
if(!byteBuffer.hasArray()) {
long address = getAddress(byteBuffer);
if(address!=0) {
long startAddress = address + byteBuffer.position();
long targetAddress = address + newPosition;
if (address > targetAddress) {
targetAddress = address;
}
UNSAFE.copyMemory(startAddress, targetAddress, byteBuffer.remaining());
}
}else{
byte[] hb = byteBuffer.array();
System.arraycopy(hb, byteBuffer.position(), hb, newPosition, byteBuffer.remaining());
}
byteBuffer.limit(newLimit);
byteBuffer.position(newPosition);
return true;
}catch (ReflectiveOperationException e){
Logger.error("TByteBuffer.moveData() Error.", e);
}
return false;
}
/**
* 复制一个 Bytebuffer 对象
* @param byteBuffer 原 ByteBuffer 对象
* @return 复制出的对象
* @throws ReflectiveOperationException 反射错误
*/
public static ByteBuffer copy(ByteBuffer byteBuffer) throws ReflectiveOperationException {
ByteBuffer newByteBuffer = TByteBuffer.allocateDirect(byteBuffer.capacity());
if(byteBuffer.hasRemaining()) {
long address = getAddress(byteBuffer);
long newAddress = getAddress(newByteBuffer);
UNSAFE.copyMemory(address, newAddress + byteBuffer.position(), byteBuffer.remaining());
}
newByteBuffer.position(byteBuffer.position());
newByteBuffer.limit(byteBuffer.limit());
return newByteBuffer;
}
/**
* 在 srcBuffer 后追加 appendBuffer;
* @param srcBuffer 被追加数据的 srcBuffer
* @param srcPosition 被追加数据的位置
* @param appendBuffer 追加的内容
* @param appendPosition 追加的数据起始位置
* @param length 追加数据的长度
* @return 返回被追加数据的 srcBuffer
*/
public static ByteBuffer append(ByteBuffer srcBuffer, int srcPosition, ByteBuffer appendBuffer, int appendPosition, int length) {
try {
int appendSize = appendBuffer.limit() < length ? appendBuffer.limit() : length;
long srcAddress = getAddress(srcBuffer) + srcPosition;
long appendAddress = getAddress(appendBuffer) + appendPosition;
int availableSize = srcBuffer.capacity() - srcBuffer.limit();
if (availableSize < appendSize) {
int newSize = srcBuffer.capacity() + appendSize;
reallocate(srcBuffer, newSize);
}
UNSAFE.copyMemory(appendAddress, srcAddress, appendSize);
srcBuffer.limit(srcPosition + appendSize);
srcBuffer.position(srcBuffer.limit());
return srcBuffer;
} catch (ReflectiveOperationException e){
Logger.error("TByteBuffer.moveData() Error.", e);
}
return null;
}
/**
* 释放byteBuffer
* 释放对外的 bytebuffer
* @param byteBuffer bytebuffer 对象
*/
public static void release(ByteBuffer byteBuffer) {
if(byteBuffer == null){
return;
}
if (byteBuffer != null) {
if(THREAD_BYTE_BUFFER_POOL.getPool().avaliable() > 0 &&
byteBuffer.capacity() > DEFAULT_BYTE_BUFFER_SIZE){
reallocate(byteBuffer, DEFAULT_BYTE_BUFFER_SIZE);
return;
}
THREAD_BYTE_BUFFER_POOL.release(byteBuffer, (buffer)->{
try {
long address = TByteBuffer.getAddress(byteBuffer);
Object att = getAtt(byteBuffer);
if (address!=0 && att!=null && att.getClass() == Deallocator.class) {
if(address!=0) {
byteBuffer.clear();
synchronized (byteBuffer) {
setAddress(byteBuffer, 0);
UNSAFE.freeMemory(address);
ByteBufferAnalysis.free(byteBuffer.capacity());
}
}
}
} catch (ReflectiveOperationException e) {
Logger.error(e);
}
});
}
}
/**
* 判断是否已经释放
* @param byteBuffer ByteBuffer 对象
* @return true: 已释放, false: 未释放
*/
public static boolean isReleased(ByteBuffer byteBuffer){
if(byteBuffer==null){
return true;
}
try {
return getAddress(byteBuffer) == 0;
}catch (ReflectiveOperationException e){
return true;
}
}
/**
* 将ByteBuffer转换成 byte 数组
* @param bytebuffer ByteBuffer 对象
* @return byte 数组
*/
public static byte[] toArray(ByteBuffer bytebuffer){
if(!bytebuffer.hasArray()) {
if(isReleased(bytebuffer)) {
return new byte[0];
}
bytebuffer.mark();
int position = bytebuffer.position();
int limit = bytebuffer.limit();
byte[] buffers = new byte[limit-position];
bytebuffer.get(buffers);
bytebuffer.reset();
return buffers;
}else{
return Arrays.copyOfRange(bytebuffer.array(), 0, bytebuffer.limit());
}
}
/**
* 将 Bytebuffer 转换成 字符串
* @param bytebuffer Bytebuffer 对象
* @param charset 字符集
* @return 字符串对象
*/
public static String toString(ByteBuffer bytebuffer,String charset) {
try {
return new String(toArray(bytebuffer), charset);
} catch (UnsupportedEncodingException e) {
Logger.error(charset+" is not supported",e);
return null;
}
}
/**
* 将 Bytebuffer 转换成 字符串
* @param bytebuffer Bytebuffer 对象
* @return 字符串对象
*/
public static String toString(ByteBuffer bytebuffer) {
return toString(bytebuffer, "UTF-8");
}
/**
* 查找特定 byte 标识的位置
* byte 标识数组第一个字节的索引位置
* @param byteBuffer Bytebuffer 对象
* @param mark byte 标识数组
* @return 第一个字节的索引位置
*/
public static int indexOf(ByteBuffer byteBuffer, byte[] mark){
if(isReleased(byteBuffer)) {
return -1;
}
if(byteBuffer.remaining() == 0){
return -1;
}
int originPosition = byteBuffer.position();
int length = byteBuffer.remaining();
if(length < mark.length){
return -1;
}
int index = -1;
int i = byteBuffer.position();
int j = 0;
while(i <= (byteBuffer.limit() - mark.length + j ) ){
if(byteBuffer.get(i) != mark[j] ){
if(i == (byteBuffer.limit() - mark.length + j )){
break;
}
int pos = TByte.byteIndexOf(mark, byteBuffer.get(i+mark.length-j));
if( pos== -1){
i = i + mark.length + 1 - j;
j = 0 ;
}else{
i = i + mark.length - pos - j;
j = 0;
}
}else{
if(j == (mark.length - 1)){
i = i - j + 1 ;
j = 0;
index = i-j - 1;
break;
}else{
i++;
j++;
}
}
}
byteBuffer.position(originPosition);
return index;
}
/**
* 获取内存地址
* @param byteBuffer bytebuffer 对象
* @return 内存地址
* @throws ReflectiveOperationException 反射异常
*/
public static Long getAddress(ByteBuffer byteBuffer) throws ReflectiveOperationException {
return UNSAFE.getLong(byteBuffer, addressFieldOffset);
}
/**
* 设置内存地址
* @param byteBuffer bytebuffer 对象
* @param address 内存地址
* @throws ReflectiveOperationException 反射异常
*/
public static void setAddress(ByteBuffer byteBuffer, long address) throws ReflectiveOperationException {
UNSAFE.putLong(byteBuffer, addressFieldOffset, address);
Object att = getAtt(byteBuffer);
if(att!=null && att instanceof Deallocator){
((Deallocator) att).setAddress(address);
}
}
/**
* 获取附加对象
* @param byteBuffer bytebuffer 对象
* @return 附加对象
* @throws ReflectiveOperationException 反射异常
*/
public static Object getAtt(ByteBuffer byteBuffer) throws ReflectiveOperationException {
return UNSAFE.getObject(byteBuffer, attFieldOffset);
}
/**
* 设置附加对象
* @param byteBuffer bytebuffer 对象
* @param attr 附加对象
* @throws ReflectiveOperationException 反射异常
*/
public static void setAttr(ByteBuffer byteBuffer, Object attr) throws ReflectiveOperationException {
UNSAFE.putObject(byteBuffer, attFieldOffset, attr);
}
/**
* 设置内存地址
* @param byteBuffer bytebuffer 对象
* @param capacity 容量
* @throws ReflectiveOperationException 反射异常
*/
public static void setCapacity(ByteBuffer byteBuffer, int capacity) throws ReflectiveOperationException {
UNSAFE.putInt(byteBuffer, capacityFieldOffset, capacity);
Object att = getAtt(byteBuffer);
if(att!=null && att instanceof Deallocator){
((Deallocator) att).setCapacity(capacity);
}
}
}
| imp: TByteBuffer 优化
| Common/src/main/java/org/voovan/tools/buffer/TByteBuffer.java | imp: TByteBuffer 优化 | <ide><path>ommon/src/main/java/org/voovan/tools/buffer/TByteBuffer.java
<ide>
<ide> Deallocator deallocator = new Deallocator(address, capacity);
<ide>
<del> ByteBuffer byteBuffer = null;
<del> byteBuffer = (ByteBuffer) TUnsafe.getUnsafe().allocateInstance(DIRECT_BYTE_BUFFER_CLASS);
<add> ByteBuffer byteBuffer = (ByteBuffer) TUnsafe.getUnsafe().allocateInstance(DIRECT_BYTE_BUFFER_CLASS);
<ide> setAddress(byteBuffer, address);
<ide> setCapacity(byteBuffer, capacity);
<ide> setAttr(byteBuffer, deallocator); |
|
Java | cc0-1.0 | 6fb56b5e19b9ba1be9b7eb73caeeae3779177006 | 0 | masmangan/turbo-octo-lana | package pucrs.alpro3.arvores;
public class BinarySearchTree {
class Node {
int value;
Node left, right;
}
private Node root;
public BinarySearchTree() {
root = null;
}
public boolean isEmpty() {
return root == null;
}
public int size() {
// TODO
return 0;
}
public void add(int value) {
// TODO
}
public boolean contains(int value) {
// TODO
return false;
}
}
| src/pucrs/alpro3/arvores/BinarySearchTree.java | package pucrs.alpro3.arvores;
public class BinarySearchTree {
}
| implementação inicial
| src/pucrs/alpro3/arvores/BinarySearchTree.java | implementação inicial | <ide><path>rc/pucrs/alpro3/arvores/BinarySearchTree.java
<ide>
<ide> public class BinarySearchTree {
<ide>
<add> class Node {
<add> int value;
<add> Node left, right;
<add> }
<add>
<add> private Node root;
<add>
<add> public BinarySearchTree() {
<add> root = null;
<add> }
<add>
<add> public boolean isEmpty() {
<add> return root == null;
<add> }
<add>
<add> public int size() {
<add> // TODO
<add> return 0;
<add> }
<add>
<add> public void add(int value) {
<add> // TODO
<add> }
<add>
<add> public boolean contains(int value) {
<add> // TODO
<add> return false;
<add> }
<ide> } |
|
JavaScript | mit | 313db40454e060c316898d9e0e837dff955e39a0 | 0 | jhuang314/poet,jsantell/poet,Nayar/poet,Nayar/poet,r14r/fork_nodejs_poet,r14r/fork_nodejs_poet,jhuang314/poet,jsantell/poet | var options, storage, utils;
module.exports = function ( _options, _storage ) {
options = _options;
storage = _storage;
utils = require( './utils' );
return {
// Posts
postList : storage.orderedPosts,
getPostCount : getPostCount,
getPost : getPost,
getPosts : getPosts,
// Tags
tagList : storage.tags,
postsWithTag : postsWithTag,
tagUrl : tagUrl,
// Categories
categoryList : storage.categories,
postsWithCategory : postsWithCategory,
categoryUrl : categoryUrl,
// Pages
getPageCount : getPageCount,
pageUrl : pageUrl
};
};
function getPostCount () {
return storage.orderedPosts.length;
}
function getPost ( title ) {
return storage.posts[ title ];
}
function getPosts ( from, to ) {
return storage.orderedPosts.slice( from, to );
}
function tagUrl ( tag ) {
return utils.stripRouteParams( options.routes.tag) + tag;
}
function categoryUrl ( cat ) {
return utils.stripRouteParams( options.routes.category ) + cat;
}
function pageUrl ( page ) {
return utils.stripRouteParams( options.routes.page ) + page;
}
function getPageCount () {
return Math.ceil( storage.orderedPosts.length / options.postsPerPage );
}
function postsWithTag ( tag ) {
if ( storage.postsTagged[ tag ] ) return storage.postsTagged[ tag ];
var ret = [];
storage.orderedPosts.forEach(function(p) {
if (p.tags && ~p.tags.indexOf( tag )) {
ret.push( p );
}
});
return storage.postsTagged[ tag ] = ret;
}
function postsWithCategory ( cat ) {
if ( storage.postsCategorized[ cat ] ) return storage.postsCategorized[ cat ];
var ret = [];
storage.orderedPosts.forEach(function(p) {
if ( p.category && p.category.toLowerCase() === cat.toLowerCase() ) {
ret.push( p );
}
});
return storage.postsCategorized[ cat ] = ret;
}
| lib/poet/core.js | var options, storage, utils;
module.exports = function ( _options, _storage ) {
options = _options;
storage = _storage;
utils = require( './utils' );
return {
// Posts
postList : storage.orderedPosts,
getPostCount : getPostCount,
getPost : getPost,
getPosts : getPosts,
// Tags
tagList : storage.tags,
postsWithTag : postsWithTag,
tagUrl : tagUrl,
// Categories
categoryList : storage.categories,
postsWithCategory : postsWithCategory,
categoryUrl : categoryUrl,
// Pages
getPageCount : getPageCount,
pageUrl : pageUrl
};
};
function getPostCount () {
return storage.orderedPosts.length;
}
function getPost ( title ) {
return storage.posts[ title ];
}
function getPosts ( from, to ) {
return storage.orderedPosts.slice( from, to );
}
function tagUrl ( tag ) {
return utils.stripRouteParams( options.routes.tag) + tag;
}
function categoryUrl ( cat ) {
return utils.stripRouteParams( options.routes.category ) + cat;
}
function pageUrl ( page ) {
return utils.stripRouteParams( options.routes.page ) + page;
}
function getPageCount () {
return Math.ceil( storage.orderedPosts.length / options.postsPerPage );
}
function postsWithTag ( tag ) {
if ( storage.postsTagged[ tag ] ) return storage.postsTagged[ tag ];
var ret = [];
storage.orderedPosts.forEach(function(p) {
if (p.tags && ~p.tags.indexOf( tag )) {
ret.push( p );
}
});
return storage.postsTagged[ tag ] = ret;
}
function postsWithCategory ( cat ) {
if ( storage.postsCategorized[ cat ] ) return storage.postsCategorized[ cat ];
var ret = [];
storage.orderedPosts.forEach(function(p) {
if ( p.category && p.category.toLowerCase() === cat.toLowerCase() ) {
ret.push( p );
}
});
return storage.postsCategorized[ cat ] = ret;
}
| Formatting
| lib/poet/core.js | Formatting | <ide><path>ib/poet/core.js
<ide> if ( storage.postsTagged[ tag ] ) return storage.postsTagged[ tag ];
<ide>
<ide> var ret = [];
<del> storage.orderedPosts.forEach(function(p) {
<add> storage.orderedPosts.forEach(function(p) {
<ide> if (p.tags && ~p.tags.indexOf( tag )) {
<ide> ret.push( p );
<ide> }
<ide> if ( storage.postsCategorized[ cat ] ) return storage.postsCategorized[ cat ];
<ide>
<ide> var ret = [];
<del> storage.orderedPosts.forEach(function(p) {
<add> storage.orderedPosts.forEach(function(p) {
<ide> if ( p.category && p.category.toLowerCase() === cat.toLowerCase() ) {
<ide> ret.push( p );
<ide> } |
|
Java | apache-2.0 | de87a00e304b833c7ee1b6382aa9e5eed021f348 | 0 | technology16/pgsqlblocks,technology16/pgsqlblocks | package ru.taximaxim.pgsqlblocks;
import java.io.IOException;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Image;
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.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.TreeColumn;
import ru.taximaxim.pgsqlblocks.dbcdata.DbcData;
import ru.taximaxim.pgsqlblocks.dbcdata.DbcDataListBuilder;
import ru.taximaxim.pgsqlblocks.dbcdata.DbcDataListContentProvider;
import ru.taximaxim.pgsqlblocks.dbcdata.DbcDataListLabelProvider;
import ru.taximaxim.pgsqlblocks.dbcdata.DbcStatus;
import ru.taximaxim.pgsqlblocks.process.Process;
import ru.taximaxim.pgsqlblocks.process.ProcessTreeBuilder;
import ru.taximaxim.pgsqlblocks.process.ProcessTreeContentProvider;
import ru.taximaxim.pgsqlblocks.process.ProcessTreeLabelProvider;
import ru.taximaxim.pgsqlblocks.utils.Images;
import ru.taximaxim.pgsqlblocks.utils.PathBuilder;
public class MainForm extends ApplicationWindow {
private static final Logger LOG = Logger.getLogger(MainForm.class);
private static final String APP_NAME = "pgSqlBlocks";
private static final String SORT_DIRECTION = "sortDirection";
private static final String PID = " pid=";
private static final int ZERO_MARGIN = 0;
private static final int[] VERTICAL_WEIGHTS = new int[] {80, 20};
private static final int[] HORIZONTAL_WEIGHTS = new int[] {12, 88};
private static final int SASH_WIDTH = 2;
private static final int TIMER_INTERVAL = 2;
private static Display display;
private static Shell shell;
private DbcData selectedDbcData;
private Process selectedProcess;
private Text procText;
private SashForm caTreeSf;
private TableViewer caServersTable;
private TreeViewer caMainTree;
private Composite procComposite;
private TableViewer bhServersTable;
private TreeViewer bhMainTree;
private Action deleteDB;
private Action editDB;
private Action connectDB;
private Action disconnectDB;
private Action autoUpdate;
private Action onlyBlocked;
private AddDbcDataDlg addDbcDlg;
private boolean autoUpdateMode = true;
private boolean onlyBlockedMode = false;
private SortColumn sortColumn = SortColumn.BLOCKED_COUNT;
private SortDirection sortDirection = SortDirection.UP;
private DbcDataListBuilder dbcDataList = DbcDataListBuilder.getInstance();
private ConcurrentMap<String, Image> imagesMap = new ConcurrentHashMap<String, Image>();
private ConcurrentMap<DbcData, ProcessTreeBuilder> processTreeMap = new ConcurrentHashMap<>();
private ConcurrentMap<DbcData, ProcessTreeBuilder> blockedProcessTreeMap = new ConcurrentHashMap<>();
private int[] caMainTreeColsSize = new int[]{80, 110, 150, 110, 110, 110, 145, 145, 145, 55, 145, 70, 65, 150, 80};
private String[] caMainTreeColsName = new String[]{
"pid", "blocked_count", "application_name", "datname", "usename", "client", "backend_start", "query_start",
"xact_stat", "state", "state_change", "blocked", "waiting", "query" , "slowquery"};
private String[] caColName = {"PID", "BLOCKED_COUNT", "APPLICATION_NAME", "DATNAME", "USENAME", "CLIENT", "BACKEND_START", "QUERY_START",
"XACT_STAT", "STATE", "STATE_CHANGE", "BLOCKED", "WAITING", "QUERY", "SLOWQUERY"};
public Process getProcessTree(DbcData dbcData) {
ProcessTreeBuilder processTree = processTreeMap.get(dbcData);
if(processTree == null){
processTree = new ProcessTreeBuilder(dbcData);
processTreeMap.put(dbcData, processTree);
}
Process rootProcess = processTree.getProcessTree();
processTree.processSort(rootProcess, sortColumn, sortDirection);
return rootProcess;
}
public Process getOnlyBlockedProcessTree(DbcData dbcData) {
ProcessTreeBuilder processTree = blockedProcessTreeMap.get(dbcData);
if(processTree == null){
processTree = new ProcessTreeBuilder(dbcData);
blockedProcessTreeMap.put(dbcData, processTree);
}
return processTree.getOnlyBlockedProcessTree();
}
public static void main(String[] args) {
try {
Logger rootLogger = Logger.getRootLogger();
rootLogger.setLevel(Level.INFO);
PatternLayout layout = new PatternLayout("%d{ISO8601} [%t] %-5p %c %x - %m%n");
rootLogger.addAppender(new ConsoleAppender(layout));
try {
DailyRollingFileAppender fileAppender = new DailyRollingFileAppender(layout, PathBuilder.getInstance().getLogsPath().toString(), "yyyy-MM-dd");
rootLogger.addAppender(fileAppender);
} catch (IOException e) {
LOG.error("Произошла ошибка при настройке логирования:", e);
}
display = new Display();
shell = new Shell(display);
MainForm wwin = new MainForm(shell);
wwin.setBlockOnOpen(true);
wwin.open();
Display.getCurrent().dispose();
} catch (Exception e) {
LOG.error("Произошла ошибка:", e);
}
}
public MainForm(Shell shell) {
super(shell);
addToolBar(SWT.RIGHT | SWT.FLAT);
}
@Override
protected void constrainShellSize() {
super.constrainShellSize();
getShell().setMaximized( true );
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(APP_NAME);
}
@Override
protected Control createContents(Composite parent)
{
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
addDbcDlg = new AddDbcDataDlg(shell);
GridLayout gridLayout = new GridLayout();
gridLayout.marginHeight = ZERO_MARGIN;
gridLayout.marginWidth = ZERO_MARGIN;
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
SashForm verticalSf = new SashForm(composite, SWT.VERTICAL);
{
verticalSf.setLayout(gridLayout);
verticalSf.setLayoutData(gridData);
verticalSf.SASH_WIDTH = SASH_WIDTH;
verticalSf.setBackground(composite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
Composite topComposite = new Composite(verticalSf, SWT.NONE);
topComposite.setLayout(gridLayout);
TabFolder tabPanel = new TabFolder(topComposite, SWT.BORDER);
{
tabPanel.setLayoutData(gridData);
TabItem currentActivityTi = new TabItem(tabPanel, SWT.NONE);
{
currentActivityTi.setText("Текущая активность");
SashForm currentActivitySf = new SashForm(tabPanel, SWT.HORIZONTAL);
{
currentActivitySf.setLayout(gridLayout);
currentActivitySf.setLayoutData(gridData);
currentActivitySf.SASH_WIDTH = SASH_WIDTH;
currentActivitySf.setBackground(topComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
caServersTable = new TableViewer(currentActivitySf, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
{
caServersTable.getTable().setHeaderVisible(true);
caServersTable.getTable().setLinesVisible(true);
caServersTable.getTable().setLayoutData(gridData);
TableViewerColumn tvColumn = new TableViewerColumn(caServersTable, SWT.NONE);
tvColumn.getColumn().setText("Сервер");
tvColumn.getColumn().setWidth(200);
caServersTable.setContentProvider(new DbcDataListContentProvider());
caServersTable.setLabelProvider(new DbcDataListLabelProvider());
caServersTable.setInput(dbcDataList.getList());
caServersTable.refresh();
}
caTreeSf = new SashForm(currentActivitySf, SWT.VERTICAL);
{
caMainTree = new TreeViewer(caTreeSf, SWT.VIRTUAL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
caMainTree.getTree().setHeaderVisible(true);
caMainTree.getTree().setLinesVisible(true);
caMainTree.getTree().setLayoutData(gridData);
for(int i=0;i<caMainTreeColsName.length;i++) {
TreeViewerColumn treeColumn = new TreeViewerColumn(caMainTree, SWT.NONE);
treeColumn.getColumn().setText(caMainTreeColsName[i]);
treeColumn.getColumn().setWidth(caMainTreeColsSize[i]);
treeColumn.getColumn().setData("colName",caColName[i]);
treeColumn.getColumn().setData(SORT_DIRECTION, SortDirection.UP);
}
caMainTree.setContentProvider(new ProcessTreeContentProvider());
caMainTree.setLabelProvider(new ProcessTreeLabelProvider());
procComposite = new Composite(caTreeSf, SWT.BORDER);
{
procComposite.setLayout(gridLayout);
GridData procCompositeGd = new GridData(SWT.FILL, SWT.FILL, true, true);
procComposite.setLayoutData(procCompositeGd);
procComposite.setVisible(false);
ToolBar pcToolBar = new ToolBar(procComposite, SWT.FLAT | SWT.RIGHT);
pcToolBar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
ToolItem terminateProc = new ToolItem(pcToolBar, SWT.PUSH);
terminateProc.setText("Уничтожить процесс");
terminateProc.addListener(SWT.Selection, event -> {
if (selectedProcess != null) {
terminate(selectedProcess);
updateTree();
caServersTable.refresh();
}
});
ToolItem cancelProc = new ToolItem(pcToolBar, SWT.PUSH);
cancelProc.setText("Послать сигнал отмены процесса");
cancelProc.addListener(SWT.Selection, event -> {
if (selectedProcess != null) {
cancel(selectedProcess);
updateTree();
caServersTable.refresh();
}
});
procText = new Text(procComposite, SWT.MULTI | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);
procText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
procText.setBackground(composite.getDisplay().getSystemColor(SWT.COLOR_WHITE));
}
}
caTreeSf.setWeights(VERTICAL_WEIGHTS);
}
currentActivitySf.setWeights(HORIZONTAL_WEIGHTS);
currentActivityTi.setControl(currentActivitySf);
}
TabItem blocksHistoryTi = new TabItem(tabPanel, SWT.NONE);
{
blocksHistoryTi.setText("История блокировок");
SashForm blocksHistorySf = new SashForm(tabPanel, SWT.HORIZONTAL);
{
blocksHistorySf.setLayout(gridLayout);
blocksHistorySf.setLayoutData(gridData);
blocksHistorySf.SASH_WIDTH = SASH_WIDTH;
blocksHistorySf.setBackground(topComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
bhServersTable = new TableViewer(blocksHistorySf, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
{
bhServersTable.getTable().setHeaderVisible(true);
bhServersTable.getTable().setLinesVisible(true);
bhServersTable.getTable().setLayoutData(gridData);
TableViewerColumn serversTc = new TableViewerColumn(bhServersTable, SWT.NONE);
serversTc.getColumn().setText("Сервер");
serversTc.getColumn().setWidth(200);
bhServersTable.setContentProvider(new DbcDataListContentProvider());
bhServersTable.setLabelProvider(new DbcDataListLabelProvider());
}
bhMainTree = new TreeViewer(blocksHistorySf, SWT.VIRTUAL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
{
bhMainTree.getTree().setHeaderVisible(true);
bhMainTree.getTree().setLinesVisible(true);
bhMainTree.getTree().setLayoutData(gridData);
for(int i = 0; i < caMainTreeColsName.length; i++) {
TreeViewerColumn treeColumn = new TreeViewerColumn(bhMainTree, SWT.NONE);
treeColumn.getColumn().setText(caMainTreeColsName[i]);
treeColumn.getColumn().setWidth(caMainTreeColsSize[i]);
}
bhMainTree.setContentProvider(new ProcessTreeContentProvider());
bhMainTree.setLabelProvider(new ProcessTreeLabelProvider());
}
}
blocksHistorySf.setWeights(HORIZONTAL_WEIGHTS);
blocksHistoryTi.setControl(blocksHistorySf);
}
}
Composite logComposite = new Composite(verticalSf, SWT.NONE);
{
logComposite.setLayout(gridLayout);
}
verticalSf.setWeights(VERTICAL_WEIGHTS);
UIAppender uiAppender = new UIAppender(logComposite);
uiAppender.setThreshold(Level.INFO);
Logger.getRootLogger().addAppender(uiAppender);
Composite statusBar = new Composite(composite, SWT.NONE);
{
statusBar.setLayout(gridLayout);
statusBar.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
Label appVersionLabel = new Label(statusBar, SWT.HORIZONTAL);
appVersionLabel.setText("PgSqlBlocks v." + getAppVersion());
}
}
caMainTree.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
if (!caMainTree.getSelection().isEmpty()) {
IStructuredSelection selected = (IStructuredSelection) event.getSelection();
selectedProcess = (Process) selected.getFirstElement();
if(!procComposite.isVisible()) {
procComposite.setVisible(true);
caTreeSf.layout(true, true);
}
procText.setText(String.format("pid=%s%n%s", selectedProcess.getPid(), selectedProcess.getQuery()));
}
}
});
caServersTable.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
if (!caServersTable.getSelection().isEmpty()) {
IStructuredSelection selected = (IStructuredSelection) event.getSelection();
selectedDbcData = (DbcData) selected.getFirstElement();
if(procComposite.isVisible()) {
procComposite.setVisible(false);
caTreeSf.layout(false, false);
}
if (selectedDbcData != null &&
(selectedDbcData.getStatus() == DbcStatus.ERROR ||
selectedDbcData.getStatus() == DbcStatus.DISABLED)) {
deleteDB.setEnabled(true);
editDB.setEnabled(true);
connectDB.setEnabled(true);
disconnectDB.setEnabled(false);
} else {
deleteDB.setEnabled(false);
editDB.setEnabled(false);
connectDB.setEnabled(false);
disconnectDB.setEnabled(true);
}
if (selectedDbcData != null) {
updateTree();
}
updateTree();
}
}
});
for (TreeColumn column : caMainTree.getTree().getColumns()) {
column.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
caMainTree.getTree().setSortColumn(column);
column.setData(SORT_DIRECTION, ((SortDirection)column.getData(SORT_DIRECTION)).getOpposite());
sortDirection = (SortDirection)column.getData(SORT_DIRECTION);
caMainTree.getTree().setSortDirection(sortDirection.getSwtData());
sortColumn = SortColumn.valueOf((String)column.getData("colName"));
updateTree();
}
});
}
caServersTable.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
if (!caServersTable.getSelection().isEmpty()) {
IStructuredSelection selected = (IStructuredSelection) event.getSelection();
selectedDbcData = (DbcData) selected.getFirstElement();
selectedDbcData.connect();
deleteDB.setEnabled(false);
editDB.setEnabled(false);
connectDB.setEnabled(false);
disconnectDB.setEnabled(true);
updateTree();
caServersTable.refresh();
display.timerExec(1000, timer);
}
}
});
return parent;
}
protected ToolBarManager createToolBarManager(int style) {
ToolBarManager toolBarManager = new ToolBarManager(style);
Action addDb = new Action(Images.ADD_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.ADD_DATABASE))) {
@Override
public void run() {
addDbcDlg.open();
caServersTable.refresh();
}
};
toolBarManager.add(addDb);
deleteDB = new Action(Images.DELETE_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.DELETE_DATABASE))) {
@Override
public void run() {
boolean okPress = MessageDialog.openQuestion(shell,
"Подтверждение действия",
String.format("Вы действительно хотите удалить %s?", selectedDbcData.getName()));
if (okPress) {
dbcDataList.delete(selectedDbcData);
}
caServersTable.refresh();
}
};
deleteDB.setEnabled(false);
toolBarManager.add(deleteDB);
editDB = new Action(Images.EDIT_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.EDIT_DATABASE))) {
@Override
public void run() {
AddDbcDataDlg editDbcDlg = new AddDbcDataDlg(shell, selectedDbcData);
editDbcDlg.open();
caServersTable.refresh();
}
};
editDB.setEnabled(false);
toolBarManager.add(editDB);
toolBarManager.add(new Separator());
connectDB = new Action(Images.CONNECT_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.CONNECT_DATABASE))) {
@Override
public void run() {
selectedDbcData.connect();
deleteDB.setEnabled(false);
editDB.setEnabled(false);
connectDB.setEnabled(false);
disconnectDB.setEnabled(true);
updateTree();
caServersTable.refresh();
display.timerExec(1000, timer);
}
};
connectDB.setEnabled(false);
toolBarManager.add(connectDB);
disconnectDB = new Action(Images.DISCONNECT_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.DISCONNECT_DATABASE))) {
@Override
public void run() {
selectedDbcData.disconnect();
deleteDB.setEnabled(true);
editDB.setEnabled(true);
connectDB.setEnabled(true);
disconnectDB.setEnabled(false);
updateTree();
caServersTable.refresh();
}
};
disconnectDB.setEnabled(false);
toolBarManager.add(disconnectDB);
toolBarManager.add(new Separator());
Action update = new Action(Images.UPDATE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.UPDATE))) {
@Override
public void run() {
updateTree();
caServersTable.refresh();
}
};
toolBarManager.add(update);
autoUpdate = new Action(Images.AUTOUPDATE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.AUTOUPDATE))) {
@Override
public void run() {
if (autoUpdate.isChecked()) {
autoUpdateMode = true;
} else {
autoUpdateMode = false;
}
}
};
autoUpdate.setChecked(true);
toolBarManager.add(autoUpdate);
toolBarManager.add(new Separator());
onlyBlocked = new Action(Images.VIEW_ONLY_BLOCKED.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.VIEW_ONLY_BLOCKED))) {
@Override
public void run() {
if (onlyBlocked.isChecked()) {
onlyBlockedMode = true;
} else {
onlyBlockedMode = false;
}
updateTree();
}
};
onlyBlocked.setChecked(false);
toolBarManager.add(onlyBlocked);
Action exportBlocks = new Action(Images.EXPORT_BLOCKS.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.EXPORT_BLOCKS))) {
@Override
public void run() {
if (processTreeMap.keySet().stream()
.filter(dbcData -> dbcData.getStatus() == DbcStatus.BLOCKED).count() > 0) {
BlocksHistory.getInstance().save(processTreeMap);
LOG.info("Блокировка сохранена...");
} else {
LOG.info("Не найдено блокировок для сохранения");
}
}
};
toolBarManager.add(exportBlocks);
Action importBlocks = new Action(Images.IMPORT_BLOCKS.getDescription()) {
@Override
public void run() {
FileDialog dialog = new FileDialog(shell);
dialog.setFilterPath(PathBuilder.getInstance().getBlockHistoryDir().toString());
dialog.setText("Открыть историю блокировок");
dialog.setFilterExtensions(new String[]{"*.xml"});
ConcurrentMap<DbcData, Process> map = BlocksHistory.getInstance().open(dialog.open());
List<DbcData> blockedDbsData = new ArrayList<DbcData>();
for (Map.Entry<DbcData, Process> entry : map.entrySet())
{
bhMainTree.setInput(entry.getValue());
blockedDbsData.add(entry.getKey());
}
bhServersTable.setInput(blockedDbsData);
bhMainTree.refresh();
bhServersTable.refresh();
}
};
importBlocks.setImageDescriptor(ImageDescriptor.createFromImage(getImage(Images.IMPORT_BLOCKS)));
toolBarManager.add(importBlocks);
return toolBarManager;
}
private Image getImage(Images type) {
Image image = imagesMap.get(type.toString());
if (image == null) {
image = new Image(null, getClass().getClassLoader().getResourceAsStream(type.getImageAddr()));
imagesMap.put(type.toString(), image);
}
return image;
}
private String getAppVersion() {
URL manifestPath = MainForm.class.getClassLoader().getResource("META-INF/MANIFEST.MF");
Manifest manifest = null;
try {
manifest = new Manifest(manifestPath.openStream());
} catch (IOException e) {
LOG.error("Ошибка при чтении манифеста", e);
}
Attributes manifestAttributes = manifest.getMainAttributes();
String appVersion = manifestAttributes.getValue("Implementation-Version");
if(appVersion == null) {
return "";
}
return appVersion;
}
private Runnable timer = new Runnable() {
@Override
public void run() {
if (autoUpdateMode) {
updateTree();
display.timerExec(TIMER_INTERVAL * 1000, this);
}
updateTree();
caServersTable.refresh();
}
};
public void terminate(Process process) {
String term = "select pg_terminate_backend(?);";
boolean kill = false;
int pid = process.getPid();
try (PreparedStatement termPs = selectedDbcData.getConnection().prepareStatement(term);) {
termPs.setInt(1, pid);
try (ResultSet resultSet = termPs.executeQuery()) {
if (resultSet.next()) {
kill = resultSet.getBoolean(1);
}
}
} catch (SQLException e) {
selectedDbcData.setStatus(DbcStatus.ERROR);
LOG.error(selectedDbcData.getName() + " " + e.getMessage(), e);
}
if(kill) {
LOG.info(selectedDbcData.getName() + PID + pid + " is terminated.");
} else {
LOG.info(selectedDbcData.getName() + PID + pid + " is terminated failed.");
}
}
public void cancel(Process process) {
String cancel = "select pg_cancel_backend(?);";
int pid = process.getPid();
boolean kill = false;
try (PreparedStatement cancelPs = selectedDbcData.getConnection().prepareStatement(cancel);) {
cancelPs.setInt(1, pid);
try (ResultSet resultSet = cancelPs.executeQuery()) {
if (resultSet.next()) {
kill = resultSet.getBoolean(1);
}
}
} catch (SQLException e) {
selectedDbcData.setStatus(DbcStatus.ERROR);
LOG.error(selectedDbcData.getName() + " " + e.getMessage(), e);
}
if(kill) {
LOG.info(selectedDbcData.getName() + PID + pid + " is canceled.");
} else {
LOG.info(selectedDbcData.getName() + PID + pid + " is canceled failed.");
}
}
private void updateTree() {
if (selectedDbcData != null) {
if (onlyBlockedMode) {
caMainTree.setInput(getOnlyBlockedProcessTree(selectedDbcData));
} else {
caMainTree.setInput(getProcessTree(selectedDbcData));
}
}
caMainTree.refresh();
bhMainTree.refresh();
caServersTable.refresh();
}
}
| src/main/java/ru/taximaxim/pgsqlblocks/MainForm.java | package ru.taximaxim.pgsqlblocks;
import java.io.IOException;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Image;
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.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.TreeColumn;
import ru.taximaxim.pgsqlblocks.dbcdata.DbcData;
import ru.taximaxim.pgsqlblocks.dbcdata.DbcDataListBuilder;
import ru.taximaxim.pgsqlblocks.dbcdata.DbcDataListContentProvider;
import ru.taximaxim.pgsqlblocks.dbcdata.DbcDataListLabelProvider;
import ru.taximaxim.pgsqlblocks.dbcdata.DbcStatus;
import ru.taximaxim.pgsqlblocks.process.Process;
import ru.taximaxim.pgsqlblocks.process.ProcessTreeBuilder;
import ru.taximaxim.pgsqlblocks.process.ProcessTreeContentProvider;
import ru.taximaxim.pgsqlblocks.process.ProcessTreeLabelProvider;
import ru.taximaxim.pgsqlblocks.utils.Images;
import ru.taximaxim.pgsqlblocks.utils.PathBuilder;
public class MainForm extends ApplicationWindow {
private static final Logger LOG = Logger.getLogger(MainForm.class);
private static final String APP_NAME = "pgSqlBlocks";
private static final String SORT_DIRECTION = "sortDirection";
private static final String PID = " pid=";
private static final int ZERO_MARGIN = 0;
private static final int[] VERTICAL_WEIGHTS = new int[] {80, 20};
private static final int[] HORIZONTAL_WEIGHTS = new int[] {12, 88};
private static final int SASH_WIDTH = 2;
private static final int TIMER_INTERVAL = 10;
private static Display display;
private static Shell shell;
private DbcData selectedDbcData;
private Process selectedProcess;
private Text procText;
private SashForm caTreeSf;
private TableViewer caServersTable;
private TreeViewer caMainTree;
private Composite procComposite;
private TableViewer bhServersTable;
private TreeViewer bhMainTree;
private Action deleteDB;
private Action editDB;
private Action connectDB;
private Action disconnectDB;
private Action autoUpdate;
private Action onlyBlocked;
private AddDbcDataDlg addDbcDlg;
private boolean autoUpdateMode = true;
private boolean onlyBlockedMode = false;
private SortColumn sortColumn = SortColumn.BLOCKED_COUNT;
private SortDirection sortDirection = SortDirection.UP;
private DbcDataListBuilder dbcDataList = DbcDataListBuilder.getInstance();
private ConcurrentMap<String, Image> imagesMap = new ConcurrentHashMap<String, Image>();
private ConcurrentMap<DbcData, ProcessTreeBuilder> processTreeMap = new ConcurrentHashMap<>();
private ConcurrentMap<DbcData, ProcessTreeBuilder> blockedProcessTreeMap = new ConcurrentHashMap<>();
private int[] caMainTreeColsSize = new int[]{80, 110, 150, 110, 110, 110, 145, 145, 145, 55, 145, 70, 65, 150, 80};
private String[] caMainTreeColsName = new String[]{
"pid", "blocked_count", "application_name", "datname", "usename", "client", "backend_start", "query_start",
"xact_stat", "state", "state_change", "blocked", "waiting", "query" , "slowquery"};
private String[] caColName = {"PID", "BLOCKED_COUNT", "APPLICATION_NAME", "DATNAME", "USENAME", "CLIENT", "BACKEND_START", "QUERY_START",
"XACT_STAT", "STATE", "STATE_CHANGE", "BLOCKED", "WAITING", "QUERY", "SLOWQUERY"};
public Process getProcessTree(DbcData dbcData) {
ProcessTreeBuilder processTree = processTreeMap.get(dbcData);
if(processTree == null){
processTree = new ProcessTreeBuilder(dbcData);
processTreeMap.put(dbcData, processTree);
}
Process rootProcess = processTree.getProcessTree();
processTree.processSort(rootProcess, sortColumn, sortDirection);
return rootProcess;
}
public Process getOnlyBlockedProcessTree(DbcData dbcData) {
ProcessTreeBuilder processTree = blockedProcessTreeMap.get(dbcData);
if(processTree == null){
processTree = new ProcessTreeBuilder(dbcData);
blockedProcessTreeMap.put(dbcData, processTree);
}
return processTree.getOnlyBlockedProcessTree();
}
public static void main(String[] args) {
try {
Logger rootLogger = Logger.getRootLogger();
rootLogger.setLevel(Level.INFO);
PatternLayout layout = new PatternLayout("%d{ISO8601} [%t] %-5p %c %x - %m%n");
rootLogger.addAppender(new ConsoleAppender(layout));
try {
DailyRollingFileAppender fileAppender = new DailyRollingFileAppender(layout, PathBuilder.getInstance().getLogsPath().toString(), "yyyy-MM-dd");
rootLogger.addAppender(fileAppender);
} catch (IOException e) {
LOG.error("Произошла ошибка при настройке логирования:", e);
}
display = new Display();
shell = new Shell(display);
MainForm wwin = new MainForm(shell);
wwin.setBlockOnOpen(true);
wwin.open();
Display.getCurrent().dispose();
} catch (Exception e) {
LOG.error("Произошла ошибка:", e);
}
}
public MainForm(Shell shell) {
super(shell);
addToolBar(SWT.RIGHT | SWT.FLAT);
}
@Override
protected void constrainShellSize() {
super.constrainShellSize();
getShell().setMaximized( true );
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(APP_NAME);
}
@Override
protected Control createContents(Composite parent)
{
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
addDbcDlg = new AddDbcDataDlg(shell);
GridLayout gridLayout = new GridLayout();
gridLayout.marginHeight = ZERO_MARGIN;
gridLayout.marginWidth = ZERO_MARGIN;
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
SashForm verticalSf = new SashForm(composite, SWT.VERTICAL);
{
verticalSf.setLayout(gridLayout);
verticalSf.setLayoutData(gridData);
verticalSf.SASH_WIDTH = SASH_WIDTH;
verticalSf.setBackground(composite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
Composite topComposite = new Composite(verticalSf, SWT.NONE);
topComposite.setLayout(gridLayout);
TabFolder tabPanel = new TabFolder(topComposite, SWT.BORDER);
{
tabPanel.setLayoutData(gridData);
TabItem currentActivityTi = new TabItem(tabPanel, SWT.NONE);
{
currentActivityTi.setText("Текущая активность");
SashForm currentActivitySf = new SashForm(tabPanel, SWT.HORIZONTAL);
{
currentActivitySf.setLayout(gridLayout);
currentActivitySf.setLayoutData(gridData);
currentActivitySf.SASH_WIDTH = SASH_WIDTH;
currentActivitySf.setBackground(topComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
caServersTable = new TableViewer(currentActivitySf, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
{
caServersTable.getTable().setHeaderVisible(true);
caServersTable.getTable().setLinesVisible(true);
caServersTable.getTable().setLayoutData(gridData);
TableViewerColumn tvColumn = new TableViewerColumn(caServersTable, SWT.NONE);
tvColumn.getColumn().setText("Сервер");
tvColumn.getColumn().setWidth(200);
caServersTable.setContentProvider(new DbcDataListContentProvider());
caServersTable.setLabelProvider(new DbcDataListLabelProvider());
caServersTable.setInput(dbcDataList.getList());
caServersTable.refresh();
}
caTreeSf = new SashForm(currentActivitySf, SWT.VERTICAL);
{
caMainTree = new TreeViewer(caTreeSf, SWT.VIRTUAL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
caMainTree.getTree().setHeaderVisible(true);
caMainTree.getTree().setLinesVisible(true);
caMainTree.getTree().setLayoutData(gridData);
for(int i=0;i<caMainTreeColsName.length;i++) {
TreeViewerColumn treeColumn = new TreeViewerColumn(caMainTree, SWT.NONE);
treeColumn.getColumn().setText(caMainTreeColsName[i]);
treeColumn.getColumn().setWidth(caMainTreeColsSize[i]);
treeColumn.getColumn().setData("colName",caColName[i]);
treeColumn.getColumn().setData(SORT_DIRECTION, SortDirection.UP);
}
caMainTree.setContentProvider(new ProcessTreeContentProvider());
caMainTree.setLabelProvider(new ProcessTreeLabelProvider());
procComposite = new Composite(caTreeSf, SWT.BORDER);
{
procComposite.setLayout(gridLayout);
GridData procCompositeGd = new GridData(SWT.FILL, SWT.FILL, true, true);
procComposite.setLayoutData(procCompositeGd);
procComposite.setVisible(false);
ToolBar pcToolBar = new ToolBar(procComposite, SWT.FLAT | SWT.RIGHT);
pcToolBar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
ToolItem terminateProc = new ToolItem(pcToolBar, SWT.PUSH);
terminateProc.setText("Уничтожить процесс");
terminateProc.addListener(SWT.Selection, event -> {
if (selectedProcess != null) {
terminate(selectedProcess);
updateTree();
caServersTable.refresh();
}
});
ToolItem cancelProc = new ToolItem(pcToolBar, SWT.PUSH);
cancelProc.setText("Послать сигнал отмены процесса");
cancelProc.addListener(SWT.Selection, event -> {
if (selectedProcess != null) {
cancel(selectedProcess);
updateTree();
caServersTable.refresh();
}
});
procText = new Text(procComposite, SWT.MULTI | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);
procText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
procText.setBackground(composite.getDisplay().getSystemColor(SWT.COLOR_WHITE));
}
}
caTreeSf.setWeights(VERTICAL_WEIGHTS);
}
currentActivitySf.setWeights(HORIZONTAL_WEIGHTS);
currentActivityTi.setControl(currentActivitySf);
}
TabItem blocksHistoryTi = new TabItem(tabPanel, SWT.NONE);
{
blocksHistoryTi.setText("История блокировок");
SashForm blocksHistorySf = new SashForm(tabPanel, SWT.HORIZONTAL);
{
blocksHistorySf.setLayout(gridLayout);
blocksHistorySf.setLayoutData(gridData);
blocksHistorySf.SASH_WIDTH = SASH_WIDTH;
blocksHistorySf.setBackground(topComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
bhServersTable = new TableViewer(blocksHistorySf, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
{
bhServersTable.getTable().setHeaderVisible(true);
bhServersTable.getTable().setLinesVisible(true);
bhServersTable.getTable().setLayoutData(gridData);
TableViewerColumn serversTc = new TableViewerColumn(bhServersTable, SWT.NONE);
serversTc.getColumn().setText("Сервер");
serversTc.getColumn().setWidth(200);
bhServersTable.setContentProvider(new DbcDataListContentProvider());
bhServersTable.setLabelProvider(new DbcDataListLabelProvider());
}
bhMainTree = new TreeViewer(blocksHistorySf, SWT.VIRTUAL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
{
bhMainTree.getTree().setHeaderVisible(true);
bhMainTree.getTree().setLinesVisible(true);
bhMainTree.getTree().setLayoutData(gridData);
for(int i = 0; i < caMainTreeColsName.length; i++) {
TreeViewerColumn treeColumn = new TreeViewerColumn(bhMainTree, SWT.NONE);
treeColumn.getColumn().setText(caMainTreeColsName[i]);
treeColumn.getColumn().setWidth(caMainTreeColsSize[i]);
}
bhMainTree.setContentProvider(new ProcessTreeContentProvider());
bhMainTree.setLabelProvider(new ProcessTreeLabelProvider());
}
}
blocksHistorySf.setWeights(HORIZONTAL_WEIGHTS);
blocksHistoryTi.setControl(blocksHistorySf);
}
}
Composite logComposite = new Composite(verticalSf, SWT.NONE);
{
logComposite.setLayout(gridLayout);
}
verticalSf.setWeights(VERTICAL_WEIGHTS);
UIAppender uiAppender = new UIAppender(logComposite);
uiAppender.setThreshold(Level.INFO);
Logger.getRootLogger().addAppender(uiAppender);
Composite statusBar = new Composite(composite, SWT.NONE);
{
statusBar.setLayout(gridLayout);
statusBar.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
Label appVersionLabel = new Label(statusBar, SWT.HORIZONTAL);
appVersionLabel.setText("PgSqlBlocks v." + getAppVersion());
}
}
caMainTree.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
if (!caMainTree.getSelection().isEmpty()) {
IStructuredSelection selected = (IStructuredSelection) event.getSelection();
selectedProcess = (Process) selected.getFirstElement();
if(!procComposite.isVisible()) {
procComposite.setVisible(true);
caTreeSf.layout(true, true);
}
procText.setText(String.format("pid=%s%n%s", selectedProcess.getPid(), selectedProcess.getQuery()));
}
}
});
caServersTable.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
if (!caServersTable.getSelection().isEmpty()) {
IStructuredSelection selected = (IStructuredSelection) event.getSelection();
selectedDbcData = (DbcData) selected.getFirstElement();
if(procComposite.isVisible()) {
procComposite.setVisible(false);
caTreeSf.layout(false, false);
}
if (selectedDbcData != null &&
(selectedDbcData.getStatus() == DbcStatus.ERROR ||
selectedDbcData.getStatus() == DbcStatus.DISABLED)) {
deleteDB.setEnabled(true);
editDB.setEnabled(true);
connectDB.setEnabled(true);
disconnectDB.setEnabled(false);
} else {
deleteDB.setEnabled(false);
editDB.setEnabled(false);
connectDB.setEnabled(false);
disconnectDB.setEnabled(true);
}
if (selectedDbcData != null) {
updateTree();
}
updateTree();
}
}
});
for (TreeColumn column : caMainTree.getTree().getColumns()) {
column.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
caMainTree.getTree().setSortColumn(column);
column.setData(SORT_DIRECTION, ((SortDirection)column.getData(SORT_DIRECTION)).getOpposite());
sortDirection = (SortDirection)column.getData(SORT_DIRECTION);
caMainTree.getTree().setSortDirection(sortDirection.getSwtData());
sortColumn = SortColumn.valueOf((String)column.getData("colName"));
updateTree();
}
});
}
caServersTable.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
if (!caServersTable.getSelection().isEmpty()) {
IStructuredSelection selected = (IStructuredSelection) event.getSelection();
selectedDbcData = (DbcData) selected.getFirstElement();
selectedDbcData.connect();
updateTree();
}
}
});
return parent;
}
protected ToolBarManager createToolBarManager(int style) {
ToolBarManager toolBarManager = new ToolBarManager(style);
Action addDb = new Action(Images.ADD_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.ADD_DATABASE))) {
@Override
public void run() {
addDbcDlg.open();
caServersTable.refresh();
}
};
toolBarManager.add(addDb);
deleteDB = new Action(Images.DELETE_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.DELETE_DATABASE))) {
@Override
public void run() {
boolean okPress = MessageDialog.openQuestion(shell,
"Подтверждение действия",
String.format("Вы действительно хотите удалить %s?", selectedDbcData.getName()));
if (okPress) {
dbcDataList.delete(selectedDbcData);
}
caServersTable.refresh();
}
};
deleteDB.setEnabled(false);
toolBarManager.add(deleteDB);
editDB = new Action(Images.EDIT_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.EDIT_DATABASE))) {
@Override
public void run() {
AddDbcDataDlg editDbcDlg = new AddDbcDataDlg(shell, selectedDbcData);
editDbcDlg.open();
caServersTable.refresh();
}
};
editDB.setEnabled(false);
toolBarManager.add(editDB);
toolBarManager.add(new Separator());
connectDB = new Action(Images.CONNECT_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.CONNECT_DATABASE))) {
@Override
public void run() {
selectedDbcData.connect();
deleteDB.setEnabled(false);
editDB.setEnabled(false);
connectDB.setEnabled(false);
disconnectDB.setEnabled(true);
updateTree();
caServersTable.refresh();
display.timerExec(1000, timer);
}
};
connectDB.setEnabled(false);
toolBarManager.add(connectDB);
disconnectDB = new Action(Images.DISCONNECT_DATABASE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.DISCONNECT_DATABASE))) {
@Override
public void run() {
selectedDbcData.disconnect();
deleteDB.setEnabled(true);
editDB.setEnabled(true);
connectDB.setEnabled(true);
disconnectDB.setEnabled(false);
updateTree();
caServersTable.refresh();
}
};
disconnectDB.setEnabled(false);
toolBarManager.add(disconnectDB);
toolBarManager.add(new Separator());
Action update = new Action(Images.UPDATE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.UPDATE))) {
@Override
public void run() {
updateTree();
caServersTable.refresh();
}
};
toolBarManager.add(update);
autoUpdate = new Action(Images.AUTOUPDATE.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.AUTOUPDATE))) {
@Override
public void run() {
if (autoUpdate.isChecked()) {
autoUpdateMode = true;
} else {
autoUpdateMode = false;
}
}
};
autoUpdate.setChecked(true);
toolBarManager.add(autoUpdate);
toolBarManager.add(new Separator());
onlyBlocked = new Action(Images.VIEW_ONLY_BLOCKED.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.VIEW_ONLY_BLOCKED))) {
@Override
public void run() {
if (onlyBlocked.isChecked()) {
onlyBlockedMode = true;
} else {
onlyBlockedMode = false;
}
updateTree();
}
};
onlyBlocked.setChecked(false);
toolBarManager.add(onlyBlocked);
Action exportBlocks = new Action(Images.EXPORT_BLOCKS.getDescription(),
ImageDescriptor.createFromImage(getImage(Images.EXPORT_BLOCKS))) {
@Override
public void run() {
if (processTreeMap.keySet().stream()
.filter(dbcData -> dbcData.getStatus() == DbcStatus.BLOCKED).count() > 0) {
BlocksHistory.getInstance().save(processTreeMap);
LOG.info("Блокировка сохранена...");
} else {
LOG.info("Не найдено блокировок для сохранения");
}
}
};
toolBarManager.add(exportBlocks);
Action importBlocks = new Action(Images.IMPORT_BLOCKS.getDescription()) {
@Override
public void run() {
FileDialog dialog = new FileDialog(shell);
dialog.setFilterPath(PathBuilder.getInstance().getBlockHistoryDir().toString());
dialog.setText("Открыть историю блокировок");
dialog.setFilterExtensions(new String[]{"*.xml"});
ConcurrentMap<DbcData, Process> map = BlocksHistory.getInstance().open(dialog.open());
List<DbcData> blockedDbsData = new ArrayList<DbcData>();
for (Map.Entry<DbcData, Process> entry : map.entrySet())
{
bhMainTree.setInput(entry.getValue());
blockedDbsData.add(entry.getKey());
}
bhServersTable.setInput(blockedDbsData);
bhMainTree.refresh();
bhServersTable.refresh();
}
};
importBlocks.setImageDescriptor(ImageDescriptor.createFromImage(getImage(Images.IMPORT_BLOCKS)));
toolBarManager.add(importBlocks);
return toolBarManager;
}
private Image getImage(Images type) {
Image image = imagesMap.get(type.toString());
if (image == null) {
image = new Image(null, getClass().getClassLoader().getResourceAsStream(type.getImageAddr()));
imagesMap.put(type.toString(), image);
}
return image;
}
private String getAppVersion() {
URL manifestPath = MainForm.class.getClassLoader().getResource("META-INF/MANIFEST.MF");
Manifest manifest = null;
try {
manifest = new Manifest(manifestPath.openStream());
} catch (IOException e) {
LOG.error("Ошибка при чтении манифеста", e);
}
Attributes manifestAttributes = manifest.getMainAttributes();
String appVersion = manifestAttributes.getValue("Implementation-Version");
if(appVersion == null) {
return "";
}
return appVersion;
}
private Runnable timer = new Runnable() {
@Override
public void run() {
if (autoUpdateMode) {
updateTree();
display.timerExec(TIMER_INTERVAL * 1000, this);
}
updateTree();
caServersTable.refresh();
}
};
public void terminate(Process process) {
String term = "select pg_terminate_backend(?);";
boolean kill = false;
int pid = process.getPid();
try (PreparedStatement termPs = selectedDbcData.getConnection().prepareStatement(term);) {
termPs.setInt(1, pid);
try (ResultSet resultSet = termPs.executeQuery()) {
if (resultSet.next()) {
kill = resultSet.getBoolean(1);
}
}
} catch (SQLException e) {
selectedDbcData.setStatus(DbcStatus.ERROR);
LOG.error(selectedDbcData.getName() + " " + e.getMessage(), e);
}
if(kill) {
LOG.info(selectedDbcData.getName() + PID + pid + " is terminated.");
} else {
LOG.info(selectedDbcData.getName() + PID + pid + " is terminated failed.");
}
}
public void cancel(Process process) {
String cancel = "select pg_cancel_backend(?);";
int pid = process.getPid();
boolean kill = false;
try (PreparedStatement cancelPs = selectedDbcData.getConnection().prepareStatement(cancel);) {
cancelPs.setInt(1, pid);
try (ResultSet resultSet = cancelPs.executeQuery()) {
if (resultSet.next()) {
kill = resultSet.getBoolean(1);
}
}
} catch (SQLException e) {
selectedDbcData.setStatus(DbcStatus.ERROR);
LOG.error(selectedDbcData.getName() + " " + e.getMessage(), e);
}
if(kill) {
LOG.info(selectedDbcData.getName() + PID + pid + " is canceled.");
} else {
LOG.info(selectedDbcData.getName() + PID + pid + " is canceled failed.");
}
}
private void updateTree() {
if (selectedDbcData != null) {
if (onlyBlockedMode) {
caMainTree.setInput(getOnlyBlockedProcessTree(selectedDbcData));
} else {
caMainTree.setInput(getProcessTree(selectedDbcData));
}
}
caMainTree.refresh();
bhMainTree.refresh();
caServersTable.refresh();
}
}
| doubleclick | src/main/java/ru/taximaxim/pgsqlblocks/MainForm.java | doubleclick | <ide><path>rc/main/java/ru/taximaxim/pgsqlblocks/MainForm.java
<ide> private static final int[] VERTICAL_WEIGHTS = new int[] {80, 20};
<ide> private static final int[] HORIZONTAL_WEIGHTS = new int[] {12, 88};
<ide> private static final int SASH_WIDTH = 2;
<del> private static final int TIMER_INTERVAL = 10;
<add> private static final int TIMER_INTERVAL = 2;
<ide>
<ide> private static Display display;
<ide> private static Shell shell;
<ide> IStructuredSelection selected = (IStructuredSelection) event.getSelection();
<ide> selectedDbcData = (DbcData) selected.getFirstElement();
<ide> selectedDbcData.connect();
<add> deleteDB.setEnabled(false);
<add> editDB.setEnabled(false);
<add> connectDB.setEnabled(false);
<add> disconnectDB.setEnabled(true);
<ide> updateTree();
<add> caServersTable.refresh();
<add> display.timerExec(1000, timer);
<ide> }
<ide> }
<ide> }); |
|
Java | agpl-3.0 | 5bab11a827e163674ab4fd556943ad9f205a3a26 | 0 | maurizi/otm-android,OpenTreeMap/otm-android,maurizi/otm-android,OpenTreeMap/otm-android,OpenTreeMap/otm-android,maurizi/otm-android | package org.azavea.otm.ui;
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.TileOverlay;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.joelapenna.foursquared.widget.SegmentedButton;
import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.azavea.map.WMSTileProvider;
import org.azavea.otm.App;
import org.azavea.otm.R;
import org.azavea.otm.data.Geometry;
import org.azavea.otm.data.Plot;
import org.azavea.otm.data.PlotContainer;
import org.azavea.otm.data.Tree;
import org.azavea.otm.map.TileProviderFactory;
import org.azavea.otm.rest.RequestGenerator;
import org.azavea.otm.rest.handlers.ContainerRestHandler;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
//import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainMapActivity extends MapActivity{
private static LatLng START_POS;
private static final int DEFAULT_ZOOM_LEVEL = 12;
private static final int FILTER_INTENT = 1;
private static final int INFO_INTENT = 2;
// modes for the add marker feature
private static final int STEP1 = 1;
private static final int STEP2 = 2;
private static final int CANCEL = 3;
private static final int FINISH = 4;
private TextView plotSpeciesView;
private TextView plotAddressView;
private TextView plotDiameterView;
private TextView plotUpdatedByView;
private ImageView plotImageView;
private RelativeLayout plotPopup;
private Plot currentPlot; // The Plot we're currently showing a pop-up for, if any
private Marker plotMarker;
private GoogleMap mMap;
private TextView filterDisplay;
TileOverlay filterTileOverlay;
WMSTileProvider filterTileProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
START_POS = App.getStartPos();
setContentView(R.layout.activity_map_display_2);
filterDisplay = (TextView)findViewById(R.id.filterDisplay);
setUpMapIfNeeded();
plotPopup = (RelativeLayout) findViewById(R.id.plotPopup);
setPopupViews();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setTreeAddMode(CANCEL);
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {@link #setUpMap()} once when {@link #mMap} is not null.
* <p>
* If it isn't installed {@link SupportMapFragment} (and
* {@link com.google.android.gms.maps.MapView
* MapView}) will show a prompt for the user to install/update the Google Play services APK on
* their device.
* <p>
* A user can return to this Activity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the Activity may not have been
* completely destroyed during this process (it is likely that it would only be stopped or
* paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
* {@link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
} else {
Toast.makeText(MainMapActivity.this, "Google play services library not found.", Toast.LENGTH_LONG).show();
Log.e(App.LOG_TAG, "Map was null!");
}
}
}
private void setUpMap() {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(START_POS, DEFAULT_ZOOM_LEVEL));
/* This is the base tree layer using wms/geoserver for debugging purposes.
In production we use tilecache.
TileProvider wmsTileProvider = TileProviderFactory.getWmsTileProvider();
TileOverlay wmsTileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(wmsTileProvider));
wmsTileOverlay.setZIndex(50);
*/
TileProvider treeTileProvider = TileProviderFactory.getTileCacheTileProvider();
TileOverlay treeTileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(treeTileProvider));
treeTileOverlay.setZIndex(50);
// Set up the filter layer
filterTileProvider = TileProviderFactory.getFilterLayerTileProvider();
filterTileProvider.setCql("1=0");
filterTileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(filterTileProvider));
filterTileOverlay.setZIndex(100);
// Set up the default click listener
mMap.setOnMapClickListener(showPopupMapClickListener);
setTreeAddMode(CANCEL);
setUpBasemapControls();
}
public void showPopup(Plot plot) {
//set default text
plotDiameterView.setText(getString(R.string.dbh_missing));
plotSpeciesView.setText(getString(R.string.species_missing));
plotAddressView.setText(getString(R.string.address_missing));
plotImageView.setImageResource(R.drawable.ic_action_search);
try {
plotUpdatedByView.setText(plot.getLastUpdatedBy());
if (plot.getAddress().length() != 0) {
plotAddressView.setText(plot.getAddress());
}
Tree tree = plot.getTree();
if (tree != null) {
String speciesName;
try {
speciesName = tree.getSpeciesName();
} catch (JSONException e) {
speciesName = "No species name";
}
plotSpeciesView.setText(speciesName);
if (tree.getDbh() != 0) {
plotDiameterView.setText(String.valueOf(tree.getDbh()) + " " + getString(R.string.dbh_units));
}
showImage(plot);
}
LatLng position = new LatLng(plot.getGeometry().getLat(), plot.getGeometry().getLon());
mMap.animateCamera(CameraUpdateFactory.newLatLng(position));
if (plotMarker != null) {
plotMarker.remove();
}
plotMarker = mMap.addMarker(new MarkerOptions().position(position).title("").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mapmarker)));
} catch (JSONException e) {
e.printStackTrace();
}
currentPlot = plot;
plotPopup.setVisibility(View.VISIBLE);
}
public void hidePopup() {
RelativeLayout plotPopup = (RelativeLayout) findViewById(R.id.plotPopup);
plotPopup.setVisibility(View.INVISIBLE);
currentPlot = null;
}
private void setPopupViews() {
plotSpeciesView = (TextView) findViewById(R.id.plotSpecies);
plotAddressView = (TextView) findViewById(R.id.plotAddress);
plotDiameterView = (TextView) findViewById(R.id.plotDiameter);
plotUpdatedByView = (TextView) findViewById(R.id.plotUpdatedBy);
plotImageView = (ImageView) findViewById(R.id.plotImage);
}
private void showImage(Plot plot) throws JSONException {
plot.getTreePhoto(new BinaryHttpResponseHandler(Plot.IMAGE_TYPES) {
@Override
public void onSuccess(byte[] imageData) {
Bitmap scaledImage = Plot.createTreeThumbnail(imageData);
ImageView plotImage = (ImageView) findViewById(R.id.plotImage);
plotImage.setImageBitmap(scaledImage);
}
@Override
public void onFailure(Throwable e, byte[] imageData) {
// Log the error, but not important enough to bother the user
Log.e(App.LOG_TAG, "Could not retreive tree image", e);
}
});
}
// onClick handler for tree-details pop-up touch event
public void showFullTreeInfo(View view) {
// Show TreeInfoDisplay with current plot
Intent viewPlot = new Intent(MainMapActivity.this, TreeInfoDisplay.class);
viewPlot.putExtra("plot", currentPlot.getData().toString());
if (App.getLoginManager().isLoggedIn()) {
viewPlot.putExtra("user", App.getLoginManager().loggedInUser.getData().toString());
}
startActivityForResult(viewPlot, INFO_INTENT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_map_display, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menu_filter) {
Intent filter = new Intent(this, FilterDisplay.class);
startActivityForResult(filter, FILTER_INTENT);
} else if (itemId == R.id.menu_add) {
if(App.getLoginManager().isLoggedIn()) {
setTreeAddMode(CANCEL);
setTreeAddMode(STEP1);
} else {
startActivity(new Intent(MainMapActivity.this, LoginActivity.class));
}
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case FILTER_INTENT:
if (resultCode == Activity.RESULT_OK) {
RequestParams activeFilters = App.getFilterManager().getActiveFiltersAsRequestParams();
setFilterDisplay(App.getFilterManager().getActiveFilterDisplay());
if (activeFilters.toString().equals("")) {
filterTileProvider.setCql("");
filterTileOverlay.clearTileCache();
} else {
RequestGenerator rc = new RequestGenerator();
rc.getCqlForFilters(activeFilters, handleNewFilterCql);
}
}
break;
case INFO_INTENT:
if (resultCode == TreeDisplay.RESULT_PLOT_EDITED) {
try {
// The plot was updated, so update the pop-up with any new data
Plot updatedPlot = new Plot();
String plotJSON = data.getExtras().getString("plot");
updatedPlot.setData(new JSONObject(plotJSON));
showPopup(updatedPlot);
} catch (JSONException e) {
Log.e(App.LOG_TAG, "Unable to deserialze updated plot for map popup", e);
hidePopup();
}
} else if (resultCode == TreeDisplay.RESULT_PLOT_DELETED) {
hidePopup();
// TODO: Do we need to refresh the map tile?
}
break;
}
}
private void setFilterDisplay(String activeFilterDisplay) {
if (activeFilterDisplay.equals("") || activeFilterDisplay == null) {
filterDisplay.setVisibility(View.GONE);
} else {
filterDisplay.setText(getString(R.string.filter_display_label) + " " + activeFilterDisplay);
filterDisplay.setVisibility(View.VISIBLE);
}
}
// onClick handler for "My Location" button
public void showMyLocation(View view) {
Context context = MainMapActivity.this;
LocationManager locationManager =
(LocationManager) context.getSystemService(context.LOCATION_SERVICE);
if (locationManager != null) {
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(crit, true);
Location lastKnownLocation = locationManager.getLastKnownLocation(provider);
if (lastKnownLocation != null) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude()
), DEFAULT_ZOOM_LEVEL+2));
} else {
Toast.makeText(MainMapActivity.this, "Could not determine current location.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainMapActivity.this, "Could not determine current location.", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onBackPressed() {
hidePopup();
setTreeAddMode(CANCEL);
}
// call backs for base layer switcher buttons
public void hybridBaselayer(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
public void mapBaselayer(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
public void satelliteBaselayer(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
// Map click listener for normal view mode
private OnMapClickListener showPopupMapClickListener = new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
Log.d("TREE_CLICK", "(" + point.latitude + "," + point.longitude + ")");
final ProgressDialog dialog = ProgressDialog.show(MainMapActivity.this, "",
"Loading. Please wait...", true);
dialog.show();
final RequestGenerator rg = new RequestGenerator();
rg.getPlotsNearLocation(
point.latitude,
point.longitude,
new ContainerRestHandler<PlotContainer>(new PlotContainer()) {
@Override
public void onFailure(Throwable e, String message) {
dialog.hide();
Log.e("TREE_CLICK",
"Error retrieving plots on map touch event: "
+ e.getMessage());
e.printStackTrace();
}
@Override
public void dataReceived(PlotContainer response) {
try {
Plot plot = response.getFirst();
if (plot != null) {
Log.d("TREE_CLICK", plot.getData().toString());
Log.d("TREE_CLICK", "Using Plot (id: " + plot.getId() + ") with coords X: " + plot.getGeometry().getLon() + ", Y:" + plot.getGeometry().getLat());
showPopup(plot);
} else {
hidePopup();
}
} catch (JSONException e) {
Log.e("TREE_CLICK",
"Error retrieving plot info on map touch event: "
+ e.getMessage());
e.printStackTrace();
} finally {
dialog.hide();
}
}
});
}
};
// Map click listener that allows us to add a tree
private OnMapClickListener addMarkerMapClickListener = new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
Log.d("TREE_CLICK", "(" + point.latitude + "," + point.longitude + ")");
plotMarker = mMap.addMarker(new MarkerOptions()
.position(point)
.title("New Tree")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mapmarker))
);
plotMarker.setDraggable(true);
setTreeAddMode(STEP2);
}
};
public void setTreeAddMode(int step) {
View step1 =findViewById(R.id.addTreeStep1);
View step2 = findViewById(R.id.addTreeStep2);
switch (step) {
case CANCEL:
step1.setVisibility(View.GONE);
step2.setVisibility(View.GONE);
if (plotMarker != null) {
plotMarker.remove();
plotMarker = null;
}
mMap.setOnMapClickListener(showPopupMapClickListener);
break;
case STEP1:
step2.setVisibility(View.GONE);
step1.setVisibility(View.VISIBLE);
hidePopup();
if (plotMarker != null) {
plotMarker.remove();
plotMarker = null;
}
if (mMap != null) {
mMap.setOnMapClickListener(addMarkerMapClickListener);
}
break;
case STEP2:
hidePopup();
step1.setVisibility(View.GONE);
step2.setVisibility(View.VISIBLE);
if (mMap != null) {
mMap.setOnMapClickListener(null);
}
break;
case FINISH:
Intent editPlotIntent = new Intent (MainMapActivity.this, TreeEditDisplay.class);
Plot newPlot;
try {
newPlot = getPlotForNewTree();
String plotString = newPlot.getData().toString();
editPlotIntent.putExtra("plot", plotString );
editPlotIntent.putExtra("new_tree", "1");
startActivity(editPlotIntent);
} catch (Exception e) {
e.printStackTrace();
setTreeAddMode(CANCEL);
Toast.makeText(MainMapActivity.this, "Error creating new tree", Toast.LENGTH_LONG).show();
}
}
}
//click handler for the next button
public void submitNewTree(View view) {
setTreeAddMode(FINISH);
}
private Plot getPlotForNewTree() throws JSONException, IOException {
Plot newPlot = new Plot();
Geometry newGeometry = new Geometry();
double lat = plotMarker.getPosition().latitude;
double lon = plotMarker.getPosition().longitude;
newGeometry.setLat(lat);
newGeometry.setLon(lon);
newPlot.setGeometry(newGeometry);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
if (addresses.size() != 0) {
Address addressData = addresses.get(0);
String streetAddress = null;
String city = null;
String zip = null;
if (addressData.getMaxAddressLineIndex() != 0) {
streetAddress = addressData.getAddressLine(0);
}
if (streetAddress == null || streetAddress == "") {
streetAddress = "No Address";
}
city = addressData.getLocality();
zip = addressData.getPostalCode();
newPlot.setAddressCity(city);
newPlot.setAddressZip(zip);
newPlot.setAddress(streetAddress);
} else {
return null;
}
newPlot.setTree(new Tree());
return newPlot;
}
// on response, set the global cqlFilter property, and cause the tile layer,
// which has a reference to this property, to refresh.
JsonHttpResponseHandler handleNewFilterCql = new JsonHttpResponseHandler() {
public void onSuccess(JSONObject data) {
String cqlFilterString = data.optString("cql_string");
Log.d("CQL-FILTERS", cqlFilterString);
filterTileProvider.setCql(cqlFilterString);
filterTileOverlay.clearTileCache();
};
protected void handleFailureMessage(Throwable arg0, String arg1) {
Toast.makeText(MainMapActivity.this, "Error processing filters", Toast.LENGTH_SHORT).show();
Log.e(App.LOG_TAG, arg1);
arg0.printStackTrace();
filterTileProvider.setCql("1=0");
};
};
public void handleLocationSearchClick(View view) {
EditText et = (EditText)findViewById(R.id.locationSearchField);
String address = et.getText().toString();
if (address == "") {
Toast.makeText(MainMapActivity.this, "Enter an address in the search field to search.", Toast.LENGTH_SHORT).show();
} else {
Geocoder g = new Geocoder(MainMapActivity.this);
try {
List<Address> a = g.getFromLocationName(address, 1);
if (a.size() == 0) {
Toast.makeText(MainMapActivity.this, "Could not find that location.", Toast.LENGTH_SHORT).show();
} else {
Address geocoded = a.get(0);
LatLng pos = new LatLng(geocoded.getLatitude(), geocoded.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, DEFAULT_ZOOM_LEVEL+4));
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainMapActivity.this, "Error searching for location.", Toast.LENGTH_SHORT);
}
}
}
public void setUpBasemapControls() {
// Create the segmented buttons
SegmentedButton buttons = (SegmentedButton)findViewById(R.id.basemap_controls);
buttons.clearButtons();
ArrayList<String> buttonNames = new ArrayList<String>();
buttonNames.add("map");
buttonNames.add("satellite");
buttonNames.add("hybrid");
buttons.addButtons(buttonNames.toArray(new String[buttonNames.size()]));
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
switch (index) {
case 0:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case 1:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 2:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
}
}
});
}
}
| OpenTreeMap/src/org/azavea/otm/ui/MainMapActivity.java | package org.azavea.otm.ui;
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.TileOverlay;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.joelapenna.foursquared.widget.SegmentedButton;
import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.azavea.map.WMSTileProvider;
import org.azavea.otm.App;
import org.azavea.otm.R;
import org.azavea.otm.data.Geometry;
import org.azavea.otm.data.Plot;
import org.azavea.otm.data.PlotContainer;
import org.azavea.otm.data.Tree;
import org.azavea.otm.map.TileProviderFactory;
import org.azavea.otm.rest.RequestGenerator;
import org.azavea.otm.rest.handlers.ContainerRestHandler;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
//import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainMapActivity extends MapActivity{
private static LatLng START_POS;
private static final int DEFAULT_ZOOM_LEVEL = 12;
private static final int FILTER_INTENT = 1;
private static final int INFO_INTENT = 2;
// modes for the add marker feature
private static final int STEP1 = 1;
private static final int STEP2 = 2;
private static final int CANCEL = 3;
private static final int FINISH = 4;
private TextView plotSpeciesView;
private TextView plotAddressView;
private TextView plotDiameterView;
private TextView plotUpdatedByView;
private ImageView plotImageView;
private RelativeLayout plotPopup;
private Plot currentPlot; // The Plot we're currently showing a pop-up for, if any
private Marker plotMarker;
private GoogleMap mMap;
private TextView filterDisplay;
TileOverlay filterTileOverlay;
WMSTileProvider filterTileProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
START_POS = App.getStartPos();
setContentView(R.layout.activity_map_display_2);
filterDisplay = (TextView)findViewById(R.id.filterDisplay);
setUpMapIfNeeded();
plotPopup = (RelativeLayout) findViewById(R.id.plotPopup);
setPopupViews();
setTreeAddMode(CANCEL);
setUpBasemapControls();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setTreeAddMode(CANCEL);
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {@link #setUpMap()} once when {@link #mMap} is not null.
* <p>
* If it isn't installed {@link SupportMapFragment} (and
* {@link com.google.android.gms.maps.MapView
* MapView}) will show a prompt for the user to install/update the Google Play services APK on
* their device.
* <p>
* A user can return to this Activity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the Activity may not have been
* completely destroyed during this process (it is likely that it would only be stopped or
* paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
* {@link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
} else {
Log.e(App.LOG_TAG, "Map was null!");
}
}
}
private void setUpMap() {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(START_POS, DEFAULT_ZOOM_LEVEL));
/* This is the base tree layer using wms/geoserver for debugging purposes.
In production we use tilecache.
TileProvider wmsTileProvider = TileProviderFactory.getWmsTileProvider();
TileOverlay wmsTileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(wmsTileProvider));
wmsTileOverlay.setZIndex(50);
*/
TileProvider treeTileProvider = TileProviderFactory.getTileCacheTileProvider();
TileOverlay treeTileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(treeTileProvider));
treeTileOverlay.setZIndex(50);
// Set up the filter layer
filterTileProvider = TileProviderFactory.getFilterLayerTileProvider();
filterTileProvider.setCql("1=0");
filterTileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(filterTileProvider));
filterTileOverlay.setZIndex(100);
// Set up the default click listener
mMap.setOnMapClickListener(showPopupMapClickListener);
}
public void showPopup(Plot plot) {
//set default text
plotDiameterView.setText(getString(R.string.dbh_missing));
plotSpeciesView.setText(getString(R.string.species_missing));
plotAddressView.setText(getString(R.string.address_missing));
plotImageView.setImageResource(R.drawable.ic_action_search);
try {
plotUpdatedByView.setText(plot.getLastUpdatedBy());
if (plot.getAddress().length() != 0) {
plotAddressView.setText(plot.getAddress());
}
Tree tree = plot.getTree();
if (tree != null) {
String speciesName;
try {
speciesName = tree.getSpeciesName();
} catch (JSONException e) {
speciesName = "No species name";
}
plotSpeciesView.setText(speciesName);
if (tree.getDbh() != 0) {
plotDiameterView.setText(String.valueOf(tree.getDbh()) + " " + getString(R.string.dbh_units));
}
showImage(plot);
}
LatLng position = new LatLng(plot.getGeometry().getLat(), plot.getGeometry().getLon());
mMap.animateCamera(CameraUpdateFactory.newLatLng(position));
if (plotMarker != null) {
plotMarker.remove();
}
plotMarker = mMap.addMarker(new MarkerOptions().position(position).title("").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mapmarker)));
} catch (JSONException e) {
e.printStackTrace();
}
currentPlot = plot;
plotPopup.setVisibility(View.VISIBLE);
}
public void hidePopup() {
RelativeLayout plotPopup = (RelativeLayout) findViewById(R.id.plotPopup);
plotPopup.setVisibility(View.INVISIBLE);
currentPlot = null;
}
private void setPopupViews() {
plotSpeciesView = (TextView) findViewById(R.id.plotSpecies);
plotAddressView = (TextView) findViewById(R.id.plotAddress);
plotDiameterView = (TextView) findViewById(R.id.plotDiameter);
plotUpdatedByView = (TextView) findViewById(R.id.plotUpdatedBy);
plotImageView = (ImageView) findViewById(R.id.plotImage);
}
private void showImage(Plot plot) throws JSONException {
plot.getTreePhoto(new BinaryHttpResponseHandler(Plot.IMAGE_TYPES) {
@Override
public void onSuccess(byte[] imageData) {
Bitmap scaledImage = Plot.createTreeThumbnail(imageData);
ImageView plotImage = (ImageView) findViewById(R.id.plotImage);
plotImage.setImageBitmap(scaledImage);
}
@Override
public void onFailure(Throwable e, byte[] imageData) {
// Log the error, but not important enough to bother the user
Log.e(App.LOG_TAG, "Could not retreive tree image", e);
}
});
}
// onClick handler for tree-details pop-up touch event
public void showFullTreeInfo(View view) {
// Show TreeInfoDisplay with current plot
Intent viewPlot = new Intent(MainMapActivity.this, TreeInfoDisplay.class);
viewPlot.putExtra("plot", currentPlot.getData().toString());
if (App.getLoginManager().isLoggedIn()) {
viewPlot.putExtra("user", App.getLoginManager().loggedInUser.getData().toString());
}
startActivityForResult(viewPlot, INFO_INTENT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_map_display, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menu_filter) {
Intent filter = new Intent(this, FilterDisplay.class);
startActivityForResult(filter, FILTER_INTENT);
} else if (itemId == R.id.menu_add) {
if(App.getLoginManager().isLoggedIn()) {
setTreeAddMode(CANCEL);
setTreeAddMode(STEP1);
} else {
startActivity(new Intent(MainMapActivity.this, LoginActivity.class));
}
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case FILTER_INTENT:
if (resultCode == Activity.RESULT_OK) {
RequestParams activeFilters = App.getFilterManager().getActiveFiltersAsRequestParams();
setFilterDisplay(App.getFilterManager().getActiveFilterDisplay());
if (activeFilters.toString().equals("")) {
filterTileProvider.setCql("");
filterTileOverlay.clearTileCache();
} else {
RequestGenerator rc = new RequestGenerator();
rc.getCqlForFilters(activeFilters, handleNewFilterCql);
}
}
break;
case INFO_INTENT:
if (resultCode == TreeDisplay.RESULT_PLOT_EDITED) {
try {
// The plot was updated, so update the pop-up with any new data
Plot updatedPlot = new Plot();
String plotJSON = data.getExtras().getString("plot");
updatedPlot.setData(new JSONObject(plotJSON));
showPopup(updatedPlot);
} catch (JSONException e) {
Log.e(App.LOG_TAG, "Unable to deserialze updated plot for map popup", e);
hidePopup();
}
} else if (resultCode == TreeDisplay.RESULT_PLOT_DELETED) {
hidePopup();
// TODO: Do we need to refresh the map tile?
}
break;
}
}
private void setFilterDisplay(String activeFilterDisplay) {
if (activeFilterDisplay.equals("") || activeFilterDisplay == null) {
filterDisplay.setVisibility(View.GONE);
} else {
filterDisplay.setText(getString(R.string.filter_display_label) + " " + activeFilterDisplay);
filterDisplay.setVisibility(View.VISIBLE);
}
}
// onClick handler for "My Location" button
public void showMyLocation(View view) {
Context context = MainMapActivity.this;
LocationManager locationManager =
(LocationManager) context.getSystemService(context.LOCATION_SERVICE);
if (locationManager != null) {
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(crit, true);
Location lastKnownLocation = locationManager.getLastKnownLocation(provider);
if (lastKnownLocation != null) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude()
), DEFAULT_ZOOM_LEVEL+2));
} else {
Toast.makeText(MainMapActivity.this, "Could not determine current location.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainMapActivity.this, "Could not determine current location.", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onBackPressed() {
hidePopup();
setTreeAddMode(CANCEL);
}
// call backs for base layer switcher buttons
public void hybridBaselayer(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
public void mapBaselayer(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
public void satelliteBaselayer(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
// Map click listener for normal view mode
private OnMapClickListener showPopupMapClickListener = new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
Log.d("TREE_CLICK", "(" + point.latitude + "," + point.longitude + ")");
final ProgressDialog dialog = ProgressDialog.show(MainMapActivity.this, "",
"Loading. Please wait...", true);
dialog.show();
final RequestGenerator rg = new RequestGenerator();
rg.getPlotsNearLocation(
point.latitude,
point.longitude,
new ContainerRestHandler<PlotContainer>(new PlotContainer()) {
@Override
public void onFailure(Throwable e, String message) {
dialog.hide();
Log.e("TREE_CLICK",
"Error retrieving plots on map touch event: "
+ e.getMessage());
e.printStackTrace();
}
@Override
public void dataReceived(PlotContainer response) {
try {
Plot plot = response.getFirst();
if (plot != null) {
Log.d("TREE_CLICK", plot.getData().toString());
Log.d("TREE_CLICK", "Using Plot (id: " + plot.getId() + ") with coords X: " + plot.getGeometry().getLon() + ", Y:" + plot.getGeometry().getLat());
showPopup(plot);
} else {
hidePopup();
}
} catch (JSONException e) {
Log.e("TREE_CLICK",
"Error retrieving plot info on map touch event: "
+ e.getMessage());
e.printStackTrace();
} finally {
dialog.hide();
}
}
});
}
};
// Map click listener that allows us to add a tree
private OnMapClickListener addMarkerMapClickListener = new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
Log.d("TREE_CLICK", "(" + point.latitude + "," + point.longitude + ")");
plotMarker = mMap.addMarker(new MarkerOptions()
.position(point)
.title("New Tree")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mapmarker))
);
plotMarker.setDraggable(true);
setTreeAddMode(STEP2);
}
};
public void setTreeAddMode(int step) {
View step1 =findViewById(R.id.addTreeStep1);
View step2 = findViewById(R.id.addTreeStep2);
switch (step) {
case CANCEL:
step1.setVisibility(View.GONE);
step2.setVisibility(View.GONE);
if (plotMarker != null) {
plotMarker.remove();
plotMarker = null;
}
mMap.setOnMapClickListener(showPopupMapClickListener);
break;
case STEP1:
step2.setVisibility(View.GONE);
step1.setVisibility(View.VISIBLE);
hidePopup();
if (plotMarker != null) {
plotMarker.remove();
plotMarker = null;
}
if (mMap != null) {
mMap.setOnMapClickListener(addMarkerMapClickListener);
}
break;
case STEP2:
hidePopup();
step1.setVisibility(View.GONE);
step2.setVisibility(View.VISIBLE);
if (mMap != null) {
mMap.setOnMapClickListener(null);
}
break;
case FINISH:
Intent editPlotIntent = new Intent (MainMapActivity.this, TreeEditDisplay.class);
Plot newPlot;
try {
newPlot = getPlotForNewTree();
String plotString = newPlot.getData().toString();
editPlotIntent.putExtra("plot", plotString );
editPlotIntent.putExtra("new_tree", "1");
startActivity(editPlotIntent);
} catch (Exception e) {
e.printStackTrace();
setTreeAddMode(CANCEL);
Toast.makeText(MainMapActivity.this, "Error creating new tree", Toast.LENGTH_LONG).show();
}
}
}
//click handler for the next button
public void submitNewTree(View view) {
setTreeAddMode(FINISH);
}
private Plot getPlotForNewTree() throws JSONException, IOException {
Plot newPlot = new Plot();
Geometry newGeometry = new Geometry();
double lat = plotMarker.getPosition().latitude;
double lon = plotMarker.getPosition().longitude;
newGeometry.setLat(lat);
newGeometry.setLon(lon);
newPlot.setGeometry(newGeometry);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
if (addresses.size() != 0) {
Address addressData = addresses.get(0);
String streetAddress = null;
String city = null;
String zip = null;
if (addressData.getMaxAddressLineIndex() != 0) {
streetAddress = addressData.getAddressLine(0);
}
if (streetAddress == null || streetAddress == "") {
streetAddress = "No Address";
}
city = addressData.getLocality();
zip = addressData.getPostalCode();
newPlot.setAddressCity(city);
newPlot.setAddressZip(zip);
newPlot.setAddress(streetAddress);
} else {
return null;
}
newPlot.setTree(new Tree());
return newPlot;
}
// on response, set the global cqlFilter property, and cause the tile layer,
// which has a reference to this property, to refresh.
JsonHttpResponseHandler handleNewFilterCql = new JsonHttpResponseHandler() {
public void onSuccess(JSONObject data) {
String cqlFilterString = data.optString("cql_string");
Log.d("CQL-FILTERS", cqlFilterString);
filterTileProvider.setCql(cqlFilterString);
filterTileOverlay.clearTileCache();
};
protected void handleFailureMessage(Throwable arg0, String arg1) {
Toast.makeText(MainMapActivity.this, "Error processing filters", Toast.LENGTH_SHORT).show();
Log.e(App.LOG_TAG, arg1);
arg0.printStackTrace();
filterTileProvider.setCql("1=0");
};
};
public void handleLocationSearchClick(View view) {
EditText et = (EditText)findViewById(R.id.locationSearchField);
String address = et.getText().toString();
if (address == "") {
Toast.makeText(MainMapActivity.this, "Enter an address in the search field to search.", Toast.LENGTH_SHORT).show();
} else {
Geocoder g = new Geocoder(MainMapActivity.this);
try {
List<Address> a = g.getFromLocationName(address, 1);
if (a.size() == 0) {
Toast.makeText(MainMapActivity.this, "Could not find that location.", Toast.LENGTH_SHORT).show();
} else {
Address geocoded = a.get(0);
LatLng pos = new LatLng(geocoded.getLatitude(), geocoded.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, DEFAULT_ZOOM_LEVEL+4));
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainMapActivity.this, "Error searching for location.", Toast.LENGTH_SHORT);
}
}
}
public void setUpBasemapControls() {
// Create the segmented buttons
SegmentedButton buttons = (SegmentedButton)findViewById(R.id.basemap_controls);
buttons.clearButtons();
ArrayList<String> buttonNames = new ArrayList<String>();
buttonNames.add("map");
buttonNames.add("satellite");
buttonNames.add("hybrid");
buttons.addButtons(buttonNames.toArray(new String[buttonNames.size()]));
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
switch (index) {
case 0:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case 1:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 2:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
}
}
});
}
}
| protect against NPE when google play lib is missing
| OpenTreeMap/src/org/azavea/otm/ui/MainMapActivity.java | protect against NPE when google play lib is missing | <ide><path>penTreeMap/src/org/azavea/otm/ui/MainMapActivity.java
<ide> setUpMapIfNeeded();
<ide> plotPopup = (RelativeLayout) findViewById(R.id.plotPopup);
<ide> setPopupViews();
<del> setTreeAddMode(CANCEL);
<del> setUpBasemapControls();
<del> }
<add> }
<ide>
<ide> @Override
<ide> protected void onResume() {
<ide> if (mMap != null) {
<ide> setUpMap();
<ide> } else {
<add> Toast.makeText(MainMapActivity.this, "Google play services library not found.", Toast.LENGTH_LONG).show();
<ide> Log.e(App.LOG_TAG, "Map was null!");
<ide> }
<ide> }
<ide>
<ide> // Set up the default click listener
<ide> mMap.setOnMapClickListener(showPopupMapClickListener);
<add>
<add> setTreeAddMode(CANCEL);
<add> setUpBasemapControls();
<add>
<ide> }
<ide>
<ide> public void showPopup(Plot plot) { |
|
Java | apache-2.0 | 5e1fe0188bed6d2c95fbeaeeecfa9b5230d75093 | 0 | madurangasiriwardena/product-is,wso2/product-is,mefarazath/product-is,mefarazath/product-is,wso2/product-is,madurangasiriwardena/product-is,mefarazath/product-is,wso2/product-is,madurangasiriwardena/product-is,wso2/product-is,wso2/product-is,madurangasiriwardena/product-is,mefarazath/product-is,madurangasiriwardena/product-is,mefarazath/product-is | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.identity.integration.test.oauth2;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.wso2.identity.integration.common.utils.ISIntegrationTest;
import org.wso2.identity.integration.test.utils.DataExtractUtil;
import java.io.IOException;
public class OIDCMetadataTest extends ISIntegrationTest {
private static final String TOKEN_ENDPOINT_SUPER_TENANT =
"https://localhost:9853/oauth2/token/.well-known/openid-configuration";
private static final String TOKEN_ENDPOINT_TENANT =
"https://localhost:9853/t/wso2.com/oauth2/token/.well-known/openid-configuration";
private static final String TOKEN_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM =
"https://localhost:9853/t/carbon.super/oauth2/token/.well-known/openid-configuration";
private static final String OIDCDISCOVERY_ENDPOINT_SUPER_TENANT =
"https://localhost:9853/oauth2/oidcdiscovery/.well-known/openid-configuration";
private static final String OIDCDISCOVERY_ENDPOINT_TENANT =
"https://localhost:9853/t/wso2.com/oauth2/oidcdiscovery/.well-known/openid-configuration";
private static final String OIDCDISCOVERY_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM =
"https://localhost:9853/t/carbon.super/oauth2/oidcdiscovery/.well-known/openid-configuration";
private static final String INTROSPECTION_ENDPOINT_SUPER_TENANT = "https://localhost:9853/oauth2/introspect";
private static final String INTROSPECTION_ENDPOINT_TENANT = "https://localhost:9853/t/wso2.com/oauth2/introspect";
private static final String CHECK_SESSION_IFRAME = "https://localhost:9853/oidc/checksession";
private static final String ISSUER = "https://localhost:9853/oauth2/token";
private static final String AUTHORIZATION_ENDPOINT = "https://localhost:9853/oauth2/authorize";
private static final String TOKEN_ENDPOINT = "https://localhost:9853/oauth2/token";
private static final String END_SESSION_ENDPOINT = "https://localhost:9853/oidc/logout";
private static final String REVOCATION_ENDPOINT = "https://localhost:9853/oauth2/revoke";
private static final String USERINFO_ENDPOINT = "https://localhost:9853/oauth2/userinfo";
private static final String JKWS_URI_SUPER_TENANT = "https://localhost:9853/oauth2/jwks";
private static final String JKWS_URI_TENANT = "https://localhost:9853/t/wso2.com/oauth2/jwks";
private static final String REGISTRATION_ENDPOINT_SUPER_TENANT =
"https://localhost:9853/api/identity/oauth2/dcr/v1.1/register";
private static final String REGISTRATION_ENDPOINT_TENANT =
"https://localhost:9853/t/wso2.com/api/identity/oauth2/dcr/v1.1/register";
@Test(groups = "wso2.is", description = "This test method will test OIDC Metadata endpoints.")
public void getOIDCMetadata() throws Exception {
testResponseContent(TOKEN_ENDPOINT_SUPER_TENANT);
testResponseContent(TOKEN_ENDPOINT_TENANT);
testResponseContent(TOKEN_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM);
testResponseContent(OIDCDISCOVERY_ENDPOINT_SUPER_TENANT);
testResponseContent(OIDCDISCOVERY_ENDPOINT_TENANT);
testResponseContent(OIDCDISCOVERY_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM);
}
private void testResponseContent(String oidcMetadataEndpoint) throws IOException, JSONException {
HttpClient client = HttpClientBuilder.create().build();
HttpResponse httpResponse = sendGetRequest(client, oidcMetadataEndpoint);
String content = DataExtractUtil.getContentData(httpResponse);
Assert.assertNotNull(content, "Response content is not received");
JSONObject oidcMetadataEndpoints = new JSONObject(content);
Assert.assertEquals(oidcMetadataEndpoints.getString("check_session_iframe"),
CHECK_SESSION_IFRAME, "Incorrect session iframe");
Assert.assertEquals(oidcMetadataEndpoints.getString("issuer"),
ISSUER, "Incorrect issuer");
Assert.assertEquals(oidcMetadataEndpoints.getString("authorization_endpoint"),
AUTHORIZATION_ENDPOINT, "Incorrect authorization endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("token_endpoint"),
TOKEN_ENDPOINT, "Incorrect token_endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("end_session_endpoint"),
END_SESSION_ENDPOINT, "Incorrect end session endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("revocation_endpoint"),
REVOCATION_ENDPOINT, "Incorrect revocation endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("userinfo_endpoint"),
USERINFO_ENDPOINT, "Incorrect userinfo endpoint");
if (oidcMetadataEndpoint.equals(TOKEN_ENDPOINT_SUPER_TENANT) ||
oidcMetadataEndpoint.equals(OIDCDISCOVERY_ENDPOINT_SUPER_TENANT) ||
oidcMetadataEndpoint.equals(TOKEN_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM) ||
oidcMetadataEndpoint.equals(OIDCDISCOVERY_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM)) {
Assert.assertEquals(oidcMetadataEndpoints.getString("jwks_uri"),
JKWS_URI_SUPER_TENANT, "Incorrect jwks uri");
Assert.assertEquals(oidcMetadataEndpoints.getString("registration_endpoint"),
REGISTRATION_ENDPOINT_SUPER_TENANT, "Incorrect registration endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("introspection_endpoint"),
INTROSPECTION_ENDPOINT_SUPER_TENANT, "Incorrect introspection endpoint");
}
if (oidcMetadataEndpoint.equals(TOKEN_ENDPOINT_TENANT) ||
oidcMetadataEndpoint.equals(OIDCDISCOVERY_ENDPOINT_TENANT)) {
Assert.assertEquals(oidcMetadataEndpoints.getString("jwks_uri"),
JKWS_URI_TENANT, "Incorrect jwks uri");
Assert.assertEquals(oidcMetadataEndpoints.getString("registration_endpoint"),
REGISTRATION_ENDPOINT_TENANT, "Incorrect registration endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("introspection_endpoint"),
INTROSPECTION_ENDPOINT_TENANT, "Incorrect introspection endpoint");
}
}
private HttpResponse sendGetRequest(HttpClient client, String oidcMetadataEndpoint) throws IOException {
HttpGet getRequest = new HttpGet(oidcMetadataEndpoint);
HttpResponse response = client.execute(getRequest);
return response;
}
}
| modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OIDCMetadataTest.java | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.identity.integration.test.oauth2;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.wso2.identity.integration.common.utils.ISIntegrationTest;
import org.wso2.identity.integration.test.utils.DataExtractUtil;
import java.io.IOException;
public class OIDCMetadataTest extends ISIntegrationTest {
private static final String TOKEN_ENDPOINT_SUPER_TENANT =
"https://localhost:9853/oauth2/token/.well-known/openid-configuration";
private static final String TOKEN_ENDPOINT_TENANT =
"https://localhost:9853/t/wso2.com/oauth2/token/.well-known/openid-configuration";
private static final String TOKEN_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM =
"https://localhost:9853/t/carbon.super/oauth2/token/.well-known/openid-configuration";
private static final String OIDCDISCOVERY_ENDPOINT_SUPER_TENANT =
"https://localhost:9853/oauth2/oidcdiscovery/.well-known/openid-configuration";
private static final String OIDCDISCOVERY_ENDPOINT_TENANT =
"https://localhost:9853/t/wso2.com/oauth2/oidcdiscovery/.well-known/openid-configuration";
private static final String OIDCDISCOVERY_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM =
"https://localhost:9853/t/carbon.super/oauth2/oidcdiscovery/.well-known/openid-configuration";
private static final String INTROSPECTION_ENDPOINT_SUPER_TENANT = "https://localhost:9853/oauth2/introspect";
private static final String INTROSPECTION_ENDPOINT_TENANT = "https://localhost:9853/t/wso2.com/oauth2/introspect";
private static final String CHECK_SESSION_IFRAME = "https://localhost:9853/oidc/checksession";
private static final String ISSUER = "https://localhost:9853/oauth2/token";
private static final String AUTHORIZATION_ENDPOINT = "https://localhost:9853/oauth2/authorize";
private static final String TOKEN_ENDPOINT = "https://localhost:9853/oauth2/token";
private static final String END_SESSION_ENDPOINT = "https://localhost:9853/oidc/logout";
private static final String REVOCATION_ENDPOINT = "https://localhost:9853/oauth2/revoke";
private static final String USERINFO_ENDPOINT = "https://localhost:9853/oauth2/userinfo";
private static final String JKWS_URI_SUPER_TENANT = "https://localhost:9853/oauth2/jwks";
private static final String JKWS_URI_TENANT = "https://localhost:9853/t/wso2.com/oauth2/jwks";
private static final String REGISTRATION_ENDPOINT_SUPER_TENANT =
"https://localhost:9853/api/identity/oauth2/dcr/v1.1/register";
private static final String REGISTRATION_ENDPOINT_TENANT =
"https://localhost:9853/t/wso2.com/api/identity/oauth2/dcr/v1.1/register";
@Test(groups = "wso2.is", description = "This test method will test OIDC Metadata endpoints.")
public void getOIDCMetadata() throws Exception {
testResponseContent(TOKEN_ENDPOINT_SUPER_TENANT);
testResponseContent(TOKEN_ENDPOINT_TENANT);
testResponseContent(TOKEN_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM);
testResponseContent(OIDCDISCOVERY_ENDPOINT_SUPER_TENANT);
testResponseContent(OIDCDISCOVERY_ENDPOINT_TENANT);
testResponseContent(OIDCDISCOVERY_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM);
}
private void testResponseContent(String oidcMetadataEndpoint) throws IOException, JSONException {
HttpClient client = HttpClientBuilder.create().build();
HttpResponse httpResponse = sendGetRequest(client, oidcMetadataEndpoint);
String content = DataExtractUtil.getContentData(httpResponse);
Assert.assertNotNull(content, "Response content is not received");
JSONObject oidcMetadataEndpoints = new JSONObject(content);
Assert.assertEquals(oidcMetadataEndpoints.getString("check_session_iframe"),
CHECK_SESSION_IFRAME, "Incorrect session iframe");
Assert.assertEquals(oidcMetadataEndpoints.getString("issuer"),
ISSUER, "Incorrect issuer");
Assert.assertEquals(oidcMetadataEndpoints.getString("authorization_endpoint"),
AUTHORIZATION_ENDPOINT, "Incorrect authorization endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("token_endpoint"),
TOKEN_ENDPOINT, "Incorrect token_endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("end_session_endpoint"),
END_SESSION_ENDPOINT, "Incorrect end session endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("revocation_endpoint"),
REVOCATION_ENDPOINT, "Incorrect revocation endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("userinfo_endpoint"),
USERINFO_ENDPOINT, "Incorrect userinfo endpoint");
if (oidcMetadataEndpoint.equals(TOKEN_ENDPOINT_SUPER_TENANT) ||
oidcMetadataEndpoint.equals(OIDCDISCOVERY_ENDPOINT_SUPER_TENANT) ||
oidcMetadataEndpoint.equals(TOKEN_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM) ||
oidcMetadataEndpoint.equals(OIDCDISCOVERY_ENDPOINT_WITH_SUPER_TENANT_AS_PATH_PARAM)) {
Assert.assertEquals(oidcMetadataEndpoints.getString("jwks_uri"),
JKWS_URI_SUPER_TENANT, "Incorrect jwks uri");
Assert.assertEquals(oidcMetadataEndpoints.getString("registration_endpoint"),
REGISTRATION_ENDPOINT_SUPER_TENANT, "Incorrect registration endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("introspection_endpoint"),
INTROSPECTION_ENDPOINT_SUPER_TENANT, "Incorrect introspection endpoint");
}
if (oidcMetadataEndpoint.equals(TOKEN_ENDPOINT_TENANT) ||
oidcMetadataEndpoint.equals(OIDCDISCOVERY_ENDPOINT_TENANT)) {
Assert.assertEquals(oidcMetadataEndpoints.getString("jwks_uri"),
JKWS_URI_TENANT, "Incorrect jwks uri");
Assert.assertEquals(oidcMetadataEndpoints.getString("registration_endpoint"),
REGISTRATION_ENDPOINT_TENANT, "Incorrect registration endpoint");
Assert.assertEquals(oidcMetadataEndpoints.getString("introspection_endpoint"),
INTROSPECTION_ENDPOINT_TENANT, "Incorrect introspection endpoint");
}
}
private HttpResponse sendGetRequest(HttpClient client, String oidcMetadataEndpoint) throws IOException {
HttpGet getRequest = new HttpGet(oidcMetadataEndpoint);
HttpResponse response = client.execute(getRequest);
return response;
}
}
| Address PR review comments
| modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OIDCMetadataTest.java | Address PR review comments | <ide><path>odules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OIDCMetadataTest.java
<ide> HttpResponse response = client.execute(getRequest);
<ide> return response;
<ide> }
<add>
<ide> } |
|
Java | mit | d66efbaf4deb8f0a05ca15e4bb713fc95c028305 | 0 | oscarguindzberg/multibit-hd,bitcoin-solutions/multibit-hd,akonring/multibit-hd-modified,bitcoin-solutions/multibit-hd,akonring/multibit-hd-modified,oscarguindzberg/multibit-hd,akonring/multibit-hd-modified,bitcoin-solutions/multibit-hd,oscarguindzberg/multibit-hd | package org.multibit.hd.ui.views.components;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import net.miginfocom.swing.MigLayout;
import org.multibit.hd.core.dto.CoreMessageKey;
import org.multibit.hd.core.managers.WalletManager;
import org.multibit.hd.ui.MultiBitUI;
import org.multibit.hd.ui.languages.Languages;
import org.multibit.hd.ui.languages.MessageKey;
import org.multibit.hd.ui.views.components.panels.BackgroundPanel;
import org.multibit.hd.ui.views.components.panels.LightBoxPanel;
import org.multibit.hd.ui.views.components.panels.PanelDecorator;
import org.multibit.hd.ui.views.components.panels.RoundedPanel;
import org.multibit.hd.ui.views.fonts.AwesomeDecorator;
import org.multibit.hd.ui.views.fonts.AwesomeIcon;
import org.multibit.hd.ui.views.themes.Themes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.Locale;
/**
* <p>Factory to provide the following to views:</p>
* <ul>
* <li>Creation of panels</li>
* </ul>
*
* @since 0.0.1
*/
public class Panels {
private static final Logger log = LoggerFactory.getLogger(Panels.class);
/**
* A global reference to the application frame
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"MS_SHOULD_BE_FINAL",
"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"
})
public static JFrame applicationFrame;
private static Optional<LightBoxPanel> lightBoxPanel = Optional.absent();
private static Optional<LightBoxPanel> lightBoxPopoverPanel = Optional.absent();
/**
* <p>A default MiG layout constraint with:</p>
* <ul>
* <li>Zero insets</li>
* <li>Fills all available space (X and Y)</li>
* <li>Handles left-to-right and right-to-left presentation automatically</li>
* </ul>
*
* @return A default MiG layout constraint that fills all X and Y with RTL appended
*/
public static String migXYLayout() {
return migLayout("fill,insets 0");
}
/**
* <p>A default MiG layout constraint with:</p>
* <ul>
* <li>Zero insets</li>
* <li>Fills all available space (X only)</li>
* <li>Handles left-to-right and right-to-left presentation automatically</li>
* </ul>
*
* @return A default MiG layout constraint that fills all X with RTL appended suitable for screens
*/
public static String migXLayout() {
return migLayout("fillx,insets 0");
}
/**
* <p>A non-standard MiG layout constraint with:</p>
* <ul>
* <li>Optional "fill", "insets", "hidemode" etc</li>
* <li>Handles left-to-right and right-to-left presentation automatically</li>
* </ul>
*
* @param layout Any of the usual MiG layout constraints except RTL (e.g. "fillx,insets 1 2 3 4")
*
* @return The MiG layout constraint with RTL handling appended
*/
public static String migLayout(String layout) {
return layout + (Languages.isLeftToRight() ? "" : ",rtl");
}
/**
* <p>A default MiG layout constraint with:</p>
* <ul>
* <li>Detail screen insets</li>
* <li>Fills all available space (X and Y)</li>
* <li>Handles left-to-right and right-to-left presentation automatically</li>
* </ul>
*
* @return A MiG layout constraint that fills all X and Y with RTL appended suitable for detail views
*/
public static String migXYDetailLayout() {
return migLayout("fill,insets 10 5 5 5");
}
/**
* <p>A default MiG layout constraint with:</p>
* <ul>
* <li>Popover screen insets</li>
* <li>Fills all available space (X only)</li>
* <li>Handles left-to-right and right-to-left presentation automatically</li>
* </ul>
*
* @return A MiG layout constraint that fills all X with RTL appended suitable for popovers
*/
public static String migXPopoverLayout() {
return migLayout("fill,insets 10 10 10 10");
}
/**
* @return A simple theme-aware panel with a single cell MigLayout that fills all X and Y
*/
public static JPanel newPanel() {
return Panels.newPanel(
new MigLayout(
migXYLayout(), // Layout
"[]", // Columns
"[]" // Rows
));
}
/**
* @param layout The layout manager for the panel (typically MigLayout)
*
* @return A simple theme-aware detail panel with the given layout
*/
public static JPanel newPanel(LayoutManager2 layout) {
JPanel panel = new JPanel(layout);
// Theme
panel.setBackground(Themes.currentTheme.detailPanelBackground());
// Force transparency
panel.setOpaque(false);
// Ensure LTR and RTL is detected by the layout
panel.applyComponentOrientation(Languages.currentComponentOrientation());
return panel;
}
/**
* @return A simple panel with rounded corners and a single column MigLayout
*/
public static JPanel newRoundedPanel() {
return newRoundedPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
}
/**
* @param layout The MiGLayout to use
*
* @return A simple panel with rounded corners
*/
public static JPanel newRoundedPanel(LayoutManager2 layout) {
JPanel panel = new RoundedPanel(layout);
// Theme
panel.setBackground(Themes.currentTheme.detailPanelBackground());
panel.setForeground(Themes.currentTheme.fadedText());
return panel;
}
/**
* @param icon The Awesome icon to use as the basis of the image for consistent LaF
*
* @return A theme-aware panel with rounded corners and a single cell MigLayout
*/
public static BackgroundPanel newDetailBackgroundPanel(AwesomeIcon icon) {
// Create an image from the AwesomeIcon
Image image = ImageDecorator.toImageIcon(
AwesomeDecorator.createIcon(
icon,
Themes.currentTheme.fadedText(),
MultiBitUI.HUGE_ICON_SIZE
)).getImage();
BackgroundPanel panel = new BackgroundPanel(image, BackgroundPanel.ACTUAL);
panel.setLayout(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
panel.setAlpha(MultiBitUI.DETAIL_PANEL_BACKGROUND_ALPHA);
panel.setPaint(Themes.currentTheme.detailPanelBackground());
panel.setBackground(Themes.currentTheme.detailPanelBackground());
return panel;
}
/**
* <p>Test if a light box is showing</p>
*
* @return True if the light box panel is visible
*/
public synchronized static boolean isLightBoxShowing() {
return lightBoxPanel.isPresent();
}
/**
* <p>Show a light box</p>
*
* @param panel The panel to act as the focus of the light box
*/
public synchronized static void showLightBox(JPanel panel) {
log.debug("Show light box");
Preconditions.checkState(SwingUtilities.isEventDispatchThread(), "LightBox requires the EDT");
// Do not override this to replace the existing light box
// The problem is that the new light box is tripping up due to a race condition in the code
// which needs to be dealt with rather than masked behind deferred clean up
Preconditions.checkState(!lightBoxPanel.isPresent(), "Light box should never be called twice ");
// Prevent focus
allowFocus(Panels.applicationFrame, false);
// Add the light box panel
lightBoxPanel = Optional.of(new LightBoxPanel(panel, JLayeredPane.MODAL_LAYER));
}
/**
* <p>Hides the currently showing light box panel (and any popover)</p>
*/
public synchronized static void hideLightBoxIfPresent() {
Preconditions.checkState(SwingUtilities.isEventDispatchThread(), "LightBoxPopover requires the EDT");
log.debug("Hide light box (if present)");
hideLightBoxPopoverIfPresent();
if (lightBoxPanel.isPresent()) {
lightBoxPanel.get().close();
}
lightBoxPanel = Optional.absent();
// Finally allow focus
allowFocus(Panels.applicationFrame, true);
}
/**
* <p>Test if a light box popover is showing</p>
*
* @return True if the popover panel is visible
*/
public synchronized static boolean isLightBoxPopoverShowing() {
return lightBoxPopoverPanel.isPresent();
}
/**
* <p>Show a light box pop over</p>
*
* @param panel The panel to act as the focus of the popover
*/
public synchronized static void showLightBoxPopover(JPanel panel) {
log.debug("Show light box popover");
Preconditions.checkState(SwingUtilities.isEventDispatchThread(), "LightBoxPopover requires the EDT");
Preconditions.checkState(lightBoxPanel.isPresent(), "LightBoxPopover should not be called unless a light box is showing");
Preconditions.checkState(!lightBoxPopoverPanel.isPresent(), "LightBoxPopover should never be called twice");
lightBoxPopoverPanel = Optional.of(new LightBoxPanel(panel, JLayeredPane.DRAG_LAYER));
}
/**
* <p>Hides the currently showing light box popover panel</p>
*/
public synchronized static void hideLightBoxPopoverIfPresent() {
Preconditions.checkState(SwingUtilities.isEventDispatchThread(), "LightBoxPopover requires the EDT");
log.debug("Hide light box popover (if present)");
if (lightBoxPopoverPanel.isPresent()) {
// A popover is not part of a handover so gets closed completely
lightBoxPopoverPanel.get().close();
}
lightBoxPopoverPanel = Optional.absent();
}
/**
* <p>An "exit selector" panel confirms an exit or switch operation</p>
*
* @param listener The action listener
* @param exitCommand The exit command name
* @param switchCommand The switch command name
*
* @return A new "exit selector" panel
*/
public static JPanel newExitSelector(
ActionListener listener,
String exitCommand,
String switchCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.EXIT_WALLET);
radio1.setSelected(true);
radio1.setActionCommand(exitCommand);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.SWITCH_WALLET);
radio2.setActionCommand(switchCommand);
// Wallet selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
return panel;
}
/**
* <p>A "licence selector" panel provides a means of ensuring the user agrees with the licence</p>
*
* @param listener The action listener
* @param agreeCommand The agree command name
* @param disagreeCommand The disagree command name
*
* @return A new "licence selector" panel
*/
public static JPanel newLicenceSelector(
ActionListener listener,
String agreeCommand,
String disagreeCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.ACCEPT_LICENCE);
radio1.setActionCommand(agreeCommand);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.REJECT_LICENCE);
radio2.setSelected(true);
radio2.setActionCommand(disagreeCommand);
// Wallet selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
return panel;
}
/**
* <p>A standard "wallet selector" panel provides a means of choosing how a wallet is to be created/accessed</p>
*
* @param listener The action listener
* @param createCommand The create command name
* @param existingWalletCommand The existing wallet command name
* @param restorePasswordCommand The restore credentials command name
* @param restoreWalletCommand The restore wallet command name
*
* @return A new "wallet selector" panel
*/
public static JPanel newWalletSelector(
ActionListener listener,
String createCommand,
String existingWalletCommand,
String restorePasswordCommand,
String restoreWalletCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.CREATE_WALLET);
radio1.setSelected(true);
radio1.setActionCommand(createCommand);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.USE_EXISTING_WALLET);
radio2.setActionCommand(existingWalletCommand);
JRadioButton radio3 = RadioButtons.newRadioButton(listener, MessageKey.RESTORE_PASSWORD);
radio3.setActionCommand(restorePasswordCommand);
JRadioButton radio4 = RadioButtons.newRadioButton(listener, MessageKey.RESTORE_WALLET);
radio4.setActionCommand(restoreWalletCommand);
// Check for existing wallets
if (WalletManager.getSoftWalletSummaries(Optional.<Locale>absent()).isEmpty()) {
radio2.setEnabled(false);
radio2.setForeground(UIManager.getColor("RadioButton.disabledText"));
}
// Wallet selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
group.add(radio3);
group.add(radio4);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
panel.add(radio3, "wrap");
panel.add(radio4, "wrap");
return panel;
}
/**
* <p>A "hardware wallet selector" panel provides a means of choosing how a hardware wallet is to be created/accessed</p>
*
* @param listener The action listener
* @param createCommand The create command name
* @param existingWalletCommand The existing wallet command name
* @param restoreWalletCommand The restore wallet command name
*
* @return A new "wallet selector" panel
*/
public static JPanel newHardwareWalletSelector(
ActionListener listener,
String createCommand,
String existingWalletCommand,
String restoreWalletCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.TREZOR_CREATE_WALLET);
radio1.setSelected(true);
radio1.setActionCommand(createCommand);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.USE_EXISTING_WALLET);
radio2.setActionCommand(existingWalletCommand);
JRadioButton radio3 = RadioButtons.newRadioButton(listener, MessageKey.RESTORE_WALLET);
radio3.setActionCommand(restoreWalletCommand);
// Check for existing wallets
if (WalletManager.getWalletSummaries().isEmpty()) {
radio2.setEnabled(false);
radio2.setForeground(UIManager.getColor("RadioButton.disabledText"));
}
// Wallet selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
group.add(radio3);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
panel.add(radio3, "wrap");
return panel;
}
/**
* <p>A "Trezor select PIN" panel provides a means of choosing how a device PIN is to be changed/removed</p>
*
* @param listener The action listener
* @param changeCommand The change PIN command name
* @param removeCommand The remove PIN command name
*
* @return A new "wallet selector" panel
*/
public static JPanel newChangePinSelector(
ActionListener listener,
String changeCommand,
String removeCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.CHANGE_PIN_OPTION);
radio1.setSelected(true);
radio1.setActionCommand(changeCommand);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.REMOVE_PIN_OPTION);
radio2.setActionCommand(removeCommand);
// Wallet selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
return panel;
}
/**
* <p>A "Trezor tool selector" panel provides a means of choosing which Trezor tool to run</p>
*
* @param listener The action listener
* @param buyTrezorCommand The buy trezor command
* @param verifyDeviceCommand The verify device command name
* @param wipeDeviceCommand The wipe device command name
*
* @return A new "use Trezor selector" panel
*/
public static JPanel newUseTrezorSelector(
ActionListener listener,
String buyTrezorCommand,
String verifyDeviceCommand,
String wipeDeviceCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.BUY_TREZOR);
radio1.setActionCommand(buyTrezorCommand);
radio1.setSelected(true);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.VERIFY_DEVICE);
radio2.setActionCommand(verifyDeviceCommand);
JRadioButton radio3 = RadioButtons.newRadioButton(listener, MessageKey.WIPE_DEVICE);
radio3.setActionCommand(wipeDeviceCommand);
// Action selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
group.add(radio3);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
panel.add(radio3, "wrap");
return panel;
}
/**
* <p>A "confirm seed phrase" panel displays the instructions to enter the seed phrase from a piece of paper</p>
*
* @return A new "confirm seed phrase" panel
*/
public static JPanel newConfirmSeedPhrase() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXYLayout(),
"[]", // Columns
"[]" // Rows
));
// Add to the panel
panel.add(Labels.newConfirmSeedPhraseNote(), "grow,push");
return panel;
}
/**
* <p>A "debugger warning" panel displays instructions to the user about a debugger being attached</p>
*
* @return A new "debugger warning" panel
*/
public static JPanel newDebuggerWarning() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Ensure it is accessible
AccessibilityDecorator.apply(panel, CoreMessageKey.DEBUGGER_ATTACHED);
PanelDecorator.applyDangerFadedTheme(panel);
// Add to the panel
panel.add(Labels.newDebuggerWarningNote(), "w 350");
return panel;
}
/**
* <p>An "unsupported firmware" panel displays instructions to the user about a hardware wallet with unsupported firmware (security risk) being attached</p>
*
* @return A new "unsupported firmware" panel
*/
public static JPanel newUnsupportedFirmware() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Ensure it is accessible
AccessibilityDecorator.apply(panel, CoreMessageKey.UNSUPPORTED_FIRMWARE_ATTACHED);
PanelDecorator.applyWarningTheme(panel);
// Add to the panel
panel.add(Labels.newUnsupportedFirmwareNote(), "w 350");
return panel;
}
/**
* <p>A "language change" panel displays instructions to the user about a language change</p>
*
* @return A new "language change" panel
*/
public static JPanel newLanguageChange() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
PanelDecorator.applySuccessFadedTheme(panel);
// Add to the panel
panel.add(Labels.newLanguageChangeNote(), "grow,push");
return panel;
}
/**
* <p>A "restore from backup" panel displays the instructions to restore from a backup folder</p>
*
* @return A new "restore from backup" panel
*/
public static JPanel newRestoreFromBackup() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Add to the panel
panel.add(Labels.newRestoreFromBackupNote(), "grow,push");
return panel;
}
/**
* <p>A "restore from seed phrase" panel displays the instructions to restore from a seed phrase</p>
*
* @return A new "restore from seed phrase" panel
*/
public static JPanel newRestoreFromSeedPhrase() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Add to the panel
panel.add(Labels.newRestoreFromSeedPhraseNote(), "grow,push");
return panel;
}
/**
* <p>A "select backup directory" panel displays the instructions to choose an appropriate backup directory</p>
*
* @return A new "select backup directory" panel
*/
public static JPanel newSelectBackupDirectory() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Add to the panel
panel.add(Labels.newSelectBackupLocationNote(), "grow,push");
return panel;
}
/**
* <p>A "select export payments directory" panel displays the instructions to choose an appropriate export payments directory</p>
*
* @return A new "select export payments directory" panel
*/
public static JPanel newSelectExportPaymentsDirectory() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Add to the panel
panel.add(Labels.newSelectExportPaymentsLocationNote(), "grow,push");
return panel;
}
/**
* New vertical dashed separator
*/
public static JPanel newVerticalDashedSeparator() {
JPanel panel = new JPanel();
panel.setMaximumSize(new Dimension(1, 10000));
panel.setBorder(BorderFactory.createDashedBorder(Themes.currentTheme.headerPanelBackground(), 5, 5));
return panel;
}
/**
* <p>Invalidate a panel so that Swing will later redraw it properly with layout changes (normally as a result of a locale change)</p>
*
* @param panel The panel to invalidate
*/
public static void invalidate(JPanel panel) {
// Added new content so validate/repaint
panel.validate();
panel.repaint();
}
/**
* <p>Recursive method to enable or disable the focus on all components in the given container</p>
* <p>Filters components that cannot have focus by design (e.g. JLabel)</p>
*
* @param component The component
* @param allowFocus True if the components should be able to gain focus
*/
private static void allowFocus(final Component component, final boolean allowFocus) {
// Limit the focus change to those components that could grab it
if (component instanceof AbstractButton) {
component.setFocusable(allowFocus);
}
if (component instanceof JComboBox) {
component.setFocusable(allowFocus);
}
if (component instanceof JTree) {
component.setFocusable(allowFocus);
}
if (component instanceof JTextComponent) {
component.setFocusable(allowFocus);
}
if (component instanceof JTable) {
component.setFocusable(allowFocus);
}
// Recursive search
if (component instanceof Container) {
for (Component child : ((Container) component).getComponents()) {
allowFocus(child, allowFocus);
}
}
}
}
| mbhd-swing/src/main/java/org/multibit/hd/ui/views/components/Panels.java | package org.multibit.hd.ui.views.components;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.miginfocom.swing.MigLayout;
import org.multibit.hd.core.dto.CoreMessageKey;
import org.multibit.hd.core.managers.WalletManager;
import org.multibit.hd.ui.MultiBitUI;
import org.multibit.hd.ui.languages.Languages;
import org.multibit.hd.ui.languages.MessageKey;
import org.multibit.hd.ui.views.components.panels.BackgroundPanel;
import org.multibit.hd.ui.views.components.panels.LightBoxPanel;
import org.multibit.hd.ui.views.components.panels.PanelDecorator;
import org.multibit.hd.ui.views.components.panels.RoundedPanel;
import org.multibit.hd.ui.views.fonts.AwesomeDecorator;
import org.multibit.hd.ui.views.fonts.AwesomeIcon;
import org.multibit.hd.ui.views.themes.Themes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.Locale;
/**
* <p>Factory to provide the following to views:</p>
* <ul>
* <li>Creation of panels</li>
* </ul>
*
* @since 0.0.1
*/
@SuppressFBWarnings({"MS_SHOULD_BE_FINAL"})
public class Panels {
private static final Logger log = LoggerFactory.getLogger(Panels.class);
/**
* A global reference to the application frame
*/
public static JFrame applicationFrame;
private static Optional<LightBoxPanel> lightBoxPanel = Optional.absent();
private static Optional<LightBoxPanel> lightBoxPopoverPanel = Optional.absent();
/**
* <p>A default MiG layout constraint with:</p>
* <ul>
* <li>Zero insets</li>
* <li>Fills all available space (X and Y)</li>
* <li>Handles left-to-right and right-to-left presentation automatically</li>
* </ul>
*
* @return A default MiG layout constraint that fills all X and Y with RTL appended
*/
public static String migXYLayout() {
return migLayout("fill,insets 0");
}
/**
* <p>A default MiG layout constraint with:</p>
* <ul>
* <li>Zero insets</li>
* <li>Fills all available space (X only)</li>
* <li>Handles left-to-right and right-to-left presentation automatically</li>
* </ul>
*
* @return A default MiG layout constraint that fills all X with RTL appended suitable for screens
*/
public static String migXLayout() {
return migLayout("fillx,insets 0");
}
/**
* <p>A non-standard MiG layout constraint with:</p>
* <ul>
* <li>Optional "fill", "insets", "hidemode" etc</li>
* <li>Handles left-to-right and right-to-left presentation automatically</li>
* </ul>
*
* @param layout Any of the usual MiG layout constraints except RTL (e.g. "fillx,insets 1 2 3 4")
*
* @return The MiG layout constraint with RTL handling appended
*/
public static String migLayout(String layout) {
return layout + (Languages.isLeftToRight() ? "" : ",rtl");
}
/**
* <p>A default MiG layout constraint with:</p>
* <ul>
* <li>Detail screen insets</li>
* <li>Fills all available space (X and Y)</li>
* <li>Handles left-to-right and right-to-left presentation automatically</li>
* </ul>
*
* @return A MiG layout constraint that fills all X and Y with RTL appended suitable for detail views
*/
public static String migXYDetailLayout() {
return migLayout("fill,insets 10 5 5 5");
}
/**
* <p>A default MiG layout constraint with:</p>
* <ul>
* <li>Popover screen insets</li>
* <li>Fills all available space (X only)</li>
* <li>Handles left-to-right and right-to-left presentation automatically</li>
* </ul>
*
* @return A MiG layout constraint that fills all X with RTL appended suitable for popovers
*/
public static String migXPopoverLayout() {
return migLayout("fill,insets 10 10 10 10");
}
/**
* @return A simple theme-aware panel with a single cell MigLayout that fills all X and Y
*/
public static JPanel newPanel() {
return Panels.newPanel(
new MigLayout(
migXYLayout(), // Layout
"[]", // Columns
"[]" // Rows
));
}
/**
* @param layout The layout manager for the panel (typically MigLayout)
*
* @return A simple theme-aware detail panel with the given layout
*/
public static JPanel newPanel(LayoutManager2 layout) {
JPanel panel = new JPanel(layout);
// Theme
panel.setBackground(Themes.currentTheme.detailPanelBackground());
// Force transparency
panel.setOpaque(false);
// Ensure LTR and RTL is detected by the layout
panel.applyComponentOrientation(Languages.currentComponentOrientation());
return panel;
}
/**
* @return A simple panel with rounded corners and a single column MigLayout
*/
public static JPanel newRoundedPanel() {
return newRoundedPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
}
/**
* @param layout The MiGLayout to use
*
* @return A simple panel with rounded corners
*/
public static JPanel newRoundedPanel(LayoutManager2 layout) {
JPanel panel = new RoundedPanel(layout);
// Theme
panel.setBackground(Themes.currentTheme.detailPanelBackground());
panel.setForeground(Themes.currentTheme.fadedText());
return panel;
}
/**
* @param icon The Awesome icon to use as the basis of the image for consistent LaF
*
* @return A theme-aware panel with rounded corners and a single cell MigLayout
*/
public static BackgroundPanel newDetailBackgroundPanel(AwesomeIcon icon) {
// Create an image from the AwesomeIcon
Image image = ImageDecorator.toImageIcon(
AwesomeDecorator.createIcon(
icon,
Themes.currentTheme.fadedText(),
MultiBitUI.HUGE_ICON_SIZE
)).getImage();
BackgroundPanel panel = new BackgroundPanel(image, BackgroundPanel.ACTUAL);
panel.setLayout(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
panel.setAlpha(MultiBitUI.DETAIL_PANEL_BACKGROUND_ALPHA);
panel.setPaint(Themes.currentTheme.detailPanelBackground());
panel.setBackground(Themes.currentTheme.detailPanelBackground());
return panel;
}
/**
* <p>Test if a light box is showing</p>
*
* @return True if the light box panel is visible
*/
public synchronized static boolean isLightBoxShowing() {
return lightBoxPanel.isPresent();
}
/**
* <p>Show a light box</p>
*
* @param panel The panel to act as the focus of the light box
*/
public synchronized static void showLightBox(JPanel panel) {
log.debug("Show light box");
Preconditions.checkState(SwingUtilities.isEventDispatchThread(), "LightBox requires the EDT");
// Do not override this to replace the existing light box
// The problem is that the new light box is tripping up due to a race condition in the code
// which needs to be dealt with rather than masked behind deferred clean up
Preconditions.checkState(!lightBoxPanel.isPresent(), "Light box should never be called twice ");
// Prevent focus
allowFocus(Panels.applicationFrame, false);
// Add the light box panel
lightBoxPanel = Optional.of(new LightBoxPanel(panel, JLayeredPane.MODAL_LAYER));
}
/**
* <p>Hides the currently showing light box panel (and any popover)</p>
*/
public synchronized static void hideLightBoxIfPresent() {
Preconditions.checkState(SwingUtilities.isEventDispatchThread(), "LightBoxPopover requires the EDT");
log.debug("Hide light box (if present)");
hideLightBoxPopoverIfPresent();
if (lightBoxPanel.isPresent()) {
lightBoxPanel.get().close();
}
lightBoxPanel = Optional.absent();
// Finally allow focus
allowFocus(Panels.applicationFrame, true);
}
/**
* <p>Test if a light box popover is showing</p>
*
* @return True if the popover panel is visible
*/
public synchronized static boolean isLightBoxPopoverShowing() {
return lightBoxPopoverPanel.isPresent();
}
/**
* <p>Show a light box pop over</p>
*
* @param panel The panel to act as the focus of the popover
*/
public synchronized static void showLightBoxPopover(JPanel panel) {
log.debug("Show light box popover");
Preconditions.checkState(SwingUtilities.isEventDispatchThread(), "LightBoxPopover requires the EDT");
Preconditions.checkState(lightBoxPanel.isPresent(), "LightBoxPopover should not be called unless a light box is showing");
Preconditions.checkState(!lightBoxPopoverPanel.isPresent(), "LightBoxPopover should never be called twice");
lightBoxPopoverPanel = Optional.of(new LightBoxPanel(panel, JLayeredPane.DRAG_LAYER));
}
/**
* <p>Hides the currently showing light box popover panel</p>
*/
public synchronized static void hideLightBoxPopoverIfPresent() {
Preconditions.checkState(SwingUtilities.isEventDispatchThread(), "LightBoxPopover requires the EDT");
log.debug("Hide light box popover (if present)");
if (lightBoxPopoverPanel.isPresent()) {
// A popover is not part of a handover so gets closed completely
lightBoxPopoverPanel.get().close();
}
lightBoxPopoverPanel = Optional.absent();
}
/**
* <p>An "exit selector" panel confirms an exit or switch operation</p>
*
* @param listener The action listener
* @param exitCommand The exit command name
* @param switchCommand The switch command name
*
* @return A new "exit selector" panel
*/
public static JPanel newExitSelector(
ActionListener listener,
String exitCommand,
String switchCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.EXIT_WALLET);
radio1.setSelected(true);
radio1.setActionCommand(exitCommand);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.SWITCH_WALLET);
radio2.setActionCommand(switchCommand);
// Wallet selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
return panel;
}
/**
* <p>A "licence selector" panel provides a means of ensuring the user agrees with the licence</p>
*
* @param listener The action listener
* @param agreeCommand The agree command name
* @param disagreeCommand The disagree command name
*
* @return A new "licence selector" panel
*/
public static JPanel newLicenceSelector(
ActionListener listener,
String agreeCommand,
String disagreeCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.ACCEPT_LICENCE);
radio1.setActionCommand(agreeCommand);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.REJECT_LICENCE);
radio2.setSelected(true);
radio2.setActionCommand(disagreeCommand);
// Wallet selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
return panel;
}
/**
* <p>A standard "wallet selector" panel provides a means of choosing how a wallet is to be created/accessed</p>
*
* @param listener The action listener
* @param createCommand The create command name
* @param existingWalletCommand The existing wallet command name
* @param restorePasswordCommand The restore credentials command name
* @param restoreWalletCommand The restore wallet command name
*
* @return A new "wallet selector" panel
*/
public static JPanel newWalletSelector(
ActionListener listener,
String createCommand,
String existingWalletCommand,
String restorePasswordCommand,
String restoreWalletCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.CREATE_WALLET);
radio1.setSelected(true);
radio1.setActionCommand(createCommand);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.USE_EXISTING_WALLET);
radio2.setActionCommand(existingWalletCommand);
JRadioButton radio3 = RadioButtons.newRadioButton(listener, MessageKey.RESTORE_PASSWORD);
radio3.setActionCommand(restorePasswordCommand);
JRadioButton radio4 = RadioButtons.newRadioButton(listener, MessageKey.RESTORE_WALLET);
radio4.setActionCommand(restoreWalletCommand);
// Check for existing wallets
if (WalletManager.getSoftWalletSummaries(Optional.<Locale>absent()).isEmpty()) {
radio2.setEnabled(false);
radio2.setForeground(UIManager.getColor("RadioButton.disabledText"));
}
// Wallet selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
group.add(radio3);
group.add(radio4);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
panel.add(radio3, "wrap");
panel.add(radio4, "wrap");
return panel;
}
/**
* <p>A "hardware wallet selector" panel provides a means of choosing how a hardware wallet is to be created/accessed</p>
*
* @param listener The action listener
* @param createCommand The create command name
* @param existingWalletCommand The existing wallet command name
* @param restoreWalletCommand The restore wallet command name
*
* @return A new "wallet selector" panel
*/
public static JPanel newHardwareWalletSelector(
ActionListener listener,
String createCommand,
String existingWalletCommand,
String restoreWalletCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.TREZOR_CREATE_WALLET);
radio1.setSelected(true);
radio1.setActionCommand(createCommand);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.USE_EXISTING_WALLET);
radio2.setActionCommand(existingWalletCommand);
JRadioButton radio3 = RadioButtons.newRadioButton(listener, MessageKey.RESTORE_WALLET);
radio3.setActionCommand(restoreWalletCommand);
// Check for existing wallets
if (WalletManager.getWalletSummaries().isEmpty()) {
radio2.setEnabled(false);
radio2.setForeground(UIManager.getColor("RadioButton.disabledText"));
}
// Wallet selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
group.add(radio3);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
panel.add(radio3, "wrap");
return panel;
}
/**
* <p>A "Trezor select PIN" panel provides a means of choosing how a device PIN is to be changed/removed</p>
*
* @param listener The action listener
* @param changeCommand The change PIN command name
* @param removeCommand The remove PIN command name
*
* @return A new "wallet selector" panel
*/
public static JPanel newChangePinSelector(
ActionListener listener,
String changeCommand,
String removeCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.CHANGE_PIN_OPTION);
radio1.setSelected(true);
radio1.setActionCommand(changeCommand);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.REMOVE_PIN_OPTION);
radio2.setActionCommand(removeCommand);
// Wallet selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
return panel;
}
/**
* <p>A "Trezor tool selector" panel provides a means of choosing which Trezor tool to run</p>
*
* @param listener The action listener
* @param buyTrezorCommand The buy trezor command
* @param verifyDeviceCommand The verify device command name
* @param wipeDeviceCommand The wipe device command name
*
* @return A new "use Trezor selector" panel
*/
public static JPanel newUseTrezorSelector(
ActionListener listener,
String buyTrezorCommand,
String verifyDeviceCommand,
String wipeDeviceCommand
) {
JPanel panel = Panels.newPanel();
JRadioButton radio1 = RadioButtons.newRadioButton(listener, MessageKey.BUY_TREZOR);
radio1.setActionCommand(buyTrezorCommand);
radio1.setSelected(true);
JRadioButton radio2 = RadioButtons.newRadioButton(listener, MessageKey.VERIFY_DEVICE);
radio2.setActionCommand(verifyDeviceCommand);
JRadioButton radio3 = RadioButtons.newRadioButton(listener, MessageKey.WIPE_DEVICE);
radio3.setActionCommand(wipeDeviceCommand);
// Action selection is mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
group.add(radio3);
// Add to the panel
panel.add(radio1, "wrap");
panel.add(radio2, "wrap");
panel.add(radio3, "wrap");
return panel;
}
/**
* <p>A "confirm seed phrase" panel displays the instructions to enter the seed phrase from a piece of paper</p>
*
* @return A new "confirm seed phrase" panel
*/
public static JPanel newConfirmSeedPhrase() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXYLayout(),
"[]", // Columns
"[]" // Rows
));
// Add to the panel
panel.add(Labels.newConfirmSeedPhraseNote(), "grow,push");
return panel;
}
/**
* <p>A "debugger warning" panel displays instructions to the user about a debugger being attached</p>
*
* @return A new "debugger warning" panel
*/
public static JPanel newDebuggerWarning() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Ensure it is accessible
AccessibilityDecorator.apply(panel, CoreMessageKey.DEBUGGER_ATTACHED);
PanelDecorator.applyDangerFadedTheme(panel);
// Add to the panel
panel.add(Labels.newDebuggerWarningNote(), "w 350");
return panel;
}
/**
* <p>An "unsupported firmware" panel displays instructions to the user about a hardware wallet with unsupported firmware (security risk) being attached</p>
*
* @return A new "unsupported firmware" panel
*/
public static JPanel newUnsupportedFirmware() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Ensure it is accessible
AccessibilityDecorator.apply(panel, CoreMessageKey.UNSUPPORTED_FIRMWARE_ATTACHED);
PanelDecorator.applyWarningTheme(panel);
// Add to the panel
panel.add(Labels.newUnsupportedFirmwareNote(), "w 350");
return panel;
}
/**
* <p>A "language change" panel displays instructions to the user about a language change</p>
*
* @return A new "language change" panel
*/
public static JPanel newLanguageChange() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
PanelDecorator.applySuccessFadedTheme(panel);
// Add to the panel
panel.add(Labels.newLanguageChangeNote(), "grow,push");
return panel;
}
/**
* <p>A "restore from backup" panel displays the instructions to restore from a backup folder</p>
*
* @return A new "restore from backup" panel
*/
public static JPanel newRestoreFromBackup() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Add to the panel
panel.add(Labels.newRestoreFromBackupNote(), "grow,push");
return panel;
}
/**
* <p>A "restore from seed phrase" panel displays the instructions to restore from a seed phrase</p>
*
* @return A new "restore from seed phrase" panel
*/
public static JPanel newRestoreFromSeedPhrase() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Add to the panel
panel.add(Labels.newRestoreFromSeedPhraseNote(), "grow,push");
return panel;
}
/**
* <p>A "select backup directory" panel displays the instructions to choose an appropriate backup directory</p>
*
* @return A new "select backup directory" panel
*/
public static JPanel newSelectBackupDirectory() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Add to the panel
panel.add(Labels.newSelectBackupLocationNote(), "grow,push");
return panel;
}
/**
* <p>A "select export payments directory" panel displays the instructions to choose an appropriate export payments directory</p>
*
* @return A new "select export payments directory" panel
*/
public static JPanel newSelectExportPaymentsDirectory() {
JPanel panel = Panels.newPanel(
new MigLayout(
Panels.migXLayout(),
"[]", // Columns
"[]" // Rows
));
// Add to the panel
panel.add(Labels.newSelectExportPaymentsLocationNote(), "grow,push");
return panel;
}
/**
* New vertical dashed separator
*/
public static JPanel newVerticalDashedSeparator() {
JPanel panel = new JPanel();
panel.setMaximumSize(new Dimension(1, 10000));
panel.setBorder(BorderFactory.createDashedBorder(Themes.currentTheme.headerPanelBackground(), 5, 5));
return panel;
}
/**
* <p>Invalidate a panel so that Swing will later redraw it properly with layout changes (normally as a result of a locale change)</p>
*
* @param panel The panel to invalidate
*/
public static void invalidate(JPanel panel) {
// Added new content so validate/repaint
panel.validate();
panel.repaint();
}
/**
* <p>Recursive method to enable or disable the focus on all components in the given container</p>
* <p>Filters components that cannot have focus by design (e.g. JLabel)</p>
*
* @param component The component
* @param allowFocus True if the components should be able to gain focus
*/
private static void allowFocus(final Component component, final boolean allowFocus) {
// Limit the focus change to those components that could grab it
if (component instanceof AbstractButton) {
component.setFocusable(allowFocus);
}
if (component instanceof JComboBox) {
component.setFocusable(allowFocus);
}
if (component instanceof JTree) {
component.setFocusable(allowFocus);
}
if (component instanceof JTextComponent) {
component.setFocusable(allowFocus);
}
if (component instanceof JTable) {
component.setFocusable(allowFocus);
}
// Recursive search
if (component instanceof Container) {
for (Component child : ((Container) component).getComponents()) {
allowFocus(child, allowFocus);
}
}
}
}
| #427 Findbugs: Changed annotation and widened bug filter
| mbhd-swing/src/main/java/org/multibit/hd/ui/views/components/Panels.java | #427 Findbugs: Changed annotation and widened bug filter | <ide><path>bhd-swing/src/main/java/org/multibit/hd/ui/views/components/Panels.java
<ide>
<ide> import com.google.common.base.Optional;
<ide> import com.google.common.base.Preconditions;
<del>import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
<ide> import net.miginfocom.swing.MigLayout;
<ide> import org.multibit.hd.core.dto.CoreMessageKey;
<ide> import org.multibit.hd.core.managers.WalletManager;
<ide> * @since 0.0.1
<ide> */
<ide>
<del>@SuppressFBWarnings({"MS_SHOULD_BE_FINAL"})
<ide> public class Panels {
<ide>
<ide> private static final Logger log = LoggerFactory.getLogger(Panels.class);
<ide> /**
<ide> * A global reference to the application frame
<ide> */
<add> @edu.umd.cs.findbugs.annotations.SuppressWarnings({
<add> "MS_SHOULD_BE_FINAL",
<add> "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"
<add> })
<ide> public static JFrame applicationFrame;
<ide>
<ide> private static Optional<LightBoxPanel> lightBoxPanel = Optional.absent(); |
|
Java | mit | 7b57e652b5fc59f6375f8c053cd10e2a61a2e198 | 0 | baseballlover723/Avvo-interview-challenge | package testing;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Test;
import enums.Color;
import enums.Number;
import enums.Shading;
import enums.Shape;
import setGame.Board;
import setGame.Card;
import setGame.Set;
public class BoardTest {
@Test
public void hasSetRevealedTest() {
Card card1 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.ONE);
Card card2 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.TWO);
Card card3 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.THREE);
Card card4 = new Card(Color.RED, Shape.SQUIGGLE, Shading.EMPTY, Number.ONE);
Card card5 = new Card(Color.RED, Shape.SQUIGGLE, Shading.STRIPED, Number.ONE);
Board board = new Board(new Card[] { card1, card2, card3, card4, card5 });
assertTrue(board.hasSetRevealed());
}
@Test
public void hasNoSetRevealedTest() {
Card card1 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.ONE);
Card card3 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.THREE);
Card card4 = new Card(Color.RED, Shape.SQUIGGLE, Shading.EMPTY, Number.ONE);
Card card10 = new Card(Color.GREEN, Shape.DIAMOND, Shading.EMPTY, Number.TWO);
Board board = new Board(new Card[] { card1, card3, card4, card10 });
assertFalse(board.hasSetRevealed());
board = new Board(new Card[] { card1, card3 });
assertFalse(board.hasSetRevealed());
}
@Test
public void removeRevealedSetTest() {
Card card1 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.ONE);
Card card2 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.TWO);
Card card3 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.THREE);
Card card4 = new Card(Color.RED, Shape.SQUIGGLE, Shading.EMPTY, Number.ONE);
Card card5 = new Card(Color.RED, Shape.SQUIGGLE, Shading.STRIPED, Number.ONE);
Set expectedSet = new Set(card1, card2, card3);
Card[] cards = new Card[] { card1, card2, card3, card4, card5 };
Collections.shuffle(Arrays.asList(cards));
Board board = new Board(cards);
Set blah = board.removeRevealedSet();
System.out.println(Arrays.toString(expectedSet.getCards()));
System.out.println();
System.out.println(Arrays.toString(blah.getCards()));
assertEquals(expectedSet, blah);
}
}
| src/testing/BoardTest.java | package testing;
import static org.junit.Assert.*;
import org.junit.Test;
import enums.Color;
import enums.Number;
import enums.Shading;
import enums.Shape;
import setGame.Board;
import setGame.Card;
import setGame.Deck;
public class BoardTest {
@Test
public void hasSetRevealedTest() {
Card card1 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.ONE);
Card card2 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.TWO);
Card card3 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.THREE);
Card card4 = new Card(Color.RED, Shape.SQUIGGLE, Shading.EMPTY, Number.ONE);
Card card5 = new Card(Color.RED, Shape.SQUIGGLE, Shading.STRIPED, Number.ONE);
Board board = new Board(new Card[] { card1, card2, card3, card4, card5 });
assertTrue(board.hasSetRevealed());
}
@Test
public void hasNoSetRevealedTest() {
Card card1 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.ONE);
Card card3 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.THREE);
Card card4 = new Card(Color.RED, Shape.SQUIGGLE, Shading.EMPTY, Number.ONE);
Card card10 = new Card(Color.GREEN, Shape.DIAMOND, Shading.EMPTY, Number.TWO);
Board board = new Board(new Card[] { card1, card3, card4, card10 });
assertFalse(board.hasSetRevealed());
board = new Board(new Card[] { card1, card3 });
assertFalse(board.hasSetRevealed());
}
}
| added test for removing sets from the board
| src/testing/BoardTest.java | added test for removing sets from the board | <ide><path>rc/testing/BoardTest.java
<ide> package testing;
<ide>
<ide> import static org.junit.Assert.*;
<add>
<add>import java.util.Arrays;
<add>import java.util.Collections;
<ide>
<ide> import org.junit.Test;
<ide>
<ide> import enums.Shape;
<ide> import setGame.Board;
<ide> import setGame.Card;
<del>import setGame.Deck;
<add>import setGame.Set;
<ide>
<ide> public class BoardTest {
<ide> @Test
<ide> board = new Board(new Card[] { card1, card3 });
<ide> assertFalse(board.hasSetRevealed());
<ide> }
<add>
<add> @Test
<add> public void removeRevealedSetTest() {
<add> Card card1 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.ONE);
<add> Card card2 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.TWO);
<add> Card card3 = new Card(Color.RED, Shape.SQUIGGLE, Shading.SOLID, Number.THREE);
<add> Card card4 = new Card(Color.RED, Shape.SQUIGGLE, Shading.EMPTY, Number.ONE);
<add> Card card5 = new Card(Color.RED, Shape.SQUIGGLE, Shading.STRIPED, Number.ONE);
<add>
<add> Set expectedSet = new Set(card1, card2, card3);
<add>
<add> Card[] cards = new Card[] { card1, card2, card3, card4, card5 };
<add> Collections.shuffle(Arrays.asList(cards));
<add>
<add> Board board = new Board(cards);
<add> Set blah = board.removeRevealedSet();
<add> System.out.println(Arrays.toString(expectedSet.getCards()));
<add> System.out.println();
<add> System.out.println(Arrays.toString(blah.getCards()));
<add> assertEquals(expectedSet, blah);
<add>
<add> }
<ide> } |
|
JavaScript | apache-2.0 | 27c529015386dbbc7682b695f35d3183026f84b6 | 0 | miikarntkl/fb-bot | 'use strict';
const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');
const JSONbig = require('json-bigint');
const async = require('async');
const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'en';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;
const FS_CLIENT_SECRET = process.env.FS_CLIENT_SECRET;
const FS_CLIENT_ID = process.env.FS_CLIENT_ID;
const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();
const foursquareVersion = '20160108';
const venueCategories = {
food: {
name: 'food',
payload: 'PAYLOAD_FOOD'
},
drinks: {
name: 'drinks',
payload: 'PAYLOAD_DRINKS'
},
coffee: {
name: 'coffee',
payload: 'PAYLOAD_COFFEE'
},
shops: {
name: 'shops',
payload: 'PAYLOAD_SHOPS'
},
arts: {
name: 'arts',
payload: 'PAYLOAD_ARTS'
},
topPicks: {
name: 'topPicks',
payload: 'PAYLOAD_TOPPICKS'
}
};
const defaultCategory = venueCategories.topPicks.name;
var suggestionLimit = 5;
var closestFirst = 0;
const actionFindVenue = 'findVenue';
const intentFindVenue = 'FindVenue';
const persistentMenu = {
help: 'PAYLOAD_HELP',
enable_quick_replies: 'PAYLOAD_ENABLE_QUICK_REPLIES',
disable_quick_replies: 'PAYLOAD_DISABLE_QUICK_REPLIES',
};
function processEvent(event) {
var sender = event.sender.id.toString();
if ((event.message && event.message.text) || (event.message && event.message.attachments)) {
var text = event.message.text;
if (!isDefined(text)) {
waitForLocation(event.message.attachments, 0);
}
// Handle a message from this sender
if (!sessionIds.has(sender)) {
sessionIds.set(sender, uuid.v1());
}
console.log("Text:", text);
let apiaiRequest = apiAiService.textRequest(text,
{
sessionId: sessionIds.get(sender)
});
apiaiRequest.on('response', (response) => {
if (isDefined(response.result)) {
let responseText = response.result.fulfillment.speech;
let responseData = response.result.fulfillment.data;
var action = response.result.action;
var intentName = response.result.metadata.intentName;
var parameters = response.result.parameters;
console.log(action);
if (isDefined(responseData) && isDefined(responseData.facebook)) {
if (!Array.isArray(responseData.facebook)) {
try {
console.log('Response as formatted message');
sendFBMessage(sender, responseData.facebook);
} catch (err) {
sendFBMessage(sender, {text: err.message});
}
} else {
async.eachSeries(responseData.facebook, (facebookMessage, callback) => {
try {
if (facebookMessage.sender_action) {
console.log('Response as sender action');
sendFBSenderAction(sender, facebookMessage.sender_action, callback);
}
else {
console.log('Response as formatted message');
sendFBMessage(sender, facebookMessage, callback);
}
} catch (err) {
sendFBMessage(sender, {text: err.message}, callback);
}
});
}
} else if (isDefined(responseText)) {
textResponse(responseText, sender);
} else if (isDefined(action) && isDefined(intentName)) {
if (action === actionFindVenue && intentName == intentFindVenue) { //check for findvenue action and intent
if (isDefined(parameters)) {
findVenue(parameters, (foursquareResponse) => { //find venues according to parameters
if (isDefined(foursquareResponse)) {
let formatted = formatVenueData(foursquareResponse); //format response data for fb
if (isDefined(formatted) && formatted.length > 0) {
sendFBGenericMessage(sender, formatted); //send data as fb cards
} else {
requestLocation(sender); //ask for location if not provided
}
} else {
requestLocation(sender);
}
});
}
}
}
}
});
apiaiRequest.on('error', (error) => console.error(error));
apiaiRequest.end();
}
else if (event.postback && event.postback.payload) {
executePostback(sender, event.postback.payload);
}
}
function waitForLocation(attachments, callCount) {
try {
var url = attachments.url;
console.log('url: ', url);
if (!isDefined(url)) {
setTimeout(function() {
waitForLocation(attachments, callCount + 1);
}, 100);
} else {
return url;
}
} catch (e) {
console.log('CallCount: ', callCount);
setTimeout(function() {
waitForLocation(attachments, callCount + 1);
}, 100);
}
console.log('x: ', x);
return null;
}
function textResponse(str, sender) {
console.log('Response as text message');
// facebook API limit for text length is 320,
// so we must split message if needed
var splittedText = splitResponse(str);
async.eachSeries(splittedText, (textPart, callback) => {
sendFBMessage(sender, {text: textPart}, callback);
});
}
function splitResponse(str) {
if (str.length <= 320) {
return [str];
}
return chunkString(str, 300);
}
function chunkString(s, len) {
var curr = len, prev = 0;
var output = [];
while (s[curr]) {
if (s[curr++] == ' ') {
output.push(s.substring(prev, curr));
prev = curr;
curr += len;
}
else {
var currReverse = curr;
do {
if (s.substring(currReverse - 1, currReverse) == ' ') {
output.push(s.substring(prev, currReverse));
prev = currReverse;
curr = currReverse + len;
break;
}
currReverse--;
} while (currReverse > prev);
}
}
output.push(s.substr(prev));
return output;
}
function sendFBMessage(sender, messageData, callback) {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: FB_PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
recipient: {id: sender},
message: messageData
}
}, (error, response, body) => {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
if (callback) {
callback();
}
});
}
function sendFBGenericMessage(sender, messageData, callback) {
console.log('Sending card message');
var cardOptions = {
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: FB_PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
recipient: {id: sender},
message: {
attachment: {
type:'template',
payload: {
template_type:'generic',
elements: []
}
}
}
}
};
for (let i = 0; i < suggestionLimit; i++) {
cardOptions.json.message.attachment.payload.elements.push(messageData[i]);
}
request(cardOptions, (error, response, body) => {
if (error) {
console.log('Error sending card: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
if (callback) {
callback();
}
});
}
function sendFBSenderAction(sender, action, callback) {
setTimeout(() => {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: FB_PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
recipient: {id: sender},
sender_action: action
}
}, (error, response, body) => {
if (error) {
console.log('Error sending action: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
if (callback) {
callback();
}
});
}, 1000);
}
function requestCategory(sender) { //enables guided UI with quick replies
var message = {
text: 'Please choose a category:',
quick_replies: [
{
content_type: 'text',
title: 'Food',
payload: venueCategories.food.payload,
},
{
content_type: 'text',
title: 'Drinks',
payload: venueCategories.drinks.payload,
},
{
content_type: 'text',
title: 'Coffee',
payload: venueCategories.coffee.payload,
},
{
content_type: 'text',
title: 'Shops',
payload: venueCategories.shops.payload,
},
{
content_type: 'text',
title: 'Arts',
payload: venueCategories.arts.payload,
},
{
content_type: 'text',
title: 'Top Picks',
payload: venueCategories.topPicks.payload,
},
]
};
sendFBMessage(sender, message);
}
function requestLocation(sender) {
var message = {
text: 'Please give me a location:',
quick_replies: [
{
content_type: 'location',
}
]
};
sendFBMessage(sender, message);
}
function executePostback(sender, postback) {
switch (postback) {
case persistentMenu.help:
console.log('Help');
break;
case persistentMenu.enable_quick_replies:
console.log('Enable quick replies');
requestCategory(sender);
break;
case persistentMenu.disable_quick_replies:
console.log('Disable quick replies');
break;
default:
console.log('No relevant postback found!');
}
}
function configureThreadSettings(settings, callback) { //configure FB messenger thread settings
console.log('Configuring thread settings'); //for now only for adding persistent menu
var options = {
url: 'https://graph.facebook.com/v2.6/me/thread_settings',
qs: {access_token: FB_PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
setting_type: 'call_to_actions',
thread_state: 'existing_thread',
call_to_actions: [
{
type: 'postback',
title: 'Help',
payload: 'PAYLOAD_HELP'
},
{
type: 'postback',
title: 'Enable Quick Replies',
payload: 'PAYLOAD_ENABLE_QUICK_REPLIES'
},
{
type: 'postback',
title: 'Disable Quick Replies',
payload: 'PAYLOAD_DISABLE_QUICK_REPLIES'
}
]
}
};
request(options, (error, response, body) => {
if (error) {
console.log('Error configuring thread settings: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
if (callback) {
callback();
}
});
}
function doSubscribeRequest() {
request({
method: 'POST',
uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
},
(error, response, body) => {
if (error) {
console.error('Error while subscription: ', error);
} else {
console.log('Subscription result: ', response.body);
}
});
}
function isDefined(obj) {
if (typeof obj == 'undefined') {
return false;
}
if (!obj) {
return false;
}
return obj != null;
}
function formatVenueData(raw) {
if (!isDefined(raw.response.groups)) {
return null;
}
var items = raw.response.groups[0].items;
var venues = [];
var j = 0;
if (isDefined(items)) {
for (let i = 0; i < suggestionLimit; i++) {
var venue = items[i].venue;
//add venue name
var formatted = {};
if (!isDefined(venue.name) || !isDefined(venue.id)) {
continue;
}
formatted.title = venue.name;
//add venue photo
if (venue.photos.count > 0 && isDefined(venue.photos.groups[0])) {
let prefix = venue.photos.groups[0].items[0].prefix;
let suffix = venue.photos.groups[0].items[0].suffix;
let original = 'original';
formatted.image_url = prefix.concat(original, suffix);
}
//add venue hours
if (isDefined(venue.hours) && isDefined(venue.hours.status)) {
formatted.subtitle = venue.hours.status;
} else {
formatted.subtitle = '';
}
formatted.buttons = [];
j = 0;
//add link to venue
formatted.buttons[j] = {
type: 'web_url',
title: 'View Website',
};
if (isDefined(venue.url)) {
formatted.buttons[j].url = venue.url;
j++;
} else {
formatted.buttons[j].url = 'http://foursquare.com/v/'.concat(venue.id);
j++;
}
//add link to venue's location on google maps
if (isDefined(venue.location)) {
var loc = null;
if (isDefined(venue.location.address) && isDefined(venue.location.city)) {
loc = venue.location.address.concat(' ', venue.location.city);
if (isDefined(venue.location.postalCode)) {
loc = loc.concat(' ', venue.location.postalCode);
}
if (isDefined(venue.location.country)) {
loc = loc.concat(' ', venue.location.country);
}
}
if (!isDefined(loc) && isDefined(venue.location.lat) && isDefined(venue.location.lng)) {
let lat = venue.location.lat;
let long = venue.location.lng;
loc = lat.toString().concat(',', long.toString());
}
if (isDefined(loc)) {
formatted.buttons[j] = {
type: 'web_url',
title: 'Show On Map',
};
formatted.buttons[j].url = 'http://maps.google.com/?q='.concat(loc);
j++;
}
}
venues.push(formatted);
}
}
return venues;
}
function formatGETOptions(parameters) {
var venueType = defaultCategory;
if (isDefined(parameters.venueType)) {
venueType = parameters.venueType;
}
console.log('Address: ', isDefined(parameters.location));
console.log('Coordinates: ', isDefined(parameters.coordinates));
console.log('Venue: ', isDefined(parameters.venueType));
var options = {
method: 'GET',
url: 'http://api.foursquare.com/v2/venues/explore',
qs: {
client_id: FS_CLIENT_ID,
client_secret: FS_CLIENT_SECRET,
v: foursquareVersion,
m: 'foursquare',
section: venueType,
limit: suggestionLimit,
sortByDistance: closestFirst,
venuePhotos: 1,
},
json: true,
};
console.log('VenueType: ', venueType);
console.log('Venue: ', options.qs.section);
var loc = null;
if (isDefined(parameters.location)) {
console.log('Location defined');
if (isDefined(parameters.location.location)) { //location as address
options.qs.near = parameters.location.location;
}
} else if (isDefined(parameters.coordinates) && isDefined(parameters.coordinates.lat) && isDefined(parameters.coordinates.long)) {
console.log('Coordinates defined'); //location as coordinates
let lat = parameters.coordinates.lat;
let long = parameters.coordinates.long;
if (lat > 90 || lat < -90 || long > 180 || long < -180) {
return null;
}
options.qs.ll = lat.toString().concat(', ', long.toString());
} else {
return null;
}
return options;
}
function findVenue(parameters, callback) {
var options = formatGETOptions(parameters);
if (isDefined(options)) {
request(options, (error, res, body) => {
if (error) {
console.error('GET Error: ', error);
} else {
callback(body);
}
});
} else {
callback(null);
}
}
const app = express();
app.use(bodyParser.text({type: 'application/json'}));
app.get('/webhook/', (req, res) => {
if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
res.send(req.query['hub.challenge']);
setTimeout(() => {
doSubscribeRequest();
}, 3000);
} else {
res.send('Error, wrong validation token');
}
});
app.post('/webhook/', (req, res) => {
try {
var data = JSONbig.parse(req.body);
if (data.entry) {
let entries = data.entry;
entries.forEach((entry) => {
let messaging_events = entry.messaging;
if (messaging_events) {
messaging_events.forEach((event) => {
if (event.message && !event.message.is_echo ||
event.postback && event.postback.payload) {
console.log('Processing event');
processEvent(event);
}
});
}
});
}
return res.status(200).json({
status: "ok"
});
} catch (err) {
console.log('Webhook error: ', err.message);
return res.status(400).json({
status: "error",
error: err
});
}
});
app.listen(REST_PORT, () => {
console.log('Rest service ready on port ' + REST_PORT);
});
doSubscribeRequest();
configureThreadSettings(null); | src/app.js | 'use strict';
const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');
const JSONbig = require('json-bigint');
const async = require('async');
const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'en';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;
const FS_CLIENT_SECRET = process.env.FS_CLIENT_SECRET;
const FS_CLIENT_ID = process.env.FS_CLIENT_ID;
const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();
const foursquareVersion = '20160108';
const venueCategories = {
food: {
name: 'food',
payload: 'PAYLOAD_FOOD'
},
drinks: {
name: 'drinks',
payload: 'PAYLOAD_DRINKS'
},
coffee: {
name: 'coffee',
payload: 'PAYLOAD_COFFEE'
},
shops: {
name: 'shops',
payload: 'PAYLOAD_SHOPS'
},
arts: {
name: 'arts',
payload: 'PAYLOAD_ARTS'
},
topPicks: {
name: 'topPicks',
payload: 'PAYLOAD_TOPPICKS'
}
};
const defaultCategory = venueCategories.topPicks.name;
var suggestionLimit = 5;
var closestFirst = 0;
const actionFindVenue = 'findVenue';
const intentFindVenue = 'FindVenue';
const persistentMenu = {
help: 'PAYLOAD_HELP',
enable_quick_replies: 'PAYLOAD_ENABLE_QUICK_REPLIES',
disable_quick_replies: 'PAYLOAD_DISABLE_QUICK_REPLIES',
};
function processEvent(event) {
var sender = event.sender.id.toString();
if ((event.message && event.message.text) || (event.message && event.message.attachments)) {
var text = event.message.text;
if (!isDefined(text)) {
console.log('Text not defined');
var x = event.message.attachments;
try {
var y = x.url;
console.log('url: ', y);
} catch (e) {
console.log('Location error: ', e.message);
}
console.log('x: ', x);
return;
}
// Handle a message from this sender
if (!sessionIds.has(sender)) {
sessionIds.set(sender, uuid.v1());
}
console.log("Text:", text);
let apiaiRequest = apiAiService.textRequest(text,
{
sessionId: sessionIds.get(sender)
});
apiaiRequest.on('response', (response) => {
if (isDefined(response.result)) {
let responseText = response.result.fulfillment.speech;
let responseData = response.result.fulfillment.data;
var action = response.result.action;
var intentName = response.result.metadata.intentName;
var parameters = response.result.parameters;
console.log(action);
if (isDefined(responseData) && isDefined(responseData.facebook)) {
if (!Array.isArray(responseData.facebook)) {
try {
console.log('Response as formatted message');
sendFBMessage(sender, responseData.facebook);
} catch (err) {
sendFBMessage(sender, {text: err.message});
}
} else {
async.eachSeries(responseData.facebook, (facebookMessage, callback) => {
try {
if (facebookMessage.sender_action) {
console.log('Response as sender action');
sendFBSenderAction(sender, facebookMessage.sender_action, callback);
}
else {
console.log('Response as formatted message');
sendFBMessage(sender, facebookMessage, callback);
}
} catch (err) {
sendFBMessage(sender, {text: err.message}, callback);
}
});
}
} else if (isDefined(responseText)) {
textResponse(responseText, sender);
} else if (isDefined(action) && isDefined(intentName)) {
if (action === actionFindVenue && intentName == intentFindVenue) { //check for findvenue action and intent
if (isDefined(parameters)) {
findVenue(parameters, (foursquareResponse) => { //find venues according to parameters
if (isDefined(foursquareResponse)) {
let formatted = formatVenueData(foursquareResponse); //format response data for fb
if (isDefined(formatted) && formatted.length > 0) {
sendFBGenericMessage(sender, formatted); //send data as fb cards
} else {
requestLocation(sender); //ask for location if not provided
}
} else {
requestLocation(sender);
}
});
}
}
}
}
});
apiaiRequest.on('error', (error) => console.error(error));
apiaiRequest.end();
}
else if (event.postback && event.postback.payload) {
executePostback(sender, event.postback.payload);
}
}
function textResponse(str, sender) {
console.log('Response as text message');
// facebook API limit for text length is 320,
// so we must split message if needed
var splittedText = splitResponse(str);
async.eachSeries(splittedText, (textPart, callback) => {
sendFBMessage(sender, {text: textPart}, callback);
});
}
function splitResponse(str) {
if (str.length <= 320) {
return [str];
}
return chunkString(str, 300);
}
function chunkString(s, len) {
var curr = len, prev = 0;
var output = [];
while (s[curr]) {
if (s[curr++] == ' ') {
output.push(s.substring(prev, curr));
prev = curr;
curr += len;
}
else {
var currReverse = curr;
do {
if (s.substring(currReverse - 1, currReverse) == ' ') {
output.push(s.substring(prev, currReverse));
prev = currReverse;
curr = currReverse + len;
break;
}
currReverse--;
} while (currReverse > prev);
}
}
output.push(s.substr(prev));
return output;
}
function sendFBMessage(sender, messageData, callback) {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: FB_PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
recipient: {id: sender},
message: messageData
}
}, (error, response, body) => {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
if (callback) {
callback();
}
});
}
function sendFBGenericMessage(sender, messageData, callback) {
console.log('Sending card message');
var cardOptions = {
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: FB_PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
recipient: {id: sender},
message: {
attachment: {
type:'template',
payload: {
template_type:'generic',
elements: []
}
}
}
}
};
for (let i = 0; i < suggestionLimit; i++) {
cardOptions.json.message.attachment.payload.elements.push(messageData[i]);
}
request(cardOptions, (error, response, body) => {
if (error) {
console.log('Error sending card: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
if (callback) {
callback();
}
});
}
function sendFBSenderAction(sender, action, callback) {
setTimeout(() => {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: FB_PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
recipient: {id: sender},
sender_action: action
}
}, (error, response, body) => {
if (error) {
console.log('Error sending action: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
if (callback) {
callback();
}
});
}, 1000);
}
function requestCategory(sender) { //enables guided UI with quick replies
var message = {
text: 'Please choose a category:',
quick_replies: [
{
content_type: 'text',
title: 'Food',
payload: venueCategories.food.payload,
},
{
content_type: 'text',
title: 'Drinks',
payload: venueCategories.drinks.payload,
},
{
content_type: 'text',
title: 'Coffee',
payload: venueCategories.coffee.payload,
},
{
content_type: 'text',
title: 'Shops',
payload: venueCategories.shops.payload,
},
{
content_type: 'text',
title: 'Arts',
payload: venueCategories.arts.payload,
},
{
content_type: 'text',
title: 'Top Picks',
payload: venueCategories.topPicks.payload,
},
]
};
sendFBMessage(sender, message);
}
function requestLocation(sender) {
var message = {
text: 'Please give me a location:',
quick_replies: [
{
content_type: 'location',
}
]
};
sendFBMessage(sender, message);
}
function executePostback(sender, postback) {
switch (postback) {
case persistentMenu.help:
console.log('Help');
break;
case persistentMenu.enable_quick_replies:
console.log('Enable quick replies');
requestCategory(sender);
break;
case persistentMenu.disable_quick_replies:
console.log('Disable quick replies');
break;
default:
console.log('No relevant postback found!');
}
}
function configureThreadSettings(settings, callback) { //configure FB messenger thread settings
console.log('Configuring thread settings'); //for now only for adding persistent menu
var options = {
url: 'https://graph.facebook.com/v2.6/me/thread_settings',
qs: {access_token: FB_PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
setting_type: 'call_to_actions',
thread_state: 'existing_thread',
call_to_actions: [
{
type: 'postback',
title: 'Help',
payload: 'PAYLOAD_HELP'
},
{
type: 'postback',
title: 'Enable Quick Replies',
payload: 'PAYLOAD_ENABLE_QUICK_REPLIES'
},
{
type: 'postback',
title: 'Disable Quick Replies',
payload: 'PAYLOAD_DISABLE_QUICK_REPLIES'
}
]
}
};
request(options, (error, response, body) => {
if (error) {
console.log('Error configuring thread settings: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
if (callback) {
callback();
}
});
}
function doSubscribeRequest() {
request({
method: 'POST',
uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
},
(error, response, body) => {
if (error) {
console.error('Error while subscription: ', error);
} else {
console.log('Subscription result: ', response.body);
}
});
}
function isDefined(obj) {
if (typeof obj == 'undefined') {
return false;
}
if (!obj) {
return false;
}
return obj != null;
}
function formatVenueData(raw) {
if (!isDefined(raw.response.groups)) {
return null;
}
var items = raw.response.groups[0].items;
var venues = [];
var j = 0;
if (isDefined(items)) {
for (let i = 0; i < suggestionLimit; i++) {
var venue = items[i].venue;
//add venue name
var formatted = {};
if (!isDefined(venue.name) || !isDefined(venue.id)) {
continue;
}
formatted.title = venue.name;
//add venue photo
if (venue.photos.count > 0 && isDefined(venue.photos.groups[0])) {
let prefix = venue.photos.groups[0].items[0].prefix;
let suffix = venue.photos.groups[0].items[0].suffix;
let original = 'original';
formatted.image_url = prefix.concat(original, suffix);
}
//add venue hours
if (isDefined(venue.hours) && isDefined(venue.hours.status)) {
formatted.subtitle = venue.hours.status;
} else {
formatted.subtitle = '';
}
formatted.buttons = [];
j = 0;
//add link to venue
formatted.buttons[j] = {
type: 'web_url',
title: 'View Website',
};
if (isDefined(venue.url)) {
formatted.buttons[j].url = venue.url;
j++;
} else {
formatted.buttons[j].url = 'http://foursquare.com/v/'.concat(venue.id);
j++;
}
//add link to venue's location on google maps
if (isDefined(venue.location)) {
var loc = null;
if (isDefined(venue.location.address) && isDefined(venue.location.city)) {
loc = venue.location.address.concat(' ', venue.location.city);
if (isDefined(venue.location.postalCode)) {
loc = loc.concat(' ', venue.location.postalCode);
}
if (isDefined(venue.location.country)) {
loc = loc.concat(' ', venue.location.country);
}
}
if (!isDefined(loc) && isDefined(venue.location.lat) && isDefined(venue.location.lng)) {
let lat = venue.location.lat;
let long = venue.location.lng;
loc = lat.toString().concat(',', long.toString());
}
if (isDefined(loc)) {
formatted.buttons[j] = {
type: 'web_url',
title: 'Show On Map',
};
formatted.buttons[j].url = 'http://maps.google.com/?q='.concat(loc);
j++;
}
}
venues.push(formatted);
}
}
return venues;
}
function formatGETOptions(parameters) {
var venueType = defaultCategory;
if (isDefined(parameters.venueType)) {
venueType = parameters.venueType;
}
console.log('Address: ', isDefined(parameters.location));
console.log('Coordinates: ', isDefined(parameters.coordinates));
console.log('Venue: ', isDefined(parameters.venueType));
var options = {
method: 'GET',
url: 'http://api.foursquare.com/v2/venues/explore',
qs: {
client_id: FS_CLIENT_ID,
client_secret: FS_CLIENT_SECRET,
v: foursquareVersion,
m: 'foursquare',
section: venueType,
limit: suggestionLimit,
sortByDistance: closestFirst,
venuePhotos: 1,
},
json: true,
};
console.log('VenueType: ', venueType);
console.log('Venue: ', options.qs.section);
var loc = null;
if (isDefined(parameters.location)) {
console.log('Location defined');
if (isDefined(parameters.location.location)) { //location as address
options.qs.near = parameters.location.location;
}
} else if (isDefined(parameters.coordinates) && isDefined(parameters.coordinates.lat) && isDefined(parameters.coordinates.long)) {
console.log('Coordinates defined'); //location as coordinates
let lat = parameters.coordinates.lat;
let long = parameters.coordinates.long;
if (lat > 90 || lat < -90 || long > 180 || long < -180) {
return null;
}
options.qs.ll = lat.toString().concat(', ', long.toString());
} else {
return null;
}
if (isDefined(loc)) {
let message = 'Showing '.concat(venueType, ' in ', loc);
textResponse()
}
return options;
}
function findVenue(parameters, callback) {
var options = formatGETOptions(parameters);
if (isDefined(options)) {
request(options, (error, res, body) => {
if (error) {
console.error('GET Error: ', error);
} else {
callback(body);
}
});
} else {
callback(null);
}
}
const app = express();
app.use(bodyParser.text({type: 'application/json'}));
app.get('/webhook/', (req, res) => {
if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
res.send(req.query['hub.challenge']);
setTimeout(() => {
doSubscribeRequest();
}, 3000);
} else {
res.send('Error, wrong validation token');
}
});
app.post('/webhook/', (req, res) => {
try {
var data = JSONbig.parse(req.body);
if (data.entry) {
let entries = data.entry;
entries.forEach((entry) => {
let messaging_events = entry.messaging;
if (messaging_events) {
messaging_events.forEach((event) => {
if (event.message && !event.message.is_echo ||
event.postback && event.postback.payload) {
console.log('Processing event');
processEvent(event);
}
});
}
});
}
return res.status(200).json({
status: "ok"
});
} catch (err) {
console.log('Webhook error: ', err.message);
return res.status(400).json({
status: "error",
error: err
});
}
});
app.listen(REST_PORT, () => {
console.log('Rest service ready on port ' + REST_PORT);
});
doSubscribeRequest();
configureThreadSettings(null); | wait for location
| src/app.js | wait for location | <ide><path>rc/app.js
<ide> var text = event.message.text;
<ide>
<ide> if (!isDefined(text)) {
<del> console.log('Text not defined');
<del> var x = event.message.attachments;
<del> try {
<del> var y = x.url;
<del> console.log('url: ', y);
<del> } catch (e) {
<del> console.log('Location error: ', e.message);
<del> }
<del> console.log('x: ', x);
<del> return;
<add> waitForLocation(event.message.attachments, 0);
<ide> }
<ide>
<ide> // Handle a message from this sender
<ide> }
<ide> }
<ide>
<add>function waitForLocation(attachments, callCount) {
<add> try {
<add> var url = attachments.url;
<add> console.log('url: ', url);
<add> if (!isDefined(url)) {
<add> setTimeout(function() {
<add> waitForLocation(attachments, callCount + 1);
<add> }, 100);
<add> } else {
<add> return url;
<add> }
<add> } catch (e) {
<add> console.log('CallCount: ', callCount);
<add> setTimeout(function() {
<add> waitForLocation(attachments, callCount + 1);
<add> }, 100);
<add> }
<add> console.log('x: ', x);
<add> return null;
<add>}
<add>
<ide> function textResponse(str, sender) {
<ide> console.log('Response as text message');
<ide> // facebook API limit for text length is 320,
<ide> return null;
<ide> }
<ide>
<del> if (isDefined(loc)) {
<del> let message = 'Showing '.concat(venueType, ' in ', loc);
<del> textResponse()
<del> }
<del>
<ide> return options;
<ide> }
<ide> |
|
Java | apache-2.0 | 3502084019296066b03983299c9bfb5ccda883e8 | 0 | maciej-zygmunt/unitime,maciej-zygmunt/unitime,UniTime/unitime,UniTime/unitime,maciej-zygmunt/unitime,UniTime/unitime | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.unitime.timetable.onlinesectioning.custom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.unitime.localization.impl.Localization;
import org.unitime.timetable.defaults.ApplicationProperty;
import org.unitime.timetable.gwt.resources.StudentSectioningMessages;
import org.unitime.timetable.gwt.shared.CourseRequestInterface;
import org.unitime.timetable.gwt.shared.SectioningException;
import org.unitime.timetable.model.Student;
import org.unitime.timetable.model.dao.StudentDAO;
import org.unitime.timetable.model.dao._RootDAO;
import org.unitime.timetable.onlinesectioning.OnlineSectioningAction;
import org.unitime.timetable.onlinesectioning.OnlineSectioningHelper;
import org.unitime.timetable.onlinesectioning.OnlineSectioningLog;
import org.unitime.timetable.onlinesectioning.OnlineSectioningServer;
import org.unitime.timetable.onlinesectioning.server.DatabaseServer;
import org.unitime.timetable.onlinesectioning.updates.ReloadStudent;
/**
* @author Tomas Muller
*/
public class CustomCourseRequestsValidationHolder {
private static StudentSectioningMessages MSG = Localization.create(StudentSectioningMessages.class);
private static CourseRequestsValidationProvider sProvider = null;
public synchronized static CourseRequestsValidationProvider getProvider() {
if (sProvider == null) {
try {
sProvider = ((CourseRequestsValidationProvider)Class.forName(ApplicationProperty.CustomizationCourseRequestsValidation.value()).newInstance());
} catch (Exception e) {
throw new SectioningException(MSG.exceptionCourseRequestValidationProvider(e.getMessage()), e);
}
}
return sProvider;
}
public synchronized static void release() {
if (sProvider != null) {
sProvider.dispose();
sProvider = null;
}
}
public synchronized static boolean hasProvider() {
return sProvider != null || ApplicationProperty.CustomizationCourseRequestsValidation.value() != null;
}
public static class Check implements OnlineSectioningAction<CourseRequestInterface> {
private static final long serialVersionUID = 1L;
private CourseRequestInterface iRequest;
public Check withRequest(CourseRequestInterface request) {
iRequest = request;
return this;
}
public CourseRequestInterface getRequest() { return iRequest; }
@Override
public CourseRequestInterface execute(OnlineSectioningServer server, OnlineSectioningHelper helper) {
CourseRequestInterface request = getRequest();
if (CustomCourseRequestsValidationHolder.hasProvider())
CustomCourseRequestsValidationHolder.getProvider().check(server, helper, request);
return request;
}
@Override
public String name() {
return "check-overrides";
}
}
public static class Update implements OnlineSectioningAction<Boolean> {
private static final long serialVersionUID = 1L;
private Collection<Long> iStudentIds = null;
public Update forStudents(Long... studentIds) {
iStudentIds = new ArrayList<Long>();
for (Long studentId: studentIds)
iStudentIds.add(studentId);
return this;
}
public Update forStudents(Collection<Long> studentIds) {
iStudentIds = studentIds;
return this;
}
public Collection<Long> getStudentIds() { return iStudentIds; }
@Override
public Boolean execute(final OnlineSectioningServer server, final OnlineSectioningHelper helper) {
if (!CustomCourseRequestsValidationHolder.hasProvider()) return false;
final List<Long> reloadIds = new ArrayList<Long>();
try {
int nrThreads = server.getConfig().getPropertyInt("CourseRequestsValidation.NrThreads", 10);
if (nrThreads <= 1 || getStudentIds().size() <= 1) {
for (Long studentId: getStudentIds()) {
if (updateStudent(server, helper, studentId)) reloadIds.add(studentId);
}
} else {
List<Worker> workers = new ArrayList<Worker>();
Iterator<Long> studentIds = getStudentIds().iterator();
for (int i = 0; i < nrThreads; i++)
workers.add(new Worker(i, studentIds) {
@Override
protected void process(Long studentId) {
if (updateStudent(server, new OnlineSectioningHelper(helper), studentId)) {
synchronized (reloadIds) {
reloadIds.add(studentId);
}
}
}
});
for (Worker worker: workers) worker.start();
for (Worker worker: workers) {
try {
worker.join();
} catch (InterruptedException e) {
}
}
}
} finally {
if (!reloadIds.isEmpty() && !(server instanceof DatabaseServer))
server.execute(server.createAction(ReloadStudent.class).forStudents(reloadIds), helper.getUser());
}
return !reloadIds.isEmpty();
}
protected boolean updateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, Long studentId) {
helper.beginTransaction();
try {
Student student = StudentDAO.getInstance().get(studentId, helper.getHibSession());
boolean changed = false;
if (student != null) {
OnlineSectioningLog.Action.Builder action = helper.addAction(this, server.getAcademicSession());
action.setStudent(OnlineSectioningLog.Entity.newBuilder()
.setUniqueId(studentId)
.setExternalId(student.getExternalUniqueId())
.setName(helper.getStudentNameFormat().format(student))
.setType(OnlineSectioningLog.Entity.EntityType.STUDENT));
long c0 = OnlineSectioningHelper.getCpuTime();
try {
if (CustomCourseRequestsValidationHolder.getProvider().updateStudent(server, helper, student, action)) {
changed = true;
action.setResult(OnlineSectioningLog.Action.ResultType.TRUE);
} else {
action.setResult(OnlineSectioningLog.Action.ResultType.FALSE);
}
} catch (SectioningException e) {
action.setResult(OnlineSectioningLog.Action.ResultType.FAILURE);
if (e.getCause() != null) {
action.addMessage(OnlineSectioningLog.Message.newBuilder()
.setLevel(OnlineSectioningLog.Message.Level.FATAL)
.setText(e.getCause().getClass().getName() + ": " + e.getCause().getMessage()));
} else {
action.addMessage(OnlineSectioningLog.Message.newBuilder()
.setLevel(OnlineSectioningLog.Message.Level.FATAL)
.setText(e.getMessage() == null ? "null" : e.getMessage()));
}
} finally {
action.setCpuTime(OnlineSectioningHelper.getCpuTime() - c0);
action.setEndTime(System.currentTimeMillis());
}
}
helper.commitTransaction();
return changed;
} catch (Exception e) {
helper.rollbackTransaction();
if (e instanceof SectioningException)
throw (SectioningException)e;
throw new SectioningException(MSG.exceptionUnknown(e.getMessage()), e);
}
}
@Override
public String name() {
return "update-overrides";
}
}
public static class Validate implements OnlineSectioningAction<Boolean> {
private static final long serialVersionUID = 1L;
private Collection<Long> iStudentIds = null;
public Validate forStudents(Long... studentIds) {
iStudentIds = new ArrayList<Long>();
for (Long studentId: studentIds)
iStudentIds.add(studentId);
return this;
}
public Validate forStudents(Collection<Long> studentIds) {
iStudentIds = studentIds;
return this;
}
public Collection<Long> getStudentIds() { return iStudentIds; }
@Override
public Boolean execute(final OnlineSectioningServer server, final OnlineSectioningHelper helper) {
if (!CustomCourseRequestsValidationHolder.hasProvider()) return false;
final List<Long> reloadIds = new ArrayList<Long>();
try {
int nrThreads = server.getConfig().getPropertyInt("CourseRequestsValidation.NrThreads", 10);
if (nrThreads <= 1 || getStudentIds().size() <= 1) {
for (Long studentId: getStudentIds()) {
if (revalidateStudent(server, helper, studentId)) reloadIds.add(studentId);
}
} else {
List<Worker> workers = new ArrayList<Worker>();
Iterator<Long> studentIds = getStudentIds().iterator();
for (int i = 0; i < nrThreads; i++)
workers.add(new Worker(i, studentIds) {
@Override
protected void process(Long studentId) {
if (revalidateStudent(server, new OnlineSectioningHelper(helper), studentId)) {
synchronized (reloadIds) {
reloadIds.add(studentId);
}
}
}
});
for (Worker worker: workers) worker.start();
for (Worker worker: workers) {
try {
worker.join();
} catch (InterruptedException e) {
}
}
}
} finally {
if (!reloadIds.isEmpty() && !(server instanceof DatabaseServer))
server.execute(server.createAction(ReloadStudent.class).forStudents(reloadIds), helper.getUser());
}
return !reloadIds.isEmpty();
}
protected boolean revalidateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, Long studentId) {
helper.beginTransaction();
try {
Student student = StudentDAO.getInstance().get(studentId, helper.getHibSession());
boolean changed = false;
if (student != null) {
OnlineSectioningLog.Action.Builder action = helper.addAction(this, server.getAcademicSession());
action.setStudent(OnlineSectioningLog.Entity.newBuilder()
.setUniqueId(studentId)
.setExternalId(student.getExternalUniqueId())
.setName(helper.getStudentNameFormat().format(student))
.setType(OnlineSectioningLog.Entity.EntityType.STUDENT));
long c0 = OnlineSectioningHelper.getCpuTime();
try {
if (CustomCourseRequestsValidationHolder.getProvider().revalidateStudent(server, helper, student, action)) {
changed = true;
action.setResult(OnlineSectioningLog.Action.ResultType.TRUE);
} else {
action.setResult(OnlineSectioningLog.Action.ResultType.FALSE);
}
} catch (SectioningException e) {
action.setResult(OnlineSectioningLog.Action.ResultType.FAILURE);
if (e.getCause() != null) {
action.addMessage(OnlineSectioningLog.Message.newBuilder()
.setLevel(OnlineSectioningLog.Message.Level.FATAL)
.setText(e.getCause().getClass().getName() + ": " + e.getCause().getMessage()));
} else {
action.addMessage(OnlineSectioningLog.Message.newBuilder()
.setLevel(OnlineSectioningLog.Message.Level.FATAL)
.setText(e.getMessage() == null ? "null" : e.getMessage()));
}
} finally {
action.setCpuTime(OnlineSectioningHelper.getCpuTime() - c0);
action.setEndTime(System.currentTimeMillis());
}
}
helper.commitTransaction();
return changed;
} catch (Exception e) {
helper.rollbackTransaction();
if (e instanceof SectioningException)
throw (SectioningException)e;
throw new SectioningException(MSG.exceptionUnknown(e.getMessage()), e);
}
}
@Override
public String name() {
return "validate-overrides";
}
}
protected static abstract class Worker extends Thread {
private Iterator<Long> iStudentsIds;
public Worker(int index, Iterator<Long> studentsIds) {
setName("Validator-" + (1 + index));
iStudentsIds = studentsIds;
}
protected abstract void process(Long studentId);
@Override
public void run() {
try {
while (true) {
Long studentId = null;
synchronized (iStudentsIds) {
if (!iStudentsIds.hasNext()) break;
studentId = iStudentsIds.next();
}
process(studentId);
}
} finally {
_RootDAO.closeCurrentThreadSessions();
}
}
}
}
| JavaSource/org/unitime/timetable/onlinesectioning/custom/CustomCourseRequestsValidationHolder.java | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.unitime.timetable.onlinesectioning.custom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.unitime.localization.impl.Localization;
import org.unitime.timetable.defaults.ApplicationProperty;
import org.unitime.timetable.gwt.resources.StudentSectioningMessages;
import org.unitime.timetable.gwt.shared.CourseRequestInterface;
import org.unitime.timetable.gwt.shared.SectioningException;
import org.unitime.timetable.model.Student;
import org.unitime.timetable.model.dao.StudentDAO;
import org.unitime.timetable.model.dao._RootDAO;
import org.unitime.timetable.onlinesectioning.OnlineSectioningAction;
import org.unitime.timetable.onlinesectioning.OnlineSectioningHelper;
import org.unitime.timetable.onlinesectioning.OnlineSectioningLog;
import org.unitime.timetable.onlinesectioning.OnlineSectioningServer;
import org.unitime.timetable.onlinesectioning.server.DatabaseServer;
import org.unitime.timetable.onlinesectioning.updates.ReloadStudent;
/**
* @author Tomas Muller
*/
public class CustomCourseRequestsValidationHolder {
private static StudentSectioningMessages MSG = Localization.create(StudentSectioningMessages.class);
private static CourseRequestsValidationProvider sProvider = null;
public synchronized static CourseRequestsValidationProvider getProvider() {
if (sProvider == null) {
try {
sProvider = ((CourseRequestsValidationProvider)Class.forName(ApplicationProperty.CustomizationCourseRequestsValidation.value()).newInstance());
} catch (Exception e) {
throw new SectioningException(MSG.exceptionCourseRequestValidationProvider(e.getMessage()), e);
}
}
return sProvider;
}
public synchronized static void release() {
if (sProvider != null) {
sProvider.dispose();
sProvider = null;
}
}
public synchronized static boolean hasProvider() {
return sProvider != null || ApplicationProperty.CustomizationCourseRequestsValidation.value() != null;
}
public static class Check implements OnlineSectioningAction<CourseRequestInterface> {
private static final long serialVersionUID = 1L;
private CourseRequestInterface iRequest;
public Check withRequest(CourseRequestInterface request) {
iRequest = request;
return this;
}
public CourseRequestInterface getRequest() { return iRequest; }
@Override
public CourseRequestInterface execute(OnlineSectioningServer server, OnlineSectioningHelper helper) {
CourseRequestInterface request = getRequest();
if (CustomCourseRequestsValidationHolder.hasProvider())
CustomCourseRequestsValidationHolder.getProvider().check(server, helper, request);
return request;
}
@Override
public String name() {
return "check-overrides";
}
}
public static class Update implements OnlineSectioningAction<Boolean> {
private static final long serialVersionUID = 1L;
private Collection<Long> iStudentIds = null;
public Update forStudents(Long... studentIds) {
iStudentIds = new ArrayList<Long>();
for (Long studentId: studentIds)
iStudentIds.add(studentId);
return this;
}
public Update forStudents(Collection<Long> studentIds) {
iStudentIds = studentIds;
return this;
}
public Collection<Long> getStudentIds() { return iStudentIds; }
@Override
public Boolean execute(final OnlineSectioningServer server, final OnlineSectioningHelper helper) {
if (!CustomCourseRequestsValidationHolder.hasProvider()) return false;
final List<Long> reloadIds = new ArrayList<Long>();
try {
int nrThreads = server.getConfig().getPropertyInt("CourseRequestsValidation.NrThreads", 10);
if (nrThreads <= 1 || getStudentIds().size() <= 1) {
for (Long studentId: getStudentIds()) {
if (updateStudent(server, helper, studentId)) reloadIds.add(studentId);
}
} else {
List<Worker> workers = new ArrayList<Worker>();
Iterator<Long> studentIds = getStudentIds().iterator();
for (int i = 0; i < nrThreads; i++)
workers.add(new Worker(i, studentIds) {
@Override
protected void process(Long studentId) {
if (updateStudent(server, new OnlineSectioningHelper(helper), studentId)) {
synchronized (reloadIds) {
reloadIds.add(studentId);
}
}
}
});
for (Worker worker: workers) worker.start();
for (Worker worker: workers) {
try {
worker.join();
} catch (InterruptedException e) {
}
}
}
} finally {
if (!reloadIds.isEmpty() && !(server instanceof DatabaseServer))
server.execute(server.createAction(ReloadStudent.class).forStudents(reloadIds), helper.getUser());
}
return !reloadIds.isEmpty();
}
protected boolean updateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, Long studentId) {
helper.beginTransaction();
try {
helper.getAction().addOther(OnlineSectioningLog.Entity.newBuilder()
.setUniqueId(studentId)
.setType(OnlineSectioningLog.Entity.EntityType.STUDENT));
Student student = StudentDAO.getInstance().get(studentId, helper.getHibSession());
boolean changed = false;
if (student != null) {
OnlineSectioningLog.Action.Builder action = helper.addAction(this, server.getAcademicSession());
action.setStudent(OnlineSectioningLog.Entity.newBuilder()
.setUniqueId(studentId)
.setExternalId(student.getExternalUniqueId())
.setName(helper.getStudentNameFormat().format(student))
.setType(OnlineSectioningLog.Entity.EntityType.STUDENT));
long c0 = OnlineSectioningHelper.getCpuTime();
try {
if (CustomCourseRequestsValidationHolder.getProvider().updateStudent(server, helper, student, action)) {
changed = true;
action.setResult(OnlineSectioningLog.Action.ResultType.TRUE);
} else {
action.setResult(OnlineSectioningLog.Action.ResultType.FALSE);
}
} catch (SectioningException e) {
action.setResult(OnlineSectioningLog.Action.ResultType.FAILURE);
if (e.getCause() != null) {
action.addMessage(OnlineSectioningLog.Message.newBuilder()
.setLevel(OnlineSectioningLog.Message.Level.FATAL)
.setText(e.getCause().getClass().getName() + ": " + e.getCause().getMessage()));
} else {
action.addMessage(OnlineSectioningLog.Message.newBuilder()
.setLevel(OnlineSectioningLog.Message.Level.FATAL)
.setText(e.getMessage() == null ? "null" : e.getMessage()));
}
} finally {
action.setCpuTime(OnlineSectioningHelper.getCpuTime() - c0);
action.setEndTime(System.currentTimeMillis());
}
}
helper.commitTransaction();
return changed;
} catch (Exception e) {
helper.rollbackTransaction();
if (e instanceof SectioningException)
throw (SectioningException)e;
throw new SectioningException(MSG.exceptionUnknown(e.getMessage()), e);
}
}
@Override
public String name() {
return "update-overrides";
}
}
public static class Validate implements OnlineSectioningAction<Boolean> {
private static final long serialVersionUID = 1L;
private Collection<Long> iStudentIds = null;
public Validate forStudents(Long... studentIds) {
iStudentIds = new ArrayList<Long>();
for (Long studentId: studentIds)
iStudentIds.add(studentId);
return this;
}
public Validate forStudents(Collection<Long> studentIds) {
iStudentIds = studentIds;
return this;
}
public Collection<Long> getStudentIds() { return iStudentIds; }
@Override
public Boolean execute(final OnlineSectioningServer server, final OnlineSectioningHelper helper) {
if (!CustomCourseRequestsValidationHolder.hasProvider()) return false;
final List<Long> reloadIds = new ArrayList<Long>();
try {
int nrThreads = server.getConfig().getPropertyInt("CourseRequestsValidation.NrThreads", 10);
if (nrThreads <= 1 || getStudentIds().size() <= 1) {
for (Long studentId: getStudentIds()) {
if (revalidateStudent(server, helper, studentId)) reloadIds.add(studentId);
}
} else {
List<Worker> workers = new ArrayList<Worker>();
Iterator<Long> studentIds = getStudentIds().iterator();
for (int i = 0; i < nrThreads; i++)
workers.add(new Worker(i, studentIds) {
@Override
protected void process(Long studentId) {
if (revalidateStudent(server, new OnlineSectioningHelper(helper), studentId)) {
synchronized (reloadIds) {
reloadIds.add(studentId);
}
}
}
});
for (Worker worker: workers) worker.start();
for (Worker worker: workers) {
try {
worker.join();
} catch (InterruptedException e) {
}
}
}
} finally {
if (!reloadIds.isEmpty() && !(server instanceof DatabaseServer))
server.execute(server.createAction(ReloadStudent.class).forStudents(reloadIds), helper.getUser());
}
return !reloadIds.isEmpty();
}
protected boolean revalidateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, Long studentId) {
helper.beginTransaction();
try {
helper.getAction().addOther(OnlineSectioningLog.Entity.newBuilder()
.setUniqueId(studentId)
.setType(OnlineSectioningLog.Entity.EntityType.STUDENT));
Student student = StudentDAO.getInstance().get(studentId, helper.getHibSession());
boolean changed = false;
if (student != null) {
OnlineSectioningLog.Action.Builder action = helper.addAction(this, server.getAcademicSession());
action.setStudent(OnlineSectioningLog.Entity.newBuilder()
.setUniqueId(studentId)
.setExternalId(student.getExternalUniqueId())
.setName(helper.getStudentNameFormat().format(student))
.setType(OnlineSectioningLog.Entity.EntityType.STUDENT));
long c0 = OnlineSectioningHelper.getCpuTime();
try {
if (CustomCourseRequestsValidationHolder.getProvider().revalidateStudent(server, helper, student, action)) {
changed = true;
action.setResult(OnlineSectioningLog.Action.ResultType.TRUE);
} else {
action.setResult(OnlineSectioningLog.Action.ResultType.FALSE);
}
} catch (SectioningException e) {
action.setResult(OnlineSectioningLog.Action.ResultType.FAILURE);
if (e.getCause() != null) {
action.addMessage(OnlineSectioningLog.Message.newBuilder()
.setLevel(OnlineSectioningLog.Message.Level.FATAL)
.setText(e.getCause().getClass().getName() + ": " + e.getCause().getMessage()));
} else {
action.addMessage(OnlineSectioningLog.Message.newBuilder()
.setLevel(OnlineSectioningLog.Message.Level.FATAL)
.setText(e.getMessage() == null ? "null" : e.getMessage()));
}
} finally {
action.setCpuTime(OnlineSectioningHelper.getCpuTime() - c0);
action.setEndTime(System.currentTimeMillis());
}
}
helper.commitTransaction();
return changed;
} catch (Exception e) {
helper.rollbackTransaction();
if (e instanceof SectioningException)
throw (SectioningException)e;
throw new SectioningException(MSG.exceptionUnknown(e.getMessage()), e);
}
}
@Override
public String name() {
return "validate-overrides";
}
}
protected static abstract class Worker extends Thread {
private Iterator<Long> iStudentsIds;
public Worker(int index, Iterator<Long> studentsIds) {
setName("Validator-" + (1 + index));
iStudentsIds = studentsIds;
}
protected abstract void process(Long studentId);
@Override
public void run() {
try {
while (true) {
Long studentId = null;
synchronized (iStudentsIds) {
if (!iStudentsIds.hasNext()) break;
studentId = iStudentsIds.next();
}
process(studentId);
}
} finally {
_RootDAO.closeCurrentThreadSessions();
}
}
}
}
| Course Requests: Custom Status Update and Re-Validation
- added ability to check/re-validate multiple students at a time
(fixed a possible concurrent modification exception when accessing the parent's action log)
| JavaSource/org/unitime/timetable/onlinesectioning/custom/CustomCourseRequestsValidationHolder.java | Course Requests: Custom Status Update and Re-Validation | <ide><path>avaSource/org/unitime/timetable/onlinesectioning/custom/CustomCourseRequestsValidationHolder.java
<ide> protected boolean updateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, Long studentId) {
<ide> helper.beginTransaction();
<ide> try {
<del> helper.getAction().addOther(OnlineSectioningLog.Entity.newBuilder()
<del> .setUniqueId(studentId)
<del> .setType(OnlineSectioningLog.Entity.EntityType.STUDENT));
<del>
<ide> Student student = StudentDAO.getInstance().get(studentId, helper.getHibSession());
<ide> boolean changed = false;
<ide>
<ide> protected boolean revalidateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, Long studentId) {
<ide> helper.beginTransaction();
<ide> try {
<del> helper.getAction().addOther(OnlineSectioningLog.Entity.newBuilder()
<del> .setUniqueId(studentId)
<del> .setType(OnlineSectioningLog.Entity.EntityType.STUDENT));
<del>
<ide> Student student = StudentDAO.getInstance().get(studentId, helper.getHibSession());
<ide>
<ide> boolean changed = false; |
|
Java | apache-2.0 | 17daed5f8eeadb6cebee686ca93c593fe609f307 | 0 | brotherlogic/pictureframe,brotherlogic/pictureframe,brotherlogic/pictureframe | package com.github.brotherlogic.pictureframe;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import io.grpc.BindableService;
public class Frame extends FrameBase {
private DropboxConnector connector;
private Config config;
private File configFile;
public Frame(String token, File configFile) {
connector = new DropboxConnector(token);
try {
if (configFile != null) {
this.configFile = configFile;
FileInputStream fis = new FileInputStream(configFile);
config = new Config(proto.ConfigOuterClass.Config.parseFrom(fis).toByteArray());
} else {
config = new Config();
}
} catch (IOException e) {
config = new Config();
}
}
public void runWebServer() throws IOException {
new HttpServer(config, this);
}
public static void main(String[] args) throws Exception {
Option optionServer = OptionBuilder.withLongOpt("server").hasArg().withDescription("Hostname of server")
.create("s");
Option optionToken = OptionBuilder.withLongOpt("token").hasArg().withDescription("Token to use for dropbox")
.create("t");
Option optionConfig = OptionBuilder.withLongOpt("config").hasArg().withDescription("Config file to user")
.create("c");
Options options = new Options();
options.addOption(optionServer);
options.addOption(optionToken);
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(options, args);
String server = "10.0.1.17";
System.out.println("ARGS = " + Arrays.toString(args));
if (line.hasOption("server"))
server = line.getOptionValue("s");
String token = "unknown";
if (line.hasOption("token"))
token = line.getOptionValue("t");
String configLocation = ".config";
if (line.hasOption("config"))
configLocation = line.getOptionValue("c");
Frame f = new Frame(token, new File(configLocation));
f.runWebServer();
f.Serve(server);
}
@Override
public String getServerName() {
return "PictureFrame";
}
public void saveConfig() {
try {
System.out.println("SAVING TO " + configFile);
FileOutputStream fos = new FileOutputStream(configFile);
config.getConfig().writeTo(fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public List<BindableService> getServices() {
return new LinkedList<BindableService>();
}
public void syncAndDisplay() {
if (connector != null) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
d.getContentPane().removeAll();
File out = new File("pics/");
out.mkdirs();
try {
connector.syncFolder("/", out);
Photo p = getTimedLatestPhoto(out.getAbsolutePath());
if (p != null) {
System.out.println("Got picture: " + p.getName());
final ImagePanel imgPanel = new ImagePanel(p.getImage());
d.add(imgPanel);
System.out.println("Added picture");
d.revalidate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
@Override
public Config getConfig() {
return config;
}
public void backgroundSync() {
while (true) {
syncAndDisplay();
// Wait before updating the picture
try {
Thread.sleep(2 * 60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
FrameDisplay d;
@Override
public void localServe() {
d = new FrameDisplay();
d.setSize(800, 480);
d.setLocationRelativeTo(null);
d.setVisible(true);
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
backgroundSync();
}
}
| src/main/java/com/github/brotherlogic/pictureframe/Frame.java | package com.github.brotherlogic.pictureframe;
import io.grpc.BindableService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
public class Frame extends FrameBase {
private DropboxConnector connector;
private Config config;
private File configFile;
public Frame(String token, File configFile) {
connector = new DropboxConnector(token);
try {
if (configFile != null) {
this.configFile = configFile;
FileInputStream fis = new FileInputStream(configFile);
config = new Config(proto.ConfigOuterClass.Config
.parseFrom(fis).toByteArray());
} else {
config = new Config();
}
} catch (IOException e) {
config = new Config();
}
}
public void runWebServer() throws IOException {
new HttpServer(config, this);
}
public static void main(String[] args) throws Exception {
Option optionServer = OptionBuilder.withLongOpt("server").hasArg()
.withDescription("Hostname of server").create("s");
Option optionToken = OptionBuilder.withLongOpt("token").hasArg()
.withDescription("Token to use for dropbox").create("t");
Option optionConfig = OptionBuilder.withLongOpt("config").hasArg()
.withDescription("Config file to user").create("c");
Options options = new Options();
options.addOption(optionServer);
options.addOption(optionToken);
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(options, args);
String server = "10.0.1.17";
System.out.println("ARGS = " + Arrays.toString(args));
if (line.hasOption("server"))
server = line.getOptionValue("s");
String token = "unknown";
if (line.hasOption("token"))
token = line.getOptionValue("t");
String configLocation = ".config";
if (line.hasOption("config"))
configLocation = line.getOptionValue("c");
Frame f = new Frame(token, new File(configLocation));
f.runWebServer();
f.Serve(server);
}
@Override
public String getServerName() {
return "PictureFrame";
}
public void saveConfig() {
try {
System.out.println("SAVING TO " + configFile);
FileOutputStream fos = new FileOutputStream(configFile);
config.getConfig().writeTo(fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public List<BindableService> getServices() {
return new LinkedList<BindableService>();
}
public void syncAndDisplay() {
if (connector != null) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
d.getContentPane().removeAll();
File out = new File("pics/");
out.mkdirs();
try {
connector.syncFolder("/", out);
Photo p = getTimedLatestPhoto(out.getAbsolutePath());
System.out.println("Got picture: " + p.getName());
if (p != null) {
final ImagePanel imgPanel = new ImagePanel(p
.getImage());
d.add(imgPanel);
System.out.println("Added picture");
d.revalidate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
@Override
public Config getConfig() {
return config;
}
public void backgroundSync() {
while (true) {
syncAndDisplay();
// Wait before updating the picture
try {
Thread.sleep(2 * 60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
FrameDisplay d;
@Override
public void localServe() {
d = new FrameDisplay();
d.setSize(800, 480);
d.setLocationRelativeTo(null);
d.setVisible(true);
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
backgroundSync();
}
}
| Bug fix
| src/main/java/com/github/brotherlogic/pictureframe/Frame.java | Bug fix | <ide><path>rc/main/java/com/github/brotherlogic/pictureframe/Frame.java
<ide> package com.github.brotherlogic.pictureframe;
<del>
<del>import io.grpc.BindableService;
<ide>
<ide> import java.io.File;
<ide> import java.io.FileInputStream;
<ide> import org.apache.commons.cli.OptionBuilder;
<ide> import org.apache.commons.cli.Options;
<ide>
<add>import io.grpc.BindableService;
<add>
<ide> public class Frame extends FrameBase {
<ide>
<ide> private DropboxConnector connector;
<ide> if (configFile != null) {
<ide> this.configFile = configFile;
<ide> FileInputStream fis = new FileInputStream(configFile);
<del> config = new Config(proto.ConfigOuterClass.Config
<del> .parseFrom(fis).toByteArray());
<add> config = new Config(proto.ConfigOuterClass.Config.parseFrom(fis).toByteArray());
<ide> } else {
<ide> config = new Config();
<ide> }
<ide> }
<ide>
<ide> public static void main(String[] args) throws Exception {
<del> Option optionServer = OptionBuilder.withLongOpt("server").hasArg()
<del> .withDescription("Hostname of server").create("s");
<del> Option optionToken = OptionBuilder.withLongOpt("token").hasArg()
<del> .withDescription("Token to use for dropbox").create("t");
<del> Option optionConfig = OptionBuilder.withLongOpt("config").hasArg()
<del> .withDescription("Config file to user").create("c");
<add> Option optionServer = OptionBuilder.withLongOpt("server").hasArg().withDescription("Hostname of server")
<add> .create("s");
<add> Option optionToken = OptionBuilder.withLongOpt("token").hasArg().withDescription("Token to use for dropbox")
<add> .create("t");
<add> Option optionConfig = OptionBuilder.withLongOpt("config").hasArg().withDescription("Config file to user")
<add> .create("c");
<ide> Options options = new Options();
<ide> options.addOption(optionServer);
<ide> options.addOption(optionToken);
<ide> connector.syncFolder("/", out);
<ide>
<ide> Photo p = getTimedLatestPhoto(out.getAbsolutePath());
<del> System.out.println("Got picture: " + p.getName());
<ide> if (p != null) {
<del> final ImagePanel imgPanel = new ImagePanel(p
<del> .getImage());
<add> System.out.println("Got picture: " + p.getName());
<add>
<add> final ImagePanel imgPanel = new ImagePanel(p.getImage());
<ide> d.add(imgPanel);
<ide> System.out.println("Added picture");
<ide> d.revalidate(); |
|
Java | agpl-3.0 | fcf2592b2e0b89ab8363b73349f0e9f183d2ed55 | 0 | RestComm/jss7,RestComm/jss7 | package org.mobicents.protocols.ss7.stream.tcp;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import org.mobicents.protocols.ss7.mtp.Mtp3;
import org.mobicents.protocols.ss7.mtp.MtpUser;
import org.mobicents.protocols.ss7.stream.HDLCHandler;
import org.mobicents.protocols.ss7.stream.StreamForwarder;
import org.mobicents.protocols.ss7.stream.tlv.LinkStatus;
import org.mobicents.protocols.ss7.stream.tlv.TLVInputStream;
import org.mobicents.protocols.ss7.stream.tlv.TLVOutputStream;
import org.mobicents.protocols.ss7.stream.tlv.Tag;
public class M3UserAgent implements StreamForwarder, MtpUser, Runnable, M3UserAgentMBean {
private static final Logger logger = Logger.getLogger(M3UserAgent.class);
private ExecutorService executor = Executors.newSingleThreadExecutor();
private int port = 1345;
private InetAddress address;
private ServerSocketChannel serverSocketChannel;
private SocketChannel channel;
private Selector readSelector;
private Selector writeSelector;
private Selector connectSelector;
// we accept only one connection
private boolean connected = false;
private ByteBuffer readBuff = ByteBuffer.allocate(8192);
private ByteBuffer txBuff = ByteBuffer.allocate(8192);
private Mtp3 mtp;
// private MTP mtp;
private boolean linkUp = false;
private Future runFuture;
//
private HDLCHandler hdlcHandler = new HDLCHandler();
private boolean runnable;
// /////////////////
// Some statics //
// ////////////////
private static final byte[] _LINK_STATE_UP;
private static final byte[] _LINK_STATE_DOWN;
static {
TLVOutputStream tlv = new TLVOutputStream();
try {
tlv.writeLinkStatus(LinkStatus.LinkUp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
_LINK_STATE_UP = tlv.toByteArray();
tlv.reset();
try {
tlv.writeLinkStatus(LinkStatus.LinkDown);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
_LINK_STATE_DOWN = tlv.toByteArray();
}
public M3UserAgent() {
super();
// wont send empty buffer
this.txBuff.limit(0);
}
///////////////////////
// Setters & Getters //
///////////////////////
public String getAddress() {
return this.address.toString();
}
public int getPort() {
return this.port;
}
public void setAddress(String address) throws UnknownHostException {
this.address = InetAddress.getAllByName(address)[0];
}
public void setPort(int port) {
if (port > 0) {
this.port = port;
} else {
// do nothing, use def
}
}
public void setMtp3(Mtp3 mtp) {
this.mtp = mtp;
if (mtp != null) {
this.mtp.setUserPart(this);
}
}
/**
* @return the connected
*/
public boolean isConnected() {
return connected;
}
public void start() throws IOException {
this.connectSelector = SelectorProvider.provider().openSelector();
this.serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
// Bind the server socket to the specified address and port
InetSocketAddress isa = new InetSocketAddress(this.address, this.port);
serverSocketChannel.socket().bind(isa);
// Register the server socket channel, indicating an interest in
// accepting new connections
serverSocketChannel.register(this.connectSelector, SelectionKey.OP_ACCEPT);
if(logger.isInfoEnabled())
{
logger.info("Initiaited server on: " + this.address + ":" + this.port);
}
runnable = true;
this.runFuture = this.executor.submit(this);
}
public void stop() {
if (this.runFuture != null) {
this.runFuture.cancel(false);
this.runFuture = null;
runnable = false;
}
if (this.connectSelector != null && this.connectSelector.isOpen()) {
try {
this.connectSelector.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (this.serverSocketChannel != null) {
try {
this.serverSocketChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
disconnect();
}
public void run()
{
while(runnable)
{
try
{
Iterator selectedKeys = null;
// Wait for an event one of the registered channels
if (!connected) {
// block till we have someone subscribing for data.
this.connectSelector.select();
selectedKeys = this.connectSelector.selectedKeys().iterator();
// operate on keys set
performKeyOperations(selectedKeys);
//} else if (linkUp) {
} else {
// else we try I/O ops.
if (this.readSelector.selectNow() > 0) {
selectedKeys = this.readSelector.selectedKeys().iterator();
// operate on keys set
performKeyOperations(selectedKeys);
}
if (this.writeSelector.selectNow() > 0) {
selectedKeys = this.writeSelector.selectedKeys().iterator();
// operate on keys set
performKeyOperations(selectedKeys);
}
if (hdlcHandler.isTxBufferEmpty()) {
// synchronized(this.writeSelector)
// {
// this.writeSelector.wait(5);
// }
}
}
}catch(ClosedSelectorException cse)
{
cse.printStackTrace();
//check for server selector?
disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void performKeyOperations(Iterator<SelectionKey> selectedKeys) throws IOException {
while (selectedKeys.hasNext()) {
SelectionKey key = selectedKeys.next();
//THIS MUST BE PRESENT!
selectedKeys.remove();
if (!key.isValid()) {
// handle disconnect here?
if(logger.isInfoEnabled()){
logger.info("Key became invalid: "+key);
}
continue;
}
// Check what event is available and deal with it
if (key.isAcceptable()) {
this.accept(key);
} else if (key.isReadable()) {
this.read(key);
} else if (key.isWritable()) {
this.write(key);
}
}
}
private void accept(SelectionKey key) throws IOException {
if(connected)
{
if(logger.isInfoEnabled())
{
logger.info("Second client not supported yet.");
}
return;
}
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
this.channel = serverSocketChannel.accept();
this.writeSelector = SelectorProvider.provider().openSelector();
this.readSelector = SelectorProvider.provider().openSelector();
Socket socket = channel.socket();
this.channel.configureBlocking(false);
this.channel.register(this.readSelector, SelectionKey.OP_READ);
this.channel.register(this.writeSelector, SelectionKey.OP_WRITE);
this.connected = true;
if (logger.isInfoEnabled()) {
logger.info("Estabilished connection with: " + socket.getInetAddress() + ":" + socket.getPort());
}
//if (connected) {
// serverSocketChannel.close();
// return;
//}
//lets strean state
if(linkUp)
{
this.streamData(_LINK_STATE_UP);
}else
{
//this.streamData(_LINK_STATE_DOWN);
}
}
private void write(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
// Write until there's not more data ?
//while (!txBuffer.isEmpty()) {
if(txBuff.remaining()>0)
{
int sentDataCount = socketChannel.write(txBuff);
if(logger.isInfoEnabled())
{
logger.info("Sent data: "+sentDataCount);
}
if(txBuff.remaining()>0)
{
//buffer filled.
return;
}else
{
}
}
//while (!this.hdlcHandler.isTxBufferEmpty()) {
if (!this.hdlcHandler.isTxBufferEmpty()) {
//ByteBuffer buf = (ByteBuffer) txBuffer.get(0);
txBuff.clear();
this.hdlcHandler.processTx(txBuff);
txBuff.flip();
if(logger.isInfoEnabled())
{
logger.info("Sending data: "+txBuff);
}
int sentCount = socketChannel.write(txBuff);
if(logger.isInfoEnabled())
{
logger.info("Sent data count: "+sentCount);
}
//if (buf.remaining() > 0) {
if(txBuff.remaining()>0)
{
// ... or the socket's buffer fills up
return;
}
//buf.clear();
//txBuff.clear();
//txBuffer.remove(0);
}
}
private void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
// FIXME: we must ensure that we have whole frame here?
// Clear out our read buffer so it's ready for new data
this.readBuff.clear();
// Attempt to read off the channel
int numRead = -1;
try {
numRead = socketChannel.read(this.readBuff);
} catch (IOException e) {
// The remote forcibly closed the connection, cancel
// the selection key and close the channel
e.printStackTrace();
handleClose(key);
return;
}
if (numRead == -1) {
// Remote entity shut the socket down cleanly. Do the
// same from our end and cancel the channel.
handleClose(key);
return;
}
//pass it on.
ByteBuffer[] readResult = null;
//This will read everything, and if there is incomplete frame, it will retain its partial content
//so on next read it can continue to decode!
this.readBuff.flip();
if(logger.isInfoEnabled())
{
logger.info("Read data: "+readBuff);
}
while((readResult = this.hdlcHandler.processRx(this.readBuff))!=null)
{
for(ByteBuffer b:readResult)
{
if(logger.isInfoEnabled())
{
logger.info("Processed data: "+b);
}
//byte sls = b.get();
//byte linksetId = b.get();
//this.layer3.send(sls,linksetId,si, ssf, b.array());
TLVInputStream tlvInputStream = new TLVInputStream(new ByteArrayInputStream(b.array()));
int tag = tlvInputStream.readTag();
if(tag == Tag._TAG_LINK_DATA)
{
byte[] data = tlvInputStream.readLinkData();
if(logger.isInfoEnabled())
{
logger.info("Send MSU to MTP3: "+Arrays.toString(data));
}
this.mtp.send( data);
}else if (tag == Tag._TAG_LINK_STATUS)
{
LinkStatus ls = tlvInputStream.readLinkStatus();
switch(ls)
{
case Query:
if(this.linkUp)
{
this.streamData(_LINK_STATE_UP);
}else
{
this.streamData(_LINK_STATE_DOWN);
}
}
}else
{
logger.warn("Received weird message!");
}
}
}
this.readBuff.clear();
//this.layer3.send(si, ssf, this.readBuff.array());
}
private void handleClose(SelectionKey key) {
if (logger.isInfoEnabled()) {
logger.info("Handling key close operations: " + key);
}
linkDown();
try {
disconnect();
} finally {
// linkDown();
//connected = false;
// synchronized (this.hdlcHandler) {
synchronized (this.writeSelector) {
// this is to ensure buffer does not have any bad data.
// this.txBuffer.clear();
this.hdlcHandler.clearTxBuffer();
}
}
return;
}
private void disconnect() {
if (this.channel != null) {
try {
this.channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.channel = null;
if (this.readSelector != null && this.readSelector.isOpen()) {
try {
this.readSelector.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (this.writeSelector != null && this.writeSelector.isOpen()) {
try {
this.writeSelector.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.connected = false;
}
/**
* Method used internaly - this one sends actuall data to remote end.
* @param data
*/
public void streamData(byte[] data) {
//if(this.channel!=null)
// connected = this.channel.isConnected();
if (!connected) {
if (logger.isInfoEnabled()) {
logger.info("There is no client interested in data stream, ignoring. Message should be retransmited.");
}
return;
}
// And queue the data we want written
//synchronized (this.txBuffer) {
//synchronized (this.hdlcHandler) {
synchronized (this.writeSelector) {
//this.txBuffer.add(ByteBuffer.wrap(data));
ByteBuffer bb = ByteBuffer.allocate(data.length);
bb.put(data);
bb.flip();
this.hdlcHandler.addToTxBuffer(bb);
// Finally, wake up our selecting thread so it can make the required
// changes
this.writeSelector.wakeup();
}
}
////////////
// LAYER4 //
////////////
public void linkDown() {
if (logger.isInfoEnabled()) {
logger.info("Received L4 Down event from layer3.");
}
this.linkUp = false;
//FIXME: proper actions here.
//this.txBuff.clear();
//this.txBuff.limit(0);
//this.readBuff.clear();
this.streamData(_LINK_STATE_DOWN);
}
public void linkUp() {
if (logger.isInfoEnabled()) {
logger.info("Received L4 Up event from layer3.");
}
this.linkUp = true;
this.streamData(_LINK_STATE_UP);
}
public void receive(String msg)
{
this.receive(msg.getBytes());
}
public void receive( byte[] msgBuff) {
// layer3 has something important, lets write.
//if(linkUp)
//{
logger.info("Preparing MSU to stream: "+Arrays.toString(msgBuff));
TLVOutputStream tlv = new TLVOutputStream();
try {
tlv.writeData(msgBuff);
byte[] data = tlv.toByteArray();
this.streamData(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//}
}
}
| mtp/src/main/java/org/mobicents/protocols/ss7/stream/tcp/M3UserAgent.java | package org.mobicents.protocols.ss7.stream.tcp;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import org.mobicents.protocols.ss7.mtp.Mtp3;
import org.mobicents.protocols.ss7.mtp.MtpUser;
import org.mobicents.protocols.ss7.stream.HDLCHandler;
import org.mobicents.protocols.ss7.stream.StreamForwarder;
import org.mobicents.protocols.ss7.stream.tlv.LinkStatus;
import org.mobicents.protocols.ss7.stream.tlv.TLVInputStream;
import org.mobicents.protocols.ss7.stream.tlv.TLVOutputStream;
import org.mobicents.protocols.ss7.stream.tlv.Tag;
public class M3UserAgent implements StreamForwarder, MtpUser, Runnable, M3UserAgentMBean {
private static final Logger logger = Logger.getLogger(M3UserAgent.class);
private ExecutorService executor = Executors.newSingleThreadExecutor();
private int port = 1345;
private InetAddress address;
private ServerSocketChannel serverSocketChannel;
private SocketChannel channel;
private Selector readSelector;
private Selector writeSelector;
private Selector connectSelector;
// we accept only one connection
private boolean connected = false;
private ByteBuffer readBuff = ByteBuffer.allocate(8192);
private ByteBuffer txBuff = ByteBuffer.allocate(8192);
private Mtp3 mtp;
// private MTP mtp;
private boolean linkUp = false;
private Future runFuture;
//
private HDLCHandler hdlcHandler = new HDLCHandler();
private boolean runnable;
// /////////////////
// Some statics //
// ////////////////
private static final byte[] _LINK_STATE_UP;
private static final byte[] _LINK_STATE_DOWN;
static {
TLVOutputStream tlv = new TLVOutputStream();
try {
tlv.writeLinkStatus(LinkStatus.LinkUp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
_LINK_STATE_UP = tlv.toByteArray();
tlv.reset();
try {
tlv.writeLinkStatus(LinkStatus.LinkDown);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
_LINK_STATE_DOWN = tlv.toByteArray();
}
public M3UserAgent() {
super();
// wont send empty buffer
this.txBuff.limit(0);
}
///////////////////////
// Setters & Getters //
///////////////////////
public String getAddress() {
return this.address.toString();
}
public int getPort() {
return this.port;
}
public void setAddress(String address) throws UnknownHostException {
this.address = InetAddress.getAllByName(address)[0];
}
public void setPort(int port) {
if (port > 0) {
this.port = port;
} else {
// do nothing, use def
}
}
public void setMtp3(Mtp3 mtp) {
this.mtp = mtp;
if (mtp != null) {
this.mtp.setUserPart(this);
}
}
/**
* @return the connected
*/
public boolean isConnected() {
return connected;
}
public void start() throws IOException {
this.connectSelector = SelectorProvider.provider().openSelector();
this.serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
// Bind the server socket to the specified address and port
InetSocketAddress isa = new InetSocketAddress(this.address, this.port);
serverSocketChannel.socket().bind(isa);
// Register the server socket channel, indicating an interest in
// accepting new connections
serverSocketChannel.register(this.connectSelector, SelectionKey.OP_ACCEPT);
if(logger.isInfoEnabled())
{
logger.info("Initiaited server on: " + this.address + ":" + this.port);
}
runnable = true;
this.runFuture = this.executor.submit(this);
}
public void stop() {
if (this.runFuture != null) {
this.runFuture.cancel(false);
this.runFuture = null;
runnable = false;
}
if (this.connectSelector != null && this.connectSelector.isOpen()) {
try {
this.connectSelector.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (this.serverSocketChannel != null) {
try {
this.serverSocketChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
disconnect();
}
public void run()
{
while(runnable)
{
try
{
Iterator selectedKeys = null;
// Wait for an event one of the registered channels
if (!connected) {
// block till we have someone subscribing for data.
this.connectSelector.select();
selectedKeys = this.connectSelector.selectedKeys().iterator();
// operate on keys set
performKeyOperations(selectedKeys);
//} else if (linkUp) {
} else {
// else we try I/O ops.
if (this.readSelector.selectNow() > 0) {
selectedKeys = this.readSelector.selectedKeys().iterator();
// operate on keys set
performKeyOperations(selectedKeys);
}
if (this.writeSelector.selectNow() > 0) {
selectedKeys = this.writeSelector.selectedKeys().iterator();
// operate on keys set
performKeyOperations(selectedKeys);
}
if (hdlcHandler.isTxBufferEmpty()) {
// synchronized(this.writeSelector)
// {
// this.writeSelector.wait(5);
// }
}
}
}catch(ClosedSelectorException cse)
{
cse.printStackTrace();
//check for server selector?
disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void performKeyOperations(Iterator<SelectionKey> selectedKeys) throws IOException {
while (selectedKeys.hasNext()) {
SelectionKey key = selectedKeys.next();
//THIS MUST BE PRESENT!
selectedKeys.remove();
if (!key.isValid()) {
// handle disconnect here?
if(logger.isInfoEnabled()){
logger.info("Key became invalid: "+key);
}
continue;
}
// Check what event is available and deal with it
if (key.isAcceptable()) {
this.accept(key);
} else if (key.isReadable()) {
this.read(key);
} else if (key.isWritable()) {
this.write(key);
}
}
}
private void accept(SelectionKey key) throws IOException {
if(connected)
{
if(logger.isInfoEnabled())
{
logger.info("Second client not supported yet.");
}
return;
}
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
this.channel = serverSocketChannel.accept();
this.writeSelector = SelectorProvider.provider().openSelector();
this.readSelector = SelectorProvider.provider().openSelector();
Socket socket = channel.socket();
this.channel.configureBlocking(false);
this.channel.register(this.readSelector, SelectionKey.OP_READ);
this.channel.register(this.writeSelector, SelectionKey.OP_WRITE);
this.connected = true;
if (logger.isInfoEnabled()) {
logger.info("Estabilished connection with: " + socket.getInetAddress() + ":" + socket.getPort());
}
//if (connected) {
// serverSocketChannel.close();
// return;
//}
//lets strean state
if(linkUp)
{
this.streamData(_LINK_STATE_UP);
}else
{
//this.streamData(_LINK_STATE_DOWN);
}
}
private void write(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
// Write until there's not more data ?
//while (!txBuffer.isEmpty()) {
if(txBuff.remaining()>0)
{
int sentDataCount = socketChannel.write(txBuff);
if(logger.isInfoEnabled())
{
logger.info("Sent data: "+sentDataCount);
}
if(txBuff.remaining()>0)
{
//buffer filled.
return;
}else
{
}
}
//while (!this.hdlcHandler.isTxBufferEmpty()) {
if (!this.hdlcHandler.isTxBufferEmpty()) {
//ByteBuffer buf = (ByteBuffer) txBuffer.get(0);
txBuff.clear();
this.hdlcHandler.processTx(txBuff);
txBuff.flip();
if(logger.isInfoEnabled())
{
logger.info("Sending data: "+txBuff);
}
int sentCount = socketChannel.write(txBuff);
if(logger.isInfoEnabled())
{
logger.info("Sent data count: "+sentCount);
}
//if (buf.remaining() > 0) {
if(txBuff.remaining()>0)
{
// ... or the socket's buffer fills up
return;
}
//buf.clear();
//txBuff.clear();
//txBuffer.remove(0);
}
}
private void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
// FIXME: we must ensure that we have whole frame here?
// Clear out our read buffer so it's ready for new data
this.readBuff.clear();
// Attempt to read off the channel
int numRead = -1;
try {
numRead = socketChannel.read(this.readBuff);
} catch (IOException e) {
// The remote forcibly closed the connection, cancel
// the selection key and close the channel
e.printStackTrace();
handleClose(key);
return;
}
if (numRead == -1) {
// Remote entity shut the socket down cleanly. Do the
// same from our end and cancel the channel.
handleClose(key);
return;
}
//pass it on.
ByteBuffer[] readResult = null;
//This will read everything, and if there is incomplete frame, it will retain its partial content
//so on next read it can continue to decode!
this.readBuff.flip();
if(logger.isInfoEnabled())
{
logger.info("Read data: "+readBuff);
}
while((readResult = this.hdlcHandler.processRx(this.readBuff))!=null)
{
for(ByteBuffer b:readResult)
{
if(logger.isInfoEnabled())
{
logger.info("Processed data: "+b);
}
//byte sls = b.get();
//byte linksetId = b.get();
//this.layer3.send(sls,linksetId,si, ssf, b.array());
TLVInputStream tlvInputStream = new TLVInputStream(new ByteArrayInputStream(b.array()));
int tag = tlvInputStream.readTag();
if(tag == Tag._TAG_LINK_DATA)
{
byte[] data = tlvInputStream.readLinkData();
if(logger.isInfoEnabled())
{
logger.info("Send MSU to MTP3: "+Arrays.toString(data));
}
this.mtp.send( data);
}else if (tag == Tag._TAG_LINK_STATUS)
{
LinkStatus ls = tlvInputStream.readLinkStatus();
switch(ls)
{
case Query:
if(this.linkUp)
{
this.streamData(_LINK_STATE_UP);
}else
{
this.streamData(_LINK_STATE_DOWN);
}
}
}else
{
logger.warn("Received weird message!");
}
}
}
this.readBuff.clear();
//this.layer3.send(si, ssf, this.readBuff.array());
}
private void handleClose(SelectionKey key) {
if (logger.isInfoEnabled()) {
logger.info("Handling key close operations: " + key);
}
linkDown();
try {
disconnect();
} finally {
// linkDown();
//connected = false;
// synchronized (this.hdlcHandler) {
synchronized (this.writeSelector) {
// this is to ensure buffer does not have any bad data.
// this.txBuffer.clear();
this.hdlcHandler.clearTxBuffer();
}
}
return;
}
private void disconnect() {
if (this.channel != null) {
try {
this.channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.channel = null;
if (this.readSelector != null && this.readSelector.isOpen()) {
try {
this.readSelector.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (this.writeSelector != null && this.writeSelector.isOpen()) {
try {
this.writeSelector.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.connected = false;
}
/**
* Method used internaly - this one sends actuall data to remote end.
* @param data
*/
public void streamData(byte[] data) {
//if(this.channel!=null)
// connected = this.channel.isConnected();
if (!connected) {
if (logger.isInfoEnabled()) {
logger.info("There is no client interested in data stream, ignoring. Message should be retransmited.");
}
return;
}
// And queue the data we want written
//synchronized (this.txBuffer) {
//synchronized (this.hdlcHandler) {
synchronized (this.writeSelector) {
//this.txBuffer.add(ByteBuffer.wrap(data));
ByteBuffer bb = ByteBuffer.allocate(data.length);
bb.put(data);
bb.flip();
this.hdlcHandler.addToTxBuffer(bb);
// Finally, wake up our selecting thread so it can make the required
// changes
this.writeSelector.wakeup();
}
}
////////////
// LAYER4 //
////////////
public void linkDown() {
if (logger.isInfoEnabled()) {
logger.info("Received L4 Down event from layer3.");
}
this.linkUp = false;
//FIXME: proper actions here.
//this.txBuff.clear();
//this.txBuff.limit(0);
//this.readBuff.clear();
this.streamData(_LINK_STATE_DOWN);
}
public void linkUp() {
if (logger.isInfoEnabled()) {
logger.info("Received L4 Up event from layer3.");
}
this.linkUp = true;
this.streamData(_LINK_STATE_UP);
}
public void receive(String msg)
{
this.receive(msg.getBytes());
}
public void receive( byte[] msgBuff) {
// layer3 has something important, lets write.
//if(linkUp)
//{
logger.info("Preparing MSU to stream: "+Arrays.toString(msgBuff));
TLVOutputStream tlv = new TLVOutputStream();
try {
tlv.writeData(msgBuff);
byte[] data = tlv.toByteArray();
this.streamData(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//}
}
}
|
git-svn-id: https://mobicents.googlecode.com/svn/trunk/protocols/ss7@11841 bf0df8d0-2c1f-0410-b170-bd30377b63dc
| mtp/src/main/java/org/mobicents/protocols/ss7/stream/tcp/M3UserAgent.java | <ide><path>tp/src/main/java/org/mobicents/protocols/ss7/stream/tcp/M3UserAgent.java
<ide> cse.printStackTrace();
<ide> //check for server selector?
<ide> disconnect();
<del> } catch (IOException e) {
<add> } catch (Exception e) {
<ide> // TODO Auto-generated catch block
<ide> e.printStackTrace();
<ide> } |
||
Java | apache-2.0 | 0e77cb06589a0ecdb73464c2ffd3994be58ca068 | 0 | atomfrede/gradle-crowdin-cli-plugin | package io.github.atomfrede.gradle.plugins.crowdincli.task.download;
import io.github.atomfrede.gradle.plugins.crowdincli.CrowdinCliPlugin;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.Task;
import org.gradle.api.file.RelativePath;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopySpecInternal;
import org.gradle.api.internal.file.copy.DestinationRootCopySpec;
import org.gradle.api.internal.file.copy.FileCopyAction;
import org.gradle.api.tasks.AbstractCopyTask;
import org.gradle.api.tasks.Copy;
import org.gradle.api.tasks.OutputDirectory;
import org.gradle.internal.reflect.Instantiator;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* This tasks depends on @{@link CrowdinCliDownloadTask} and extracts the downloaded
* crowdin-cli.zip to 'gradle/corowdin-cli/crowdin-cli.jar`. The content of the
* archive is flatted such that only the executable jar file is extracted to the destination directory.
*/
public class CrowdinCliUnzipTask extends Copy {
public static final String TASK_NAME = "unzipCrowdinCli";
public static final String DESCRIPTION = "Unzip the crowdin cli into gradle/crowdin-cli";
public CrowdinCliUnzipTask() {
super();
getProject().getTasksByName("unzipCrowdinCli", true);
setDependsOn(Collections.singletonList(getDownloadTask()));
setGroup(CrowdinCliPlugin.GROUP);
setDescription(DESCRIPTION);
// only include the crowdin-cli.jar
include("**/*.jar");
setIncludeEmptyDirs(false);
from(getProject().zipTree(getDownloadTask().getDest()));
setDestinationDir(getDownloadTask().getDest().getParentFile());
// flatten the result, such that we have a stable path where to find the crowdin cli executable
eachFile(fileCopyDetails -> fileCopyDetails.setRelativePath(new RelativePath(true, fileCopyDetails.getName())));
}
private CrowdinCliDownloadTask getDownloadTask() {
Set<Task> tasks = getProject().getTasksByName(CrowdinCliDownloadTask.TASK_NAME, true);
List<Task> allTasks = new ArrayList<>();
allTasks.addAll(tasks);
if (allTasks.size() == 0) {
getLogger().error("Required task {} is missing.", CrowdinCliDownloadTask.TASK_NAME);
throw new RuntimeException(String.format("Required task %s is missing.", CrowdinCliDownloadTask.TASK_NAME));
}
return (CrowdinCliDownloadTask) allTasks.get(0);
}
}
| src/main/java/io/github/atomfrede/gradle/plugins/crowdincli/task/download/CrowdinCliUnzipTask.java | package io.github.atomfrede.gradle.plugins.crowdincli.task.download;
import io.github.atomfrede.gradle.plugins.crowdincli.CrowdinCliPlugin;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.Task;
import org.gradle.api.file.RelativePath;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopySpecInternal;
import org.gradle.api.internal.file.copy.DestinationRootCopySpec;
import org.gradle.api.internal.file.copy.FileCopyAction;
import org.gradle.api.tasks.AbstractCopyTask;
import org.gradle.api.tasks.OutputDirectory;
import org.gradle.internal.reflect.Instantiator;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* This tasks depends on @{@link CrowdinCliDownloadTask} and extracts the downloaded
* crowdin-cli.zip to 'gradle/corowdin-cli/crowdin-cli.jar`. The content of the
* archive is flatted such that only the executable jar file is extracted to the destination directory.
*/
public class CrowdinCliUnzipTask extends AbstractCopyTask {
public static final String TASK_NAME = "unzipCrowdinCli";
public static final String DESCRIPTION = "Unzip the crowdin cli into gradle/crowdin-cli";
public CrowdinCliUnzipTask() {
super();
getProject().getTasksByName("unzipCrowdinCli", true);
setDependsOn(Collections.singletonList(getDownloadTask()));
setGroup(CrowdinCliPlugin.GROUP);
setDescription(DESCRIPTION);
// only include the crowdin-cli.jar
include("**/*.jar");
setIncludeEmptyDirs(false);
from(getProject().zipTree(getDownloadTask().getDest()));
setDestinationDir(getDownloadTask().getDest().getParentFile());
// flatten the result, such that we have a stable path where to find the crowdin cli executable
eachFile(fileCopyDetails -> fileCopyDetails.setRelativePath(new RelativePath(true, fileCopyDetails.getName())));
}
private CrowdinCliDownloadTask getDownloadTask() {
Set<Task> tasks = getProject().getTasksByName(CrowdinCliDownloadTask.TASK_NAME, true);
List<Task> allTasks = new ArrayList<>();
allTasks.addAll(tasks);
if (allTasks.size() == 0) {
getLogger().error("Required task {} is missing.", CrowdinCliDownloadTask.TASK_NAME);
throw new RuntimeException(String.format("Required task %s is missing.", CrowdinCliDownloadTask.TASK_NAME));
}
return (CrowdinCliDownloadTask) allTasks.get(0);
}
@Override
protected CopyAction createCopyAction() {
File destinationDir = this.getDestinationDir();
if (destinationDir == null) {
throw new InvalidUserDataException("No copy destination directory has been specified, use 'into' to specify a target directory.");
} else {
return new FileCopyAction(this.getFileLookup().getFileResolver(destinationDir));
}
}
@Override
protected CopySpecInternal createRootSpec() {
Instantiator instantiator = this.getInstantiator();
FileResolver fileResolver = this.getFileResolver();
return (CopySpecInternal)instantiator.newInstance(DestinationRootCopySpec.class, new Object[]{fileResolver, super.createRootSpec()});
}
public DestinationRootCopySpec getRootSpec() {
return (DestinationRootCopySpec)super.getRootSpec();
}
@OutputDirectory
public File getDestinationDir() {
return this.getRootSpec().getDestinationDir();
}
public void setDestinationDir(File destinationDir) {
this.into(destinationDir);
}
}
| extend copy instead of abstract copy action
| src/main/java/io/github/atomfrede/gradle/plugins/crowdincli/task/download/CrowdinCliUnzipTask.java | extend copy instead of abstract copy action | <ide><path>rc/main/java/io/github/atomfrede/gradle/plugins/crowdincli/task/download/CrowdinCliUnzipTask.java
<ide> import org.gradle.api.internal.file.copy.DestinationRootCopySpec;
<ide> import org.gradle.api.internal.file.copy.FileCopyAction;
<ide> import org.gradle.api.tasks.AbstractCopyTask;
<add>import org.gradle.api.tasks.Copy;
<ide> import org.gradle.api.tasks.OutputDirectory;
<ide> import org.gradle.internal.reflect.Instantiator;
<ide>
<ide> * crowdin-cli.zip to 'gradle/corowdin-cli/crowdin-cli.jar`. The content of the
<ide> * archive is flatted such that only the executable jar file is extracted to the destination directory.
<ide> */
<del>public class CrowdinCliUnzipTask extends AbstractCopyTask {
<add>public class CrowdinCliUnzipTask extends Copy {
<ide>
<ide> public static final String TASK_NAME = "unzipCrowdinCli";
<ide> public static final String DESCRIPTION = "Unzip the crowdin cli into gradle/crowdin-cli";
<ide>
<ide> return (CrowdinCliDownloadTask) allTasks.get(0);
<ide> }
<del>
<del> @Override
<del> protected CopyAction createCopyAction() {
<del> File destinationDir = this.getDestinationDir();
<del> if (destinationDir == null) {
<del> throw new InvalidUserDataException("No copy destination directory has been specified, use 'into' to specify a target directory.");
<del> } else {
<del> return new FileCopyAction(this.getFileLookup().getFileResolver(destinationDir));
<del> }
<del> }
<del>
<del> @Override
<del> protected CopySpecInternal createRootSpec() {
<del>
<del> Instantiator instantiator = this.getInstantiator();
<del> FileResolver fileResolver = this.getFileResolver();
<del> return (CopySpecInternal)instantiator.newInstance(DestinationRootCopySpec.class, new Object[]{fileResolver, super.createRootSpec()});
<del> }
<del>
<del> public DestinationRootCopySpec getRootSpec() {
<del> return (DestinationRootCopySpec)super.getRootSpec();
<del> }
<del>
<del> @OutputDirectory
<del> public File getDestinationDir() {
<del> return this.getRootSpec().getDestinationDir();
<del> }
<del>
<del> public void setDestinationDir(File destinationDir) {
<del> this.into(destinationDir);
<del> }
<ide> } |
|
JavaScript | mit | e2567533454d25497aa4dbe36e32cb1c38d6d67b | 0 | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | import React, { useState } from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import {
FormModal,
Row,
Field,
Label,
PasswordInput,
Input,
Checkbox,
Select,
useApi,
useNotifications,
useEventManager
} from 'react-components';
import MemberStorageSelector from './MemberStorageSelector';
import MemberVPNSelector from './MemberVPNSelector';
import { DEFAULT_ENCRYPTION_CONFIG, ENCRYPTION_CONFIGS, GIGA } from 'proton-shared/lib/constants';
import { createMember, createMemberAddress } from 'proton-shared/lib/api/members';
import { setupMemberKey } from './actionHelper';
import SelectEncryption from '../keys/addKey/SelectEncryption';
import { srpVerify } from 'proton-shared/lib/srp';
const FIVE_GIGA = 5 * GIGA;
const MemberModal = ({ onClose, organization, organizationKey, domains, ...rest }) => {
const { createNotification } = useNotifications();
const { call } = useEventManager();
const api = useApi();
const [model, updateModel] = useState({
name: '',
private: false,
password: '',
confirm: '',
address: '',
domain: domains[0].DomainName,
vpn: 1,
storage: FIVE_GIGA
});
const update = (key, value) => updateModel({ ...model, [key]: value });
const [encryptionType, setEncryptionType] = useState(DEFAULT_ENCRYPTION_CONFIG);
const [loading, setLoading] = useState(false);
const hasVPN = !!organization.MaxVPN;
const domainOptions = domains.map(({ DomainName }) => ({ text: DomainName, value: DomainName }));
const handleChange = (key) => ({ target }) => update(key, target.value);
const handleChangePrivate = ({ target }) => update('private', target.checked);
const handleChangeStorage = (value) => update('storage', value);
const handleChangeVPN = (value) => update('vpn', value);
const save = async () => {
const { Member } = await srpVerify({
api,
credentials: { password: model.password },
config: createMember({
Name: model.name,
Private: +model.private,
MaxSpace: model.storage,
MaxVPN: model.vpn
})
});
const { Address } = await api(
createMemberAddress(Member.ID, {
Local: model.address,
Domain: model.domain
})
);
if (!model.private) {
await setupMemberKey({
api,
Member,
Address,
organizationKey,
encryptionConfig: ENCRYPTION_CONFIGS[encryptionType],
password: model.password
});
}
};
const validate = () => {
if (!model.name.length) {
return c('Error').t`Invalid name`;
}
if (!model.private && model.password !== model.confirm) {
return c('Error').t`Invalid password`;
}
if (!model.address.length) {
return c('Error').t`Invalid address`;
}
const domain = domains.find(({ DomainName }) => DomainName === model.domain);
const address = domain.addresses.find(({ Email }) => Email === `${model.address}@${model.domain}`);
if (address) {
return c('Error').t`Address already associated to a user`;
}
if (!model.private && !organizationKey) {
return c('Error').t`The organization key must be activated first.`;
}
};
const handleSubmit = async () => {
const error = validate();
if (error) {
return createNotification({ type: 'error', text: error });
}
try {
setLoading(true);
await save();
await call();
onClose();
createNotification({ text: c('Success').t`User created` });
} catch (e) {
setLoading(false);
}
};
return (
<FormModal
title={c('Title').t`Add user`}
loading={loading}
onSubmit={handleSubmit}
onClose={onClose}
close={c('Action').t`Cancel`}
submit={c('Action').t`Save`}
{...rest}
>
<Row>
<Label htmlFor="nameInput">{c('Label').t`Name`}</Label>
<Field>
<Input id="nameInput" placeholder="Thomas A. Anderson" onChange={handleChange('name')} required />
</Field>
<div className="ml1 flex flex-nowrap flex-items-center">
<Checkbox checked={model.private} onChange={handleChangePrivate} />
{c('Label for new member').t`Private`}
</div>
</Row>
{model.private ? null : (
<Row>
<Label>{c('Label').t`Key strength`}</Label>
<div>
<SelectEncryption encryptionType={encryptionType} setEncryptionType={setEncryptionType} />
</div>
</Row>
)}
<Row>
<Label>{c('Label').t`Password`}</Label>
<Field>
<div className="mb1">
<PasswordInput
value={model.password}
onChange={handleChange('password')}
placeholder={c('Placeholder').t`Password`}
required
/>
</div>
<div>
<PasswordInput
value={model.confirm}
onChange={handleChange('confirm')}
placeholder={c('Placeholder').t`Confirm password`}
required
/>
</div>
</Field>
</Row>
<Row>
<Label>{c('Label').t`Address`}</Label>
<Field>
<Input onChange={handleChange('address')} placeholder={c('Placeholder').t`Address`} required />
</Field>
<div className="ml1 flex flex-nowrap flex-items-center">
{domainOptions.length === 1 ? (
`@${domainOptions[0].value}`
) : (
<Select options={domainOptions} value={model.domain} onChange={handleChange('domain')} />
)}
</div>
</Row>
<Row>
<Label>{c('Label').t`Account storage`}</Label>
<Field>
<MemberStorageSelector organization={organization} onChange={handleChangeStorage} />
</Field>
</Row>
{hasVPN ? (
<Row>
<Label>{c('Label').t`VPN connections`}</Label>
<Field>
<MemberVPNSelector organization={organization} onChange={handleChangeVPN} />
</Field>
</Row>
) : null}
</FormModal>
);
};
MemberModal.propTypes = {
onClose: PropTypes.func,
organization: PropTypes.object.isRequired,
organizationKey: PropTypes.object.isRequired,
domains: PropTypes.array.isRequired
};
export default MemberModal;
| packages/components/containers/members/MemberModal.js | import React, { useState } from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import {
FormModal,
Row,
Field,
Label,
PasswordInput,
Input,
Checkbox,
Select,
useApi,
useNotifications,
useEventManager
} from 'react-components';
import MemberStorageSelector from './MemberStorageSelector';
import MemberVPNSelector from './MemberVPNSelector';
import { DEFAULT_ENCRYPTION_CONFIG, ENCRYPTION_CONFIGS, GIGA } from 'proton-shared/lib/constants';
import { createMember, createMemberAddress } from 'proton-shared/lib/api/members';
import { setupMemberKey } from './actionHelper';
import SelectEncryption from '../keys/addKey/SelectEncryption';
import { srpVerify } from 'proton-shared/lib/srp';
const FIVE_GIGA = 5 * GIGA;
const MemberModal = ({ onClose, organization, organizationKey, domains, ...rest }) => {
const { createNotification } = useNotifications();
const { call } = useEventManager();
const api = useApi();
const [model, updateModel] = useState({
name: '',
private: false,
password: '',
confirm: '',
address: '',
domain: domains[0].DomainName,
vpn: 1,
storage: FIVE_GIGA
});
const update = (key, value) => updateModel({ ...model, [key]: value });
const [encryptionType, setEncryptionType] = useState(DEFAULT_ENCRYPTION_CONFIG);
const [loading, setLoading] = useState(false);
const hasVPN = !!organization.MaxVPN;
const domainOptions = domains.map(({ DomainName }) => ({ text: DomainName, value: DomainName }));
const handleChange = (key) => ({ target }) => update(key, target.value);
const handleChangePrivate = ({ target }) => update('private', target.checked);
const handleChangeStorage = (value) => update('storage', value);
const handleChangeVPN = (value) => update('vpn', value);
const save = async () => {
const { Member } = await srpVerify({
api,
credentials: { password: model.password },
config: createMember({
Name: model.name,
Private: +model.private,
MaxSpace: model.storage,
MaxVPN: model.vpn
})
});
const { Address } = await api(
createMemberAddress(Member.ID, {
Local: model.address,
Domain: model.domain
})
);
if (!model.private) {
await setupMemberKey({
api,
Member,
Address,
organizationKey,
encryptionConfig: ENCRYPTION_CONFIGS[encryptionType],
password: model.password
});
}
};
const validate = () => {
if (!model.name.length) {
return c('Error').t`Invalid name`;
}
if (!model.private && model.password !== model.confirm) {
return c('Error').t`Invalid password`;
}
if (!model.address.length) {
return c('Error').t`Invalid address`;
}
const domain = domains.find(({ DomainName }) => DomainName === model.domain);
const address = domain.addresses.find(({ Email }) => Email === `${model.address}@${model.domain}`);
if (address) {
return c('Error').t`Address already associated to a user`;
}
if (!model.private && !organizationKey) {
return c('Error').t`The organization key must be activated first.`;
}
};
const handleSubmit = async () => {
const error = validate();
if (error) {
return createNotification({ type: 'error', text: error });
}
try {
setLoading(true);
await save();
await call();
onClose();
createNotification({ text: c('Success').t`User created` });
} catch (e) {
setLoading(false);
}
};
return (
<FormModal
title={c('Title').t`Add user`}
loading={loading}
onSubmit={handleSubmit}
onClose={onClose}
close={c('Action').t`Cancel`}
submit={c('Action').t`Save`}
{...rest}
>
<Row>
<Label htmlFor="nameInput">{c('Label').t`Name`}</Label>
<Field className="flex-autogrid">
<Input
id="nameInput"
className="flex-autogrid-item"
placeholder="Thomas A. Anderson"
onChange={handleChange('name')}
required
/>
<Label className="flex-autogrid-item">
<Checkbox checked={model.private} onChange={handleChangePrivate} />
{c('Label for new member').t`Private`}
</Label>
</Field>
</Row>
{model.private ? null : (
<Row>
<Label>{c('Label').t`Key strength`}</Label>
<Field className="flex-autogrid">
<SelectEncryption encryptionType={encryptionType} setEncryptionType={setEncryptionType} />
</Field>
</Row>
)}
<Row>
<Label>{c('Label').t`Password`}</Label>
<Field className="flex-autogrid">
<PasswordInput
value={model.password}
className="flex-autogrid-item mb1"
onChange={handleChange('password')}
placeholder={c('Placeholder').t`Password`}
required
/>
<PasswordInput
value={model.confirm}
className="flex-autogrid-item"
onChange={handleChange('confirm')}
placeholder={c('Placeholder').t`Confirm password`}
required
/>
</Field>
</Row>
<Row>
<Label>{c('Label').t`Address`}</Label>
<Field className="flex-autogrid">
<Input onChange={handleChange('address')} placeholder={c('Placeholder').t`Address`} required />
{domainOptions.length === 1 ? (
`@${domainOptions[0].value}`
) : (
<Select options={domainOptions} value={model.domain} onChange={handleChange('domain')} />
)}
</Field>
</Row>
<Row>
<Label>{c('Label').t`Account storage`}</Label>
<Field>
<MemberStorageSelector organization={organization} onChange={handleChangeStorage} />
</Field>
</Row>
{hasVPN ? (
<Row>
<Label>{c('Label').t`VPN connections`}</Label>
<Field>
<MemberVPNSelector organization={organization} onChange={handleChangeVPN} />
</Field>
</Row>
) : null}
</FormModal>
);
};
MemberModal.propTypes = {
onClose: PropTypes.func,
organization: PropTypes.object.isRequired,
organizationKey: PropTypes.object.isRequired,
domains: PropTypes.array.isRequired
};
export default MemberModal;
| Review member modal structure
| packages/components/containers/members/MemberModal.js | Review member modal structure | <ide><path>ackages/components/containers/members/MemberModal.js
<ide> >
<ide> <Row>
<ide> <Label htmlFor="nameInput">{c('Label').t`Name`}</Label>
<del> <Field className="flex-autogrid">
<del> <Input
<del> id="nameInput"
<del> className="flex-autogrid-item"
<del> placeholder="Thomas A. Anderson"
<del> onChange={handleChange('name')}
<del> required
<del> />
<del> <Label className="flex-autogrid-item">
<del> <Checkbox checked={model.private} onChange={handleChangePrivate} />
<del> {c('Label for new member').t`Private`}
<del> </Label>
<del> </Field>
<add> <Field>
<add> <Input id="nameInput" placeholder="Thomas A. Anderson" onChange={handleChange('name')} required />
<add> </Field>
<add> <div className="ml1 flex flex-nowrap flex-items-center">
<add> <Checkbox checked={model.private} onChange={handleChangePrivate} />
<add> {c('Label for new member').t`Private`}
<add> </div>
<ide> </Row>
<ide> {model.private ? null : (
<ide> <Row>
<ide> <Label>{c('Label').t`Key strength`}</Label>
<del> <Field className="flex-autogrid">
<add> <div>
<ide> <SelectEncryption encryptionType={encryptionType} setEncryptionType={setEncryptionType} />
<del> </Field>
<add> </div>
<ide> </Row>
<ide> )}
<ide> <Row>
<ide> <Label>{c('Label').t`Password`}</Label>
<del> <Field className="flex-autogrid">
<del> <PasswordInput
<del> value={model.password}
<del> className="flex-autogrid-item mb1"
<del> onChange={handleChange('password')}
<del> placeholder={c('Placeholder').t`Password`}
<del> required
<del> />
<del> <PasswordInput
<del> value={model.confirm}
<del> className="flex-autogrid-item"
<del> onChange={handleChange('confirm')}
<del> placeholder={c('Placeholder').t`Confirm password`}
<del> required
<del> />
<add> <Field>
<add> <div className="mb1">
<add> <PasswordInput
<add> value={model.password}
<add> onChange={handleChange('password')}
<add> placeholder={c('Placeholder').t`Password`}
<add> required
<add> />
<add> </div>
<add> <div>
<add> <PasswordInput
<add> value={model.confirm}
<add> onChange={handleChange('confirm')}
<add> placeholder={c('Placeholder').t`Confirm password`}
<add> required
<add> />
<add> </div>
<ide> </Field>
<ide> </Row>
<ide> <Row>
<ide> <Label>{c('Label').t`Address`}</Label>
<del> <Field className="flex-autogrid">
<add> <Field>
<ide> <Input onChange={handleChange('address')} placeholder={c('Placeholder').t`Address`} required />
<add> </Field>
<add> <div className="ml1 flex flex-nowrap flex-items-center">
<ide> {domainOptions.length === 1 ? (
<ide> `@${domainOptions[0].value}`
<ide> ) : (
<ide> <Select options={domainOptions} value={model.domain} onChange={handleChange('domain')} />
<ide> )}
<del> </Field>
<add> </div>
<ide> </Row>
<ide> <Row>
<ide> <Label>{c('Label').t`Account storage`}</Label> |
|
Java | apache-2.0 | 80310898a08da64e82314d6562a1a751d4e5f7d8 | 0 | SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java | /*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.event.model;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.Any;
import io.spine.base.EventMessage;
import io.spine.base.FieldPath;
import io.spine.server.event.EventSubscriber;
import io.spine.server.model.AbstractHandlerMethod;
import io.spine.server.model.FilteringHandler;
import io.spine.server.model.HandlerId;
import io.spine.server.model.MessageFilter;
import io.spine.server.model.ParameterSpec;
import io.spine.server.model.VoidMethod;
import io.spine.server.type.EmptyClass;
import io.spine.server.type.EventClass;
import io.spine.server.type.EventEnvelope;
import java.lang.reflect.Method;
import java.util.function.Supplier;
import static com.google.common.base.Suppliers.memoize;
import static io.spine.base.FieldPaths.getValue;
import static io.spine.protobuf.TypeConverter.toObject;
/**
* A method annotated with the {@link io.spine.core.Subscribe @Subscribe} annotation.
*
* <p>Such a method may have side effects, but provides no visible output.
*
* @see io.spine.core.Subscribe
*/
@Immutable
public abstract class SubscriberMethod
extends AbstractHandlerMethod<EventSubscriber,
EventMessage,
EventClass,
EventEnvelope,
EmptyClass>
implements VoidMethod<EventSubscriber, EventClass, EventEnvelope>,
FilteringHandler<EventSubscriber, EventClass, EventEnvelope, EmptyClass> {
@SuppressWarnings("Immutable") // because this `Supplier` is effectively immutable.
private final Supplier<MessageFilter> filter = memoize(this::createFilter);
protected SubscriberMethod(Method method, ParameterSpec<EventEnvelope> parameterSpec) {
super(method, parameterSpec);
}
@Override
public HandlerId id() {
HandlerId typeBasedToken = super.id();
MessageFilter filter = filter();
FieldPath fieldPath = filter.getField();
return fieldPath.getFieldNameList().isEmpty()
? typeBasedToken
: typeBasedToken.toBuilder()
.setFilter(filter)
.build();
}
@Override
public EventClass messageClass() {
return EventClass.from(rawMessageClass());
}
/**
* Creates the filter for messages handled by this method.
*/
protected abstract MessageFilter createFilter();
@Override
public final MessageFilter filter() {
return filter.get();
}
/**
* Checks if this method can handle the given event.
*
* <p>It is assumed that the type of the event is correct and only the field filter should be
* checked.
*
* @param event the event to check
* @return {@code true} if this method can handle the given event, {@code false} otherwise
*/
final boolean canHandle(EventEnvelope event) {
MessageFilter filter = filter();
FieldPath fieldPath = filter.getField();
if (fieldPath.getFieldNameList().isEmpty()) {
return true;
} else {
EventMessage msg = event.message();
return match(msg, filter);
}
}
private static boolean match(EventMessage event, MessageFilter filter) {
FieldPath path = filter.getField();
Object valueOfField = getValue(path, event);
Any value = filter.getValue();
Object expectedValue = toObject(value, valueOfField.getClass());
boolean filterMatches = valueOfField.equals(expectedValue);
return filterMatches;
}
}
| server/src/main/java/io/spine/server/event/model/SubscriberMethod.java | /*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.event.model;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.Any;
import io.spine.base.EventMessage;
import io.spine.base.FieldPath;
import io.spine.server.event.EventSubscriber;
import io.spine.server.model.AbstractHandlerMethod;
import io.spine.server.model.FilteringHandler;
import io.spine.server.model.HandlerId;
import io.spine.server.model.MessageFilter;
import io.spine.server.model.ParameterSpec;
import io.spine.server.model.VoidMethod;
import io.spine.server.type.EmptyClass;
import io.spine.server.type.EventClass;
import io.spine.server.type.EventEnvelope;
import java.lang.reflect.Method;
import java.util.function.Supplier;
import static com.google.common.base.Suppliers.memoize;
import static io.spine.base.FieldPaths.getValue;
import static io.spine.protobuf.TypeConverter.toObject;
/**
* A method annotated with the {@link io.spine.core.Subscribe @Subscribe} annotation.
*
* <p>Such a method may have side effects, but provides no visible output.
*
* @see io.spine.core.Subscribe
*/
@Immutable
public abstract class SubscriberMethod
extends AbstractHandlerMethod<EventSubscriber,
EventMessage,
EventClass,
EventEnvelope,
EmptyClass>
implements VoidMethod<EventSubscriber, EventClass, EventEnvelope>,
FilteringHandler<EventSubscriber, EventClass, EventEnvelope, EmptyClass> {
@SuppressWarnings("Immutable") // because this `Supplier` is effectively immutable.
private final Supplier<MessageFilter> filter = memoize(this::createFilter);
protected SubscriberMethod(Method method, ParameterSpec<EventEnvelope> parameterSpec) {
super(method, parameterSpec);
}
@Override
public HandlerId id() {
HandlerId typeBasedToken = super.id();
MessageFilter filter = filter();
FieldPath fieldPath = filter.getField();
return fieldPath.getFieldNameList().isEmpty()
? typeBasedToken
: typeBasedToken.toBuilder()
.setFilter(filter)
.build();
}
@Override
public EventClass messageClass() {
return EventClass.from(rawMessageClass());
}
/**
* Creates the filter for messages handled by this method.
*/
protected abstract MessageFilter createFilter();
@Override
public MessageFilter filter() {
return filter.get();
}
/**
* Checks if this method can handle the given event.
*
* <p>It is assumed that the type of the event is correct and only the field filter should be
* checked.
*
* @param event the event to check
* @return {@code true} if this method can handle the given event, {@code false} otherwise
*/
final boolean canHandle(EventEnvelope event) {
MessageFilter filter = filter();
FieldPath fieldPath = filter.getField();
if (fieldPath.getFieldNameList().isEmpty()) {
return true;
} else {
EventMessage msg = event.message();
return match(msg, filter);
}
}
private static boolean match(EventMessage event, MessageFilter filter) {
FieldPath path = filter.getField();
Object valueOfField = getValue(path, event);
Any value = filter.getValue();
Object expectedValue = toObject(value, valueOfField.getClass());
boolean filterMatches = valueOfField.equals(expectedValue);
return filterMatches;
}
}
| Make method final
| server/src/main/java/io/spine/server/event/model/SubscriberMethod.java | Make method final | <ide><path>erver/src/main/java/io/spine/server/event/model/SubscriberMethod.java
<ide> protected abstract MessageFilter createFilter();
<ide>
<ide> @Override
<del> public MessageFilter filter() {
<add> public final MessageFilter filter() {
<ide> return filter.get();
<ide> }
<ide> |
|
Java | apache-2.0 | 803e6e2cea52e9ef57dfd5aba9bd25c58727532b | 0 | panossot/xnio,kabir/xnio,panossot/xnio,xnio/xnio,fl4via/xnio,stuartwdouglas/xnio,kabir/xnio,xnio/xnio,dmlloyd/xnio,fl4via/xnio | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2011 Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xnio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Set;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import org.xnio.channels.AcceptingChannel;
import org.xnio.channels.BoundChannel;
import org.xnio.channels.Channels;
import org.xnio.channels.CloseableChannel;
import org.xnio.channels.Configurable;
import org.xnio.channels.ConnectedMessageChannel;
import org.xnio.channels.ConnectedStreamChannel;
import org.xnio.channels.MulticastMessageChannel;
import org.xnio.channels.StreamChannel;
import org.xnio.channels.StreamSinkChannel;
import org.xnio.channels.StreamSourceChannel;
import org.xnio.streams.ChannelInputStream;
import org.xnio.streams.ChannelOutputStream;
import static org.xnio.Messages.msg;
/**
* A worker for I/O channel notification.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*
* @since 3.0
*/
@SuppressWarnings("unused")
public abstract class XnioWorker extends AbstractExecutorService implements Configurable, ExecutorService {
private final Xnio xnio;
private final TaskPool taskPool;
private final String name;
private final Runnable terminationTask;
private volatile int taskSeq;
private volatile int coreSize;
private static final AtomicIntegerFieldUpdater<XnioWorker> taskSeqUpdater = AtomicIntegerFieldUpdater.newUpdater(XnioWorker.class, "taskSeq");
private static final AtomicIntegerFieldUpdater<XnioWorker> coreSizeUpdater = AtomicIntegerFieldUpdater.newUpdater(XnioWorker.class, "coreSize");
private static final AtomicInteger seq = new AtomicInteger(1);
private int getNextSeq() {
return taskSeqUpdater.incrementAndGet(this);
}
/**
* Construct a new instance. Intended to be called only from implementations. To construct an XNIO worker,
* use the {@link Xnio#createWorker(OptionMap)} method.
*
* @param xnio the XNIO provider which produced this worker instance
* @param threadGroup the thread group for worker threads
* @param optionMap the option map to use to configure this worker
* @param terminationTask
*/
protected XnioWorker(final Xnio xnio, final ThreadGroup threadGroup, final OptionMap optionMap, final Runnable terminationTask) {
this.xnio = xnio;
this.terminationTask = terminationTask;
String workerName = optionMap.get(Options.WORKER_NAME);
if (workerName == null) {
workerName = "XNIO-" + seq.getAndIncrement();
}
name = workerName;
BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>();
this.coreSize = optionMap.get(Options.WORKER_TASK_CORE_THREADS, 4);
final boolean markThreadAsDaemon = optionMap.get(Options.THREAD_DAEMON, false);
taskPool = new TaskPool(
optionMap.get(Options.WORKER_TASK_MAX_THREADS, 16), // ignore core threads setting, always fill to max
optionMap.get(Options.WORKER_TASK_MAX_THREADS, 16),
optionMap.get(Options.WORKER_TASK_KEEPALIVE, 60), TimeUnit.MILLISECONDS,
taskQueue,
new ThreadFactory() {
public Thread newThread(final Runnable r) {
final Thread taskThread = new Thread(threadGroup, r, name + " task-" + getNextSeq(), optionMap.get(Options.STACK_SIZE, 0L));
// Mark the thread as daemon if the Options.THREAD_DAEMON has been set
if (markThreadAsDaemon) {
taskThread.setDaemon(true);
}
return taskThread;
}
}, new ThreadPoolExecutor.AbortPolicy());
}
//==================================================
//
// Stream methods
//
//==================================================
// Servers
/**
* Create a stream server, for TCP or UNIX domain servers. The type of server is determined by the bind address.
*
* @param bindAddress the address to bind to
* @param acceptListener the initial accept listener
* @param optionMap the initial configuration for the server
* @return the acceptor
* @throws IOException if the server could not be created
*/
public AcceptingChannel<? extends ConnectedStreamChannel> createStreamServer(SocketAddress bindAddress, ChannelListener<? super AcceptingChannel<ConnectedStreamChannel>> acceptListener, OptionMap optionMap) throws IOException {
if (bindAddress == null) {
throw msg.nullParameter("bindAddress");
}
if (bindAddress instanceof InetSocketAddress) {
return createTcpServer((InetSocketAddress) bindAddress, acceptListener, optionMap);
} else if (bindAddress instanceof LocalSocketAddress) {
return createLocalStreamServer((LocalSocketAddress) bindAddress, acceptListener, optionMap);
} else {
throw msg.badSockType(bindAddress.getClass());
}
}
/**
* Implementation helper method to create a TCP stream server.
*
* @param bindAddress the address to bind to
* @param acceptListener the initial accept listener
* @param optionMap the initial configuration for the server
* @return the acceptor
* @throws IOException if the server could not be created
*/
protected AcceptingChannel<? extends ConnectedStreamChannel> createTcpServer(InetSocketAddress bindAddress, ChannelListener<? super AcceptingChannel<ConnectedStreamChannel>> acceptListener, OptionMap optionMap) throws IOException {
throw new UnsupportedOperationException("TCP server");
}
/**
* Implementation helper method to create a UNIX domain stream server.
*
* @param bindAddress the address to bind to
* @param acceptListener the initial accept listener
* @param optionMap the initial configuration for the server
* @return the acceptor
* @throws IOException if the server could not be created
*/
protected AcceptingChannel<? extends ConnectedStreamChannel> createLocalStreamServer(LocalSocketAddress bindAddress, ChannelListener<? super AcceptingChannel<ConnectedStreamChannel>> acceptListener, OptionMap optionMap) throws IOException {
throw new UnsupportedOperationException("UNIX stream server");
}
// Connectors
/**
* Connect to a remote stream server. The protocol family is determined by the type of the socket address given.
*
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
public IoFuture<ConnectedStreamChannel> connectStream(SocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, OptionMap optionMap) {
if (destination == null) {
throw msg.nullParameter("destination");
}
if (destination instanceof InetSocketAddress) {
return connectTcpStream(Xnio.ANY_INET_ADDRESS, (InetSocketAddress) destination, openListener, null, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return connectLocalStream(Xnio.ANY_LOCAL_ADDRESS, (LocalSocketAddress) destination, openListener, null, optionMap);
} else {
throw msg.badSockType(destination.getClass());
}
}
/**
* Connect to a remote stream server. The protocol family is determined by the type of the socket address given.
*
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
public IoFuture<ConnectedStreamChannel> connectStream(SocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (destination == null) {
throw msg.nullParameter("destination");
}
if (destination instanceof InetSocketAddress) {
return connectTcpStream(Xnio.ANY_INET_ADDRESS, (InetSocketAddress) destination, openListener, bindListener, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return connectLocalStream(Xnio.ANY_LOCAL_ADDRESS, (LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw msg.badSockType(destination.getClass());
}
}
/**
* Connect to a remote stream server. The protocol family is determined by the type of the socket addresses given
* (which must match).
*
* @param bindAddress the local address to bind to
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
public IoFuture<ConnectedStreamChannel> connectStream(SocketAddress bindAddress, SocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (bindAddress == null) {
throw msg.nullParameter("bindAddress");
}
if (destination == null) {
throw msg.nullParameter("destination");
}
if (bindAddress.getClass() != destination.getClass()) {
throw msg.mismatchSockType(bindAddress.getClass(), destination.getClass());
}
if (destination instanceof InetSocketAddress) {
return connectTcpStream((InetSocketAddress) bindAddress, (InetSocketAddress) destination, openListener, bindListener, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return connectLocalStream((LocalSocketAddress) bindAddress, (LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw msg.badSockType(destination.getClass());
}
}
/**
* Implementation helper method to connect to a TCP server.
*
* @param bindAddress the bind address
* @param destinationAddress the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map @return the future result of this operation
* @return the future result of this operation
*/
protected IoFuture<ConnectedStreamChannel> connectTcpStream(InetSocketAddress bindAddress, InetSocketAddress destinationAddress, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Connect to TCP server");
}
/**
* Implementation helper method to connect to a local (UNIX domain) server.
*
* @param bindAddress the bind address
* @param destinationAddress the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
protected IoFuture<ConnectedStreamChannel> connectLocalStream(LocalSocketAddress bindAddress, LocalSocketAddress destinationAddress, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Connect to local stream server");
}
// Acceptors
/**
* Accept a stream connection at a destination address. If a wildcard address is specified, then a destination address
* is chosen in a manner specific to the OS and/or channel type.
*
* @param destination the destination (bind) address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the acceptor is bound, or {@code null} for none
* @param optionMap the option map
* @return the future connection
*/
public IoFuture<ConnectedStreamChannel> acceptStream(SocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (destination == null) {
throw msg.nullParameter("destination");
}
if (destination instanceof InetSocketAddress) {
return acceptTcpStream((InetSocketAddress) destination, openListener, bindListener, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return acceptLocalStream((LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw msg.badSockType(destination.getClass());
}
}
/**
* Implementation helper method to accept a local (UNIX domain) stream connection.
*
* @param destination the destination (bind) address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the acceptor is bound, or {@code null} for none
* @param optionMap the option map
*
* @return the future connection
*/
protected IoFuture<ConnectedStreamChannel> acceptLocalStream(LocalSocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Accept a local stream connection");
}
/**
* Implementation helper method to accept a TCP connection.
*
* @param destination the destination (bind) address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the acceptor is bound, or {@code null} for none
* @param optionMap the option map
*
* @return the future connection
*/
protected IoFuture<ConnectedStreamChannel> acceptTcpStream(InetSocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Accept a TCP connection");
}
//==================================================
//
// Message (datagram) channel methods
//
//==================================================
/**
* Connect to a remote stream server. The protocol family is determined by the type of the socket address given.
*
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
public IoFuture<ConnectedMessageChannel> connectDatagram(SocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (destination == null) {
throw msg.nullParameter("destination");
}
if (destination instanceof InetSocketAddress) {
return connectUdpDatagram(Xnio.ANY_INET_ADDRESS, (InetSocketAddress) destination, openListener, bindListener, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return connectLocalDatagram(Xnio.ANY_LOCAL_ADDRESS, (LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw msg.badSockType(destination.getClass());
}
}
/**
* Connect to a remote datagram server. The protocol family is determined by the type of the socket addresses given
* (which must match).
*
* @param bindAddress the local address to bind to
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
public IoFuture<ConnectedMessageChannel> connectDatagram(SocketAddress bindAddress, SocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (bindAddress == null) {
throw new IllegalArgumentException("bindAddress is null");
}
if (destination == null) {
throw new IllegalArgumentException("destination is null");
}
if (bindAddress.getClass() != destination.getClass()) {
throw new IllegalArgumentException("Bind address " + bindAddress.getClass() + " is not the same type as destination address " + destination.getClass());
}
if (destination instanceof InetSocketAddress) {
return connectUdpDatagram((InetSocketAddress) bindAddress, (InetSocketAddress) destination, openListener, bindListener, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return connectLocalDatagram((LocalSocketAddress) bindAddress, (LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw new UnsupportedOperationException("Connect to server with socket address " + destination.getClass());
}
}
/**
* Implementation helper method to connect to a UDP server.
*
* @param bindAddress the bind address
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
protected IoFuture<ConnectedMessageChannel> connectUdpDatagram(InetSocketAddress bindAddress, InetSocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Connect to UDP server");
}
/**
* Implementation helper method to connect to a local (UNIX domain) datagram server.
*
* @param bindAddress the bind address
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
protected IoFuture<ConnectedMessageChannel> connectLocalDatagram(LocalSocketAddress bindAddress, LocalSocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Connect to local datagram server");
}
// Acceptors
/**
* Accept a message connection at a destination address. If a wildcard address is specified, then a destination address
* is chosen in a manner specific to the OS and/or channel type.
*
* @param destination the destination (bind) address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the acceptor is bound, or {@code null} for none
* @param optionMap the option map
* @return the future connection
*/
public IoFuture<ConnectedMessageChannel> acceptDatagram(SocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (destination == null) {
throw new IllegalArgumentException("destination is null");
}
if (destination instanceof LocalSocketAddress) {
return acceptLocalDatagram((LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw new UnsupportedOperationException("Accept a connection to socket address " + destination.getClass());
}
}
/**
* Implementation helper method to accept a local (UNIX domain) datagram connection.
*
* @param destination the destination (bind) address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the acceptor is bound, or {@code null} for none
* @param optionMap the option map
*
* @return the future connection
*/
protected IoFuture<ConnectedMessageChannel> acceptLocalDatagram(LocalSocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Accept a local message connection");
}
//==================================================
//
// UDP methods
//
//==================================================
/**
* Create a UDP server. The UDP server can be configured to be multicast-capable; this should only be
* done if multicast is needed, since some providers have a performance penalty associated with multicast.
* The provider's default executor will be used to execute listener methods.
*
* @param bindAddress the bind address
* @param bindListener the initial open-connection listener
* @param optionMap the initial configuration for the server
* @return the UDP server channel
* @throws IOException if the server could not be created
*
* @since 3.0
*/
public MulticastMessageChannel createUdpServer(InetSocketAddress bindAddress, ChannelListener<? super MulticastMessageChannel> bindListener, OptionMap optionMap) throws IOException {
throw new UnsupportedOperationException("UDP Server");
}
/**
* Create a UDP server. The UDP server can be configured to be multicast-capable; this should only be
* done if multicast is needed, since some providers have a performance penalty associated with multicast.
* The provider's default executor will be used to execute listener methods.
*
* @param bindAddress the bind address
* @param optionMap the initial configuration for the server
* @return the UDP server channel
* @throws IOException if the server could not be created
*
* @since 3.0
*/
public MulticastMessageChannel createUdpServer(InetSocketAddress bindAddress, OptionMap optionMap) throws IOException {
return createUdpServer(bindAddress, ChannelListeners.nullChannelListener(), optionMap);
}
//==================================================
//
// Stream pipe methods
//
//==================================================
/**
* Open a bidirectional stream pipe.
*
* @param leftOpenListener the left-hand open listener
* @param rightOpenListener the right-hand open listener
* @param optionMap the pipe channel configuration
* @throws IOException if the pipe could not be created
* @deprecated Users should prefer the simpler {@link #createFullDuplexPipe()} instead.
*/
@Deprecated
public void createPipe(ChannelListener<? super StreamChannel> leftOpenListener, ChannelListener<? super StreamChannel> rightOpenListener, final OptionMap optionMap) throws IOException {
final ChannelPipe<StreamChannel, StreamChannel> pipe = createFullDuplexPipe();
final boolean establishWriting = optionMap.get(Options.WORKER_ESTABLISH_WRITING, false);
final StreamChannel left = pipe.getLeftSide();
XnioExecutor leftExec = establishWriting ? left.getWriteThread() : left.getReadThread();
final StreamChannel right = pipe.getRightSide();
XnioExecutor rightExec = establishWriting ? right.getWriteThread() : right.getReadThread();
// not unsafe - http://youtrack.jetbrains.net/issue/IDEA-59290
//noinspection unchecked
leftExec.execute(ChannelListeners.getChannelListenerTask(left, leftOpenListener));
// not unsafe - http://youtrack.jetbrains.net/issue/IDEA-59290
//noinspection unchecked
rightExec.execute(ChannelListeners.getChannelListenerTask(right, rightOpenListener));
}
/**
* Open a unidirectional stream pipe.
*
* @param sourceListener the source open listener
* @param sinkListener the sink open listener
* @param optionMap the pipe channel configuration
* @throws IOException if the pipe could not be created
* @deprecated Users should prefer the simpler {@link #createHalfDuplexPipe()} instead.
*/
@Deprecated
public void createOneWayPipe(ChannelListener<? super StreamSourceChannel> sourceListener, ChannelListener<? super StreamSinkChannel> sinkListener, final OptionMap optionMap) throws IOException {
final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = createHalfDuplexPipe();
final StreamSourceChannel left = pipe.getLeftSide();
XnioExecutor leftExec = left.getReadThread();
final StreamSinkChannel right = pipe.getRightSide();
XnioExecutor rightExec = right.getWriteThread();
// not unsafe - http://youtrack.jetbrains.net/issue/IDEA-59290
//noinspection unchecked
leftExec.execute(ChannelListeners.getChannelListenerTask(left, sourceListener));
// not unsafe - http://youtrack.jetbrains.net/issue/IDEA-59290
//noinspection unchecked
rightExec.execute(ChannelListeners.getChannelListenerTask(right, sinkListener));
}
//==================================================
//
// Compression methods
//
//==================================================
/**
* Create a stream channel that decompresses the source data according to the configuration in the given option map.
*
* @param delegate the compressed channel
* @param options the configuration options for the channel
* @return a decompressed channel
* @throws IOException if the channel could not be constructed
*/
public StreamSourceChannel getInflatingChannel(final StreamSourceChannel delegate, OptionMap options) throws IOException {
final boolean nowrap;
switch (options.get(Options.COMPRESSION_TYPE, CompressionType.DEFLATE)) {
case DEFLATE: nowrap = false; break;
case GZIP: nowrap = true; break;
default: throw new IllegalArgumentException("Compression format not supported");
}
return getInflatingChannel(delegate, new Inflater(nowrap));
}
/**
* Create a stream channel that decompresses the source data according to the configuration in the given inflater.
*
* @param delegate the compressed channel
* @param inflater the inflater to use
* @return a decompressed channel
* @throws IOException if the channel could not be constructed
*/
protected StreamSourceChannel getInflatingChannel(final StreamSourceChannel delegate, final Inflater inflater) throws IOException {
final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = createHalfDuplexPipe();
final StreamSourceChannel source = pipe.getLeftSide();
final StreamSinkChannel sink = pipe.getRightSide();
execute(new Runnable() {
public void run() {
final InflaterInputStream inputStream = new InflaterInputStream(new ChannelInputStream(delegate), inflater);
final byte[] buf = new byte[16384];
final ByteBuffer byteBuffer = ByteBuffer.wrap(buf);
int res;
try {
for (;;) {
res = inputStream.read(buf);
if (res == -1) {
sink.shutdownWrites();
Channels.flushBlocking(sink);
return;
}
byteBuffer.limit(res);
Channels.writeBlocking(sink, byteBuffer);
}
} catch (IOException e) {
// todo: push this to the stream source somehow
} finally {
IoUtils.safeClose(inputStream);
IoUtils.safeClose(sink);
}
}
});
return source;
}
/**
* Create a stream channel that compresses to the destination according to the configuration in the given option map.
*
* @param delegate the channel to compress to
* @param options the configuration options for the channel
* @return a compressed channel
* @throws IOException if the channel could not be constructed
*/
public StreamSinkChannel getDeflatingChannel(final StreamSinkChannel delegate, final OptionMap options) throws IOException {
final int level = options.get(Options.COMPRESSION_LEVEL, -1);
final boolean nowrap;
switch (options.get(Options.COMPRESSION_TYPE, CompressionType.DEFLATE)) {
case DEFLATE: nowrap = false; break;
case GZIP: nowrap = true; break;
default: throw new IllegalArgumentException("Compression format not supported");
}
return getDeflatingChannel(delegate, new Deflater(level, nowrap));
}
/**
* Create a stream channel that compresses to the destination according to the configuration in the given inflater.
*
* @param delegate the channel to compress to
* @param deflater the deflater to use
* @return a compressed channel
* @throws IOException if the channel could not be constructed
*/
protected StreamSinkChannel getDeflatingChannel(final StreamSinkChannel delegate, final Deflater deflater) throws IOException {
final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = createHalfDuplexPipe();
final StreamSourceChannel source = pipe.getLeftSide();
final StreamSinkChannel sink = pipe.getRightSide();
execute(new Runnable() {
public void run() {
final DeflaterOutputStream outputStream = new DeflaterOutputStream(new ChannelOutputStream(delegate), deflater);
final byte[] buf = new byte[16384];
final ByteBuffer byteBuffer = ByteBuffer.wrap(buf);
int res;
try {
for (;;) {
if (Channels.readBlocking(source, byteBuffer) == -1) {
outputStream.close();
return;
}
outputStream.write(buf, 0, byteBuffer.position());
}
} catch (IOException e) {
// todo: push this to the stream source somehow
} finally {
IoUtils.safeClose(outputStream);
IoUtils.safeClose(source);
}
}
});
return sink;
}
/**
* Create a two-way stream pipe.
*
* @return the created pipe
* @throws IOException if the pipe could not be created
*/
public ChannelPipe<StreamChannel, StreamChannel> createFullDuplexPipe() throws IOException {
throw new UnsupportedOperationException("Create a full-duplex pipe");
}
/**
* Create a one-way stream pipe.
*
* @return the created pipe
* @throws IOException if the pipe could not be created
*/
public ChannelPipe<StreamSourceChannel, StreamSinkChannel> createHalfDuplexPipe() throws IOException {
throw new UnsupportedOperationException("Create a half-duplex pipe");
}
//==================================================
//
// State methods
//
//==================================================
/**
* Shut down this worker. This method returns immediately. Upon return worker shutdown will have
* commenced but not necessarily completed. When worker shutdown is complete, the termination task (if one was
* defined) will be executed.
*/
public abstract void shutdown();
/**
* Immediately terminate the worker. Any outstanding tasks are collected and returned in a list. Upon return
* worker shutdown will have commenced but not necessarily completed; however the worker will only complete its
* current tasks instead of completing all tasks.
*
* @return the list of outstanding tasks
*/
public abstract List<Runnable> shutdownNow();
/**
* Determine whether the worker has been shut down. Will return {@code true} once either shutdown method has
* been called.
*
* @return {@code true} the worker has been shut down
*/
public abstract boolean isShutdown();
/**
* Determine whether the worker has terminated. Will return {@code true} once all worker threads are exited
* (with the possible exception of the thread running the termination task, if any).
*
* @return {@code true} if the worker is terminated
*/
public abstract boolean isTerminated();
/**
* Wait for termination.
*
* @param timeout the amount of time to wait
* @param unit the unit of time
* @return {@code true} if termination completed before the timeout expired
* @throws InterruptedException if the operation was interrupted
*/
public abstract boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException;
/**
* Wait for termination.
*
* @throws InterruptedException if the operation was interrupted
*/
public abstract void awaitTermination() throws InterruptedException;
//==================================================
//
// Thread pool methods
//
//==================================================
/**
* Get the user task to run once termination is complete.
*
* @return the termination task
*/
protected Runnable getTerminationTask() {
return terminationTask;
}
/**
* Callback to indicate that the task thread pool has terminated.
*/
protected void taskPoolTerminated() {}
/**
* Initiate shutdown of the task thread pool. When all the tasks and threads have completed,
* the {@link #taskPoolTerminated()} method is called.
*/
protected void shutDownTaskPool() {
taskPool.shutdown();
}
/**
* Shut down the task thread pool immediately and return its pending tasks.
*
* @return the pending task list
*/
protected List<Runnable> shutDownTaskPoolNow() {
return taskPool.shutdownNow();
}
/**
* Execute a command in the task pool.
*
* @param command the command to run
*/
public void execute(final Runnable command) {
taskPool.execute(command);
}
//==================================================
//
// Configuration methods
//
//==================================================
private static Set<Option<?>> OPTIONS = Option.setBuilder()
.add(Options.WORKER_TASK_CORE_THREADS)
.add(Options.WORKER_TASK_MAX_THREADS)
.add(Options.WORKER_TASK_KEEPALIVE)
.create();
public boolean supportsOption(final Option<?> option) {
return OPTIONS.contains(option);
}
public <T> T getOption(final Option<T> option) throws IOException {
if (option.equals(Options.WORKER_TASK_CORE_THREADS)) {
return option.cast(Integer.valueOf(coreSize));
} else if (option.equals(Options.WORKER_TASK_MAX_THREADS)) {
return option.cast(Integer.valueOf(taskPool.getMaximumPoolSize()));
} else if (option.equals(Options.WORKER_TASK_KEEPALIVE)) {
return option.cast(Integer.valueOf((int) Math.min((long) Integer.MAX_VALUE, taskPool.getKeepAliveTime(TimeUnit.MILLISECONDS))));
} else {
return null;
}
}
public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException, IOException {
if (option.equals(Options.WORKER_TASK_CORE_THREADS)) {
return option.cast(Integer.valueOf(coreSizeUpdater.getAndSet(this, Options.WORKER_TASK_CORE_THREADS.cast(value).intValue())));
} else if (option.equals(Options.WORKER_TASK_MAX_THREADS)) {
final int old = taskPool.getMaximumPoolSize();
taskPool.setCorePoolSize(Options.WORKER_TASK_MAX_THREADS.cast(value).intValue());
taskPool.setMaximumPoolSize(Options.WORKER_TASK_MAX_THREADS.cast(value).intValue());
return option.cast(Integer.valueOf(old));
} else if (option.equals(Options.WORKER_TASK_KEEPALIVE)) {
final long old = taskPool.getKeepAliveTime(TimeUnit.MILLISECONDS);
taskPool.setKeepAliveTime(Options.WORKER_TASK_KEEPALIVE.cast(value).intValue(), TimeUnit.MILLISECONDS);
return option.cast(Integer.valueOf((int) Math.min((long) Integer.MAX_VALUE, old)));
} else {
return null;
}
}
//==================================================
//
// Migration methods
//
//==================================================
/**
* Migrate the given channel to this worker. Requires that the creating {@code Xnio} instance of the worker
* of the given channel matches this one.
*
* @param channel the channel
* @throws IOException if the source or destination worker is closed or the migration failed
* @throws IllegalArgumentException if the worker is incompatible
*/
public void migrate(CloseableChannel channel) throws IOException, IllegalArgumentException {
if (channel.getWorker().getXnio() != xnio) {
throw new IllegalArgumentException("Cannot migrate channel (XNIO providers do not match)");
}
doMigration(channel);
}
protected abstract void doMigration(CloseableChannel channel) throws IOException;
//==================================================
//
// Accessor methods
//
//==================================================
/**
* Get the XNIO provider which produced this worker.
*
* @return the XNIO provider
*/
public Xnio getXnio() {
return xnio;
}
/**
* Get the name of this worker.
*
* @return the name of the worker
*/
public String getName() {
return name;
}
final class TaskPool extends ThreadPoolExecutor {
TaskPool(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory, final RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
protected void terminated() {
taskPoolTerminated();
}
}
}
| api/src/main/java/org/xnio/XnioWorker.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2011 Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xnio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Set;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import org.xnio.channels.AcceptingChannel;
import org.xnio.channels.BoundChannel;
import org.xnio.channels.Channels;
import org.xnio.channels.CloseableChannel;
import org.xnio.channels.Configurable;
import org.xnio.channels.ConnectedMessageChannel;
import org.xnio.channels.ConnectedStreamChannel;
import org.xnio.channels.MulticastMessageChannel;
import org.xnio.channels.StreamChannel;
import org.xnio.channels.StreamSinkChannel;
import org.xnio.channels.StreamSourceChannel;
import org.xnio.streams.ChannelInputStream;
import org.xnio.streams.ChannelOutputStream;
import static org.xnio.Messages.msg;
/**
* A worker for I/O channel notification.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*
* @since 3.0
*/
@SuppressWarnings("unused")
public abstract class XnioWorker extends AbstractExecutorService implements Configurable, ExecutorService {
private final Xnio xnio;
private final TaskPool taskPool;
private final String name;
private final Runnable terminationTask;
private volatile int taskSeq;
private volatile int coreSize;
private static final AtomicIntegerFieldUpdater<XnioWorker> taskSeqUpdater = AtomicIntegerFieldUpdater.newUpdater(XnioWorker.class, "taskSeq");
private static final AtomicIntegerFieldUpdater<XnioWorker> coreSizeUpdater = AtomicIntegerFieldUpdater.newUpdater(XnioWorker.class, "coreSize");
private static final AtomicInteger seq = new AtomicInteger(1);
private int getNextSeq() {
return taskSeqUpdater.incrementAndGet(this);
}
/**
* Construct a new instance. Intended to be called only from implementations. To construct an XNIO worker,
* use the {@link Xnio#createWorker(OptionMap)} method.
*
* @param xnio the XNIO provider which produced this worker instance
* @param threadGroup the thread group for worker threads
* @param optionMap the option map to use to configure this worker
* @param terminationTask
*/
protected XnioWorker(final Xnio xnio, final ThreadGroup threadGroup, final OptionMap optionMap, final Runnable terminationTask) {
this.xnio = xnio;
this.terminationTask = terminationTask;
String workerName = optionMap.get(Options.WORKER_NAME);
if (workerName == null) {
workerName = "XNIO-" + seq.getAndIncrement();
}
name = workerName;
BlockingQueue<Runnable> taskQueue;
try {
taskQueue = new LinkedTransferQueue<Runnable>();
} catch (Throwable t) {
taskQueue = new LinkedBlockingQueue<Runnable>();
}
this.coreSize = optionMap.get(Options.WORKER_TASK_CORE_THREADS, 4);
final boolean markThreadAsDaemon = optionMap.get(Options.THREAD_DAEMON, false);
taskPool = new TaskPool(
optionMap.get(Options.WORKER_TASK_MAX_THREADS, 16), // ignore core threads setting, always fill to max
optionMap.get(Options.WORKER_TASK_MAX_THREADS, 16),
optionMap.get(Options.WORKER_TASK_KEEPALIVE, 60), TimeUnit.MILLISECONDS,
taskQueue,
new ThreadFactory() {
public Thread newThread(final Runnable r) {
final Thread taskThread = new Thread(threadGroup, r, name + " task-" + getNextSeq(), optionMap.get(Options.STACK_SIZE, 0L));
// Mark the thread as daemon if the Options.THREAD_DAEMON has been set
if (markThreadAsDaemon) {
taskThread.setDaemon(true);
}
return taskThread;
}
}, new ThreadPoolExecutor.AbortPolicy());
}
//==================================================
//
// Stream methods
//
//==================================================
// Servers
/**
* Create a stream server, for TCP or UNIX domain servers. The type of server is determined by the bind address.
*
* @param bindAddress the address to bind to
* @param acceptListener the initial accept listener
* @param optionMap the initial configuration for the server
* @return the acceptor
* @throws IOException if the server could not be created
*/
public AcceptingChannel<? extends ConnectedStreamChannel> createStreamServer(SocketAddress bindAddress, ChannelListener<? super AcceptingChannel<ConnectedStreamChannel>> acceptListener, OptionMap optionMap) throws IOException {
if (bindAddress == null) {
throw msg.nullParameter("bindAddress");
}
if (bindAddress instanceof InetSocketAddress) {
return createTcpServer((InetSocketAddress) bindAddress, acceptListener, optionMap);
} else if (bindAddress instanceof LocalSocketAddress) {
return createLocalStreamServer((LocalSocketAddress) bindAddress, acceptListener, optionMap);
} else {
throw msg.badSockType(bindAddress.getClass());
}
}
/**
* Implementation helper method to create a TCP stream server.
*
* @param bindAddress the address to bind to
* @param acceptListener the initial accept listener
* @param optionMap the initial configuration for the server
* @return the acceptor
* @throws IOException if the server could not be created
*/
protected AcceptingChannel<? extends ConnectedStreamChannel> createTcpServer(InetSocketAddress bindAddress, ChannelListener<? super AcceptingChannel<ConnectedStreamChannel>> acceptListener, OptionMap optionMap) throws IOException {
throw new UnsupportedOperationException("TCP server");
}
/**
* Implementation helper method to create a UNIX domain stream server.
*
* @param bindAddress the address to bind to
* @param acceptListener the initial accept listener
* @param optionMap the initial configuration for the server
* @return the acceptor
* @throws IOException if the server could not be created
*/
protected AcceptingChannel<? extends ConnectedStreamChannel> createLocalStreamServer(LocalSocketAddress bindAddress, ChannelListener<? super AcceptingChannel<ConnectedStreamChannel>> acceptListener, OptionMap optionMap) throws IOException {
throw new UnsupportedOperationException("UNIX stream server");
}
// Connectors
/**
* Connect to a remote stream server. The protocol family is determined by the type of the socket address given.
*
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
public IoFuture<ConnectedStreamChannel> connectStream(SocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, OptionMap optionMap) {
if (destination == null) {
throw msg.nullParameter("destination");
}
if (destination instanceof InetSocketAddress) {
return connectTcpStream(Xnio.ANY_INET_ADDRESS, (InetSocketAddress) destination, openListener, null, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return connectLocalStream(Xnio.ANY_LOCAL_ADDRESS, (LocalSocketAddress) destination, openListener, null, optionMap);
} else {
throw msg.badSockType(destination.getClass());
}
}
/**
* Connect to a remote stream server. The protocol family is determined by the type of the socket address given.
*
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
public IoFuture<ConnectedStreamChannel> connectStream(SocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (destination == null) {
throw msg.nullParameter("destination");
}
if (destination instanceof InetSocketAddress) {
return connectTcpStream(Xnio.ANY_INET_ADDRESS, (InetSocketAddress) destination, openListener, bindListener, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return connectLocalStream(Xnio.ANY_LOCAL_ADDRESS, (LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw msg.badSockType(destination.getClass());
}
}
/**
* Connect to a remote stream server. The protocol family is determined by the type of the socket addresses given
* (which must match).
*
* @param bindAddress the local address to bind to
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
public IoFuture<ConnectedStreamChannel> connectStream(SocketAddress bindAddress, SocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (bindAddress == null) {
throw msg.nullParameter("bindAddress");
}
if (destination == null) {
throw msg.nullParameter("destination");
}
if (bindAddress.getClass() != destination.getClass()) {
throw msg.mismatchSockType(bindAddress.getClass(), destination.getClass());
}
if (destination instanceof InetSocketAddress) {
return connectTcpStream((InetSocketAddress) bindAddress, (InetSocketAddress) destination, openListener, bindListener, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return connectLocalStream((LocalSocketAddress) bindAddress, (LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw msg.badSockType(destination.getClass());
}
}
/**
* Implementation helper method to connect to a TCP server.
*
* @param bindAddress the bind address
* @param destinationAddress the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map @return the future result of this operation
* @return the future result of this operation
*/
protected IoFuture<ConnectedStreamChannel> connectTcpStream(InetSocketAddress bindAddress, InetSocketAddress destinationAddress, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Connect to TCP server");
}
/**
* Implementation helper method to connect to a local (UNIX domain) server.
*
* @param bindAddress the bind address
* @param destinationAddress the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
protected IoFuture<ConnectedStreamChannel> connectLocalStream(LocalSocketAddress bindAddress, LocalSocketAddress destinationAddress, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Connect to local stream server");
}
// Acceptors
/**
* Accept a stream connection at a destination address. If a wildcard address is specified, then a destination address
* is chosen in a manner specific to the OS and/or channel type.
*
* @param destination the destination (bind) address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the acceptor is bound, or {@code null} for none
* @param optionMap the option map
* @return the future connection
*/
public IoFuture<ConnectedStreamChannel> acceptStream(SocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (destination == null) {
throw msg.nullParameter("destination");
}
if (destination instanceof InetSocketAddress) {
return acceptTcpStream((InetSocketAddress) destination, openListener, bindListener, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return acceptLocalStream((LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw msg.badSockType(destination.getClass());
}
}
/**
* Implementation helper method to accept a local (UNIX domain) stream connection.
*
* @param destination the destination (bind) address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the acceptor is bound, or {@code null} for none
* @param optionMap the option map
*
* @return the future connection
*/
protected IoFuture<ConnectedStreamChannel> acceptLocalStream(LocalSocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Accept a local stream connection");
}
/**
* Implementation helper method to accept a TCP connection.
*
* @param destination the destination (bind) address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the acceptor is bound, or {@code null} for none
* @param optionMap the option map
*
* @return the future connection
*/
protected IoFuture<ConnectedStreamChannel> acceptTcpStream(InetSocketAddress destination, ChannelListener<? super ConnectedStreamChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Accept a TCP connection");
}
//==================================================
//
// Message (datagram) channel methods
//
//==================================================
/**
* Connect to a remote stream server. The protocol family is determined by the type of the socket address given.
*
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
public IoFuture<ConnectedMessageChannel> connectDatagram(SocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (destination == null) {
throw msg.nullParameter("destination");
}
if (destination instanceof InetSocketAddress) {
return connectUdpDatagram(Xnio.ANY_INET_ADDRESS, (InetSocketAddress) destination, openListener, bindListener, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return connectLocalDatagram(Xnio.ANY_LOCAL_ADDRESS, (LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw msg.badSockType(destination.getClass());
}
}
/**
* Connect to a remote datagram server. The protocol family is determined by the type of the socket addresses given
* (which must match).
*
* @param bindAddress the local address to bind to
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
public IoFuture<ConnectedMessageChannel> connectDatagram(SocketAddress bindAddress, SocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (bindAddress == null) {
throw new IllegalArgumentException("bindAddress is null");
}
if (destination == null) {
throw new IllegalArgumentException("destination is null");
}
if (bindAddress.getClass() != destination.getClass()) {
throw new IllegalArgumentException("Bind address " + bindAddress.getClass() + " is not the same type as destination address " + destination.getClass());
}
if (destination instanceof InetSocketAddress) {
return connectUdpDatagram((InetSocketAddress) bindAddress, (InetSocketAddress) destination, openListener, bindListener, optionMap);
} else if (destination instanceof LocalSocketAddress) {
return connectLocalDatagram((LocalSocketAddress) bindAddress, (LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw new UnsupportedOperationException("Connect to server with socket address " + destination.getClass());
}
}
/**
* Implementation helper method to connect to a UDP server.
*
* @param bindAddress the bind address
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
protected IoFuture<ConnectedMessageChannel> connectUdpDatagram(InetSocketAddress bindAddress, InetSocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Connect to UDP server");
}
/**
* Implementation helper method to connect to a local (UNIX domain) datagram server.
*
* @param bindAddress the bind address
* @param destination the destination address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the channel is bound, or {@code null} for none
* @param optionMap the option map
* @return the future result of this operation
*/
protected IoFuture<ConnectedMessageChannel> connectLocalDatagram(LocalSocketAddress bindAddress, LocalSocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Connect to local datagram server");
}
// Acceptors
/**
* Accept a message connection at a destination address. If a wildcard address is specified, then a destination address
* is chosen in a manner specific to the OS and/or channel type.
*
* @param destination the destination (bind) address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the acceptor is bound, or {@code null} for none
* @param optionMap the option map
* @return the future connection
*/
public IoFuture<ConnectedMessageChannel> acceptDatagram(SocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
if (destination == null) {
throw new IllegalArgumentException("destination is null");
}
if (destination instanceof LocalSocketAddress) {
return acceptLocalDatagram((LocalSocketAddress) destination, openListener, bindListener, optionMap);
} else {
throw new UnsupportedOperationException("Accept a connection to socket address " + destination.getClass());
}
}
/**
* Implementation helper method to accept a local (UNIX domain) datagram connection.
*
* @param destination the destination (bind) address
* @param openListener the listener which will be notified when the channel is open, or {@code null} for none
* @param bindListener the listener which will be notified when the acceptor is bound, or {@code null} for none
* @param optionMap the option map
*
* @return the future connection
*/
protected IoFuture<ConnectedMessageChannel> acceptLocalDatagram(LocalSocketAddress destination, ChannelListener<? super ConnectedMessageChannel> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Accept a local message connection");
}
//==================================================
//
// UDP methods
//
//==================================================
/**
* Create a UDP server. The UDP server can be configured to be multicast-capable; this should only be
* done if multicast is needed, since some providers have a performance penalty associated with multicast.
* The provider's default executor will be used to execute listener methods.
*
* @param bindAddress the bind address
* @param bindListener the initial open-connection listener
* @param optionMap the initial configuration for the server
* @return the UDP server channel
* @throws IOException if the server could not be created
*
* @since 3.0
*/
public MulticastMessageChannel createUdpServer(InetSocketAddress bindAddress, ChannelListener<? super MulticastMessageChannel> bindListener, OptionMap optionMap) throws IOException {
throw new UnsupportedOperationException("UDP Server");
}
/**
* Create a UDP server. The UDP server can be configured to be multicast-capable; this should only be
* done if multicast is needed, since some providers have a performance penalty associated with multicast.
* The provider's default executor will be used to execute listener methods.
*
* @param bindAddress the bind address
* @param optionMap the initial configuration for the server
* @return the UDP server channel
* @throws IOException if the server could not be created
*
* @since 3.0
*/
public MulticastMessageChannel createUdpServer(InetSocketAddress bindAddress, OptionMap optionMap) throws IOException {
return createUdpServer(bindAddress, ChannelListeners.nullChannelListener(), optionMap);
}
//==================================================
//
// Stream pipe methods
//
//==================================================
/**
* Open a bidirectional stream pipe.
*
* @param leftOpenListener the left-hand open listener
* @param rightOpenListener the right-hand open listener
* @param optionMap the pipe channel configuration
* @throws IOException if the pipe could not be created
* @deprecated Users should prefer the simpler {@link #createFullDuplexPipe()} instead.
*/
@Deprecated
public void createPipe(ChannelListener<? super StreamChannel> leftOpenListener, ChannelListener<? super StreamChannel> rightOpenListener, final OptionMap optionMap) throws IOException {
final ChannelPipe<StreamChannel, StreamChannel> pipe = createFullDuplexPipe();
final boolean establishWriting = optionMap.get(Options.WORKER_ESTABLISH_WRITING, false);
final StreamChannel left = pipe.getLeftSide();
XnioExecutor leftExec = establishWriting ? left.getWriteThread() : left.getReadThread();
final StreamChannel right = pipe.getRightSide();
XnioExecutor rightExec = establishWriting ? right.getWriteThread() : right.getReadThread();
// not unsafe - http://youtrack.jetbrains.net/issue/IDEA-59290
//noinspection unchecked
leftExec.execute(ChannelListeners.getChannelListenerTask(left, leftOpenListener));
// not unsafe - http://youtrack.jetbrains.net/issue/IDEA-59290
//noinspection unchecked
rightExec.execute(ChannelListeners.getChannelListenerTask(right, rightOpenListener));
}
/**
* Open a unidirectional stream pipe.
*
* @param sourceListener the source open listener
* @param sinkListener the sink open listener
* @param optionMap the pipe channel configuration
* @throws IOException if the pipe could not be created
* @deprecated Users should prefer the simpler {@link #createHalfDuplexPipe()} instead.
*/
@Deprecated
public void createOneWayPipe(ChannelListener<? super StreamSourceChannel> sourceListener, ChannelListener<? super StreamSinkChannel> sinkListener, final OptionMap optionMap) throws IOException {
final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = createHalfDuplexPipe();
final StreamSourceChannel left = pipe.getLeftSide();
XnioExecutor leftExec = left.getReadThread();
final StreamSinkChannel right = pipe.getRightSide();
XnioExecutor rightExec = right.getWriteThread();
// not unsafe - http://youtrack.jetbrains.net/issue/IDEA-59290
//noinspection unchecked
leftExec.execute(ChannelListeners.getChannelListenerTask(left, sourceListener));
// not unsafe - http://youtrack.jetbrains.net/issue/IDEA-59290
//noinspection unchecked
rightExec.execute(ChannelListeners.getChannelListenerTask(right, sinkListener));
}
//==================================================
//
// Compression methods
//
//==================================================
/**
* Create a stream channel that decompresses the source data according to the configuration in the given option map.
*
* @param delegate the compressed channel
* @param options the configuration options for the channel
* @return a decompressed channel
* @throws IOException if the channel could not be constructed
*/
public StreamSourceChannel getInflatingChannel(final StreamSourceChannel delegate, OptionMap options) throws IOException {
final boolean nowrap;
switch (options.get(Options.COMPRESSION_TYPE, CompressionType.DEFLATE)) {
case DEFLATE: nowrap = false; break;
case GZIP: nowrap = true; break;
default: throw new IllegalArgumentException("Compression format not supported");
}
return getInflatingChannel(delegate, new Inflater(nowrap));
}
/**
* Create a stream channel that decompresses the source data according to the configuration in the given inflater.
*
* @param delegate the compressed channel
* @param inflater the inflater to use
* @return a decompressed channel
* @throws IOException if the channel could not be constructed
*/
protected StreamSourceChannel getInflatingChannel(final StreamSourceChannel delegate, final Inflater inflater) throws IOException {
final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = createHalfDuplexPipe();
final StreamSourceChannel source = pipe.getLeftSide();
final StreamSinkChannel sink = pipe.getRightSide();
execute(new Runnable() {
public void run() {
final InflaterInputStream inputStream = new InflaterInputStream(new ChannelInputStream(delegate), inflater);
final byte[] buf = new byte[16384];
final ByteBuffer byteBuffer = ByteBuffer.wrap(buf);
int res;
try {
for (;;) {
res = inputStream.read(buf);
if (res == -1) {
sink.shutdownWrites();
Channels.flushBlocking(sink);
return;
}
byteBuffer.limit(res);
Channels.writeBlocking(sink, byteBuffer);
}
} catch (IOException e) {
// todo: push this to the stream source somehow
} finally {
IoUtils.safeClose(inputStream);
IoUtils.safeClose(sink);
}
}
});
return source;
}
/**
* Create a stream channel that compresses to the destination according to the configuration in the given option map.
*
* @param delegate the channel to compress to
* @param options the configuration options for the channel
* @return a compressed channel
* @throws IOException if the channel could not be constructed
*/
public StreamSinkChannel getDeflatingChannel(final StreamSinkChannel delegate, final OptionMap options) throws IOException {
final int level = options.get(Options.COMPRESSION_LEVEL, -1);
final boolean nowrap;
switch (options.get(Options.COMPRESSION_TYPE, CompressionType.DEFLATE)) {
case DEFLATE: nowrap = false; break;
case GZIP: nowrap = true; break;
default: throw new IllegalArgumentException("Compression format not supported");
}
return getDeflatingChannel(delegate, new Deflater(level, nowrap));
}
/**
* Create a stream channel that compresses to the destination according to the configuration in the given inflater.
*
* @param delegate the channel to compress to
* @param deflater the deflater to use
* @return a compressed channel
* @throws IOException if the channel could not be constructed
*/
protected StreamSinkChannel getDeflatingChannel(final StreamSinkChannel delegate, final Deflater deflater) throws IOException {
final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = createHalfDuplexPipe();
final StreamSourceChannel source = pipe.getLeftSide();
final StreamSinkChannel sink = pipe.getRightSide();
execute(new Runnable() {
public void run() {
final DeflaterOutputStream outputStream = new DeflaterOutputStream(new ChannelOutputStream(delegate), deflater);
final byte[] buf = new byte[16384];
final ByteBuffer byteBuffer = ByteBuffer.wrap(buf);
int res;
try {
for (;;) {
if (Channels.readBlocking(source, byteBuffer) == -1) {
outputStream.close();
return;
}
outputStream.write(buf, 0, byteBuffer.position());
}
} catch (IOException e) {
// todo: push this to the stream source somehow
} finally {
IoUtils.safeClose(outputStream);
IoUtils.safeClose(source);
}
}
});
return sink;
}
/**
* Create a two-way stream pipe.
*
* @return the created pipe
* @throws IOException if the pipe could not be created
*/
public ChannelPipe<StreamChannel, StreamChannel> createFullDuplexPipe() throws IOException {
throw new UnsupportedOperationException("Create a full-duplex pipe");
}
/**
* Create a one-way stream pipe.
*
* @return the created pipe
* @throws IOException if the pipe could not be created
*/
public ChannelPipe<StreamSourceChannel, StreamSinkChannel> createHalfDuplexPipe() throws IOException {
throw new UnsupportedOperationException("Create a half-duplex pipe");
}
//==================================================
//
// State methods
//
//==================================================
/**
* Shut down this worker. This method returns immediately. Upon return worker shutdown will have
* commenced but not necessarily completed. When worker shutdown is complete, the termination task (if one was
* defined) will be executed.
*/
public abstract void shutdown();
/**
* Immediately terminate the worker. Any outstanding tasks are collected and returned in a list. Upon return
* worker shutdown will have commenced but not necessarily completed; however the worker will only complete its
* current tasks instead of completing all tasks.
*
* @return the list of outstanding tasks
*/
public abstract List<Runnable> shutdownNow();
/**
* Determine whether the worker has been shut down. Will return {@code true} once either shutdown method has
* been called.
*
* @return {@code true} the worker has been shut down
*/
public abstract boolean isShutdown();
/**
* Determine whether the worker has terminated. Will return {@code true} once all worker threads are exited
* (with the possible exception of the thread running the termination task, if any).
*
* @return {@code true} if the worker is terminated
*/
public abstract boolean isTerminated();
/**
* Wait for termination.
*
* @param timeout the amount of time to wait
* @param unit the unit of time
* @return {@code true} if termination completed before the timeout expired
* @throws InterruptedException if the operation was interrupted
*/
public abstract boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException;
/**
* Wait for termination.
*
* @throws InterruptedException if the operation was interrupted
*/
public abstract void awaitTermination() throws InterruptedException;
//==================================================
//
// Thread pool methods
//
//==================================================
/**
* Get the user task to run once termination is complete.
*
* @return the termination task
*/
protected Runnable getTerminationTask() {
return terminationTask;
}
/**
* Callback to indicate that the task thread pool has terminated.
*/
protected void taskPoolTerminated() {}
/**
* Initiate shutdown of the task thread pool. When all the tasks and threads have completed,
* the {@link #taskPoolTerminated()} method is called.
*/
protected void shutDownTaskPool() {
taskPool.shutdown();
}
/**
* Shut down the task thread pool immediately and return its pending tasks.
*
* @return the pending task list
*/
protected List<Runnable> shutDownTaskPoolNow() {
return taskPool.shutdownNow();
}
/**
* Execute a command in the task pool.
*
* @param command the command to run
*/
public void execute(final Runnable command) {
taskPool.execute(command);
}
//==================================================
//
// Configuration methods
//
//==================================================
private static Set<Option<?>> OPTIONS = Option.setBuilder()
.add(Options.WORKER_TASK_CORE_THREADS)
.add(Options.WORKER_TASK_MAX_THREADS)
.add(Options.WORKER_TASK_KEEPALIVE)
.create();
public boolean supportsOption(final Option<?> option) {
return OPTIONS.contains(option);
}
public <T> T getOption(final Option<T> option) throws IOException {
if (option.equals(Options.WORKER_TASK_CORE_THREADS)) {
return option.cast(Integer.valueOf(coreSize));
} else if (option.equals(Options.WORKER_TASK_MAX_THREADS)) {
return option.cast(Integer.valueOf(taskPool.getMaximumPoolSize()));
} else if (option.equals(Options.WORKER_TASK_KEEPALIVE)) {
return option.cast(Integer.valueOf((int) Math.min((long) Integer.MAX_VALUE, taskPool.getKeepAliveTime(TimeUnit.MILLISECONDS))));
} else {
return null;
}
}
public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException, IOException {
if (option.equals(Options.WORKER_TASK_CORE_THREADS)) {
return option.cast(Integer.valueOf(coreSizeUpdater.getAndSet(this, Options.WORKER_TASK_CORE_THREADS.cast(value).intValue())));
} else if (option.equals(Options.WORKER_TASK_MAX_THREADS)) {
final int old = taskPool.getMaximumPoolSize();
taskPool.setCorePoolSize(Options.WORKER_TASK_MAX_THREADS.cast(value).intValue());
taskPool.setMaximumPoolSize(Options.WORKER_TASK_MAX_THREADS.cast(value).intValue());
return option.cast(Integer.valueOf(old));
} else if (option.equals(Options.WORKER_TASK_KEEPALIVE)) {
final long old = taskPool.getKeepAliveTime(TimeUnit.MILLISECONDS);
taskPool.setKeepAliveTime(Options.WORKER_TASK_KEEPALIVE.cast(value).intValue(), TimeUnit.MILLISECONDS);
return option.cast(Integer.valueOf((int) Math.min((long) Integer.MAX_VALUE, old)));
} else {
return null;
}
}
//==================================================
//
// Migration methods
//
//==================================================
/**
* Migrate the given channel to this worker. Requires that the creating {@code Xnio} instance of the worker
* of the given channel matches this one.
*
* @param channel the channel
* @throws IOException if the source or destination worker is closed or the migration failed
* @throws IllegalArgumentException if the worker is incompatible
*/
public void migrate(CloseableChannel channel) throws IOException, IllegalArgumentException {
if (channel.getWorker().getXnio() != xnio) {
throw new IllegalArgumentException("Cannot migrate channel (XNIO providers do not match)");
}
doMigration(channel);
}
protected abstract void doMigration(CloseableChannel channel) throws IOException;
//==================================================
//
// Accessor methods
//
//==================================================
/**
* Get the XNIO provider which produced this worker.
*
* @return the XNIO provider
*/
public Xnio getXnio() {
return xnio;
}
/**
* Get the name of this worker.
*
* @return the name of the worker
*/
public String getName() {
return name;
}
final class TaskPool extends ThreadPoolExecutor {
TaskPool(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory, final RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
protected void terminated() {
taskPoolTerminated();
}
}
}
| LinkedTransferQueue uses Thread.yield(), which is a big piece of shit. Remove this to get rid of stinky performance regression
| api/src/main/java/org/xnio/XnioWorker.java | LinkedTransferQueue uses Thread.yield(), which is a big piece of shit. Remove this to get rid of stinky performance regression | <ide><path>pi/src/main/java/org/xnio/XnioWorker.java
<ide> import java.util.concurrent.BlockingQueue;
<ide> import java.util.concurrent.ExecutorService;
<ide> import java.util.concurrent.LinkedBlockingQueue;
<del>import java.util.concurrent.LinkedTransferQueue;
<ide> import java.util.concurrent.RejectedExecutionHandler;
<ide> import java.util.concurrent.ThreadFactory;
<ide> import java.util.concurrent.ThreadPoolExecutor;
<ide> workerName = "XNIO-" + seq.getAndIncrement();
<ide> }
<ide> name = workerName;
<del> BlockingQueue<Runnable> taskQueue;
<del> try {
<del> taskQueue = new LinkedTransferQueue<Runnable>();
<del> } catch (Throwable t) {
<del> taskQueue = new LinkedBlockingQueue<Runnable>();
<del> }
<add> BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>();
<ide> this.coreSize = optionMap.get(Options.WORKER_TASK_CORE_THREADS, 4);
<ide> final boolean markThreadAsDaemon = optionMap.get(Options.THREAD_DAEMON, false);
<ide> taskPool = new TaskPool( |
|
Java | bsd-3-clause | 5a4a417b48e301f442253171859f1d2e9bdd3ad3 | 0 | jxson/reader,jxson/reader,jxson/reader,vanadium/reader,vanadium/reader,jxson/reader,vanadium/reader | // Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package io.v.android.apps.reader.db;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import io.v.android.apps.reader.model.DeviceInfoFactory;
import io.v.android.apps.reader.model.IdFactory;
import io.v.android.apps.reader.model.Listener;
import io.v.android.apps.reader.vdl.Device;
import io.v.android.apps.reader.vdl.DeviceSet;
import io.v.android.apps.reader.vdl.File;
import io.v.android.libs.security.BlessingsManager;
import io.v.android.v23.V;
import io.v.android.v23.services.blessing.BlessingCreationException;
import io.v.android.v23.services.blessing.BlessingService;
import io.v.impl.google.naming.NamingUtil;
import io.v.impl.google.services.syncbase.SyncbaseServer;
import io.v.v23.VIterable;
import io.v.v23.context.CancelableVContext;
import io.v.v23.context.VContext;
import io.v.v23.rpc.Server;
import io.v.v23.security.BlessingPattern;
import io.v.v23.security.Blessings;
import io.v.v23.security.VCertificate;
import io.v.v23.security.VPrincipal;
import io.v.v23.security.VSecurity;
import io.v.v23.security.access.AccessList;
import io.v.v23.security.access.Constants;
import io.v.v23.security.access.Permissions;
import io.v.v23.services.syncbase.nosql.BatchOptions;
import io.v.v23.services.syncbase.nosql.BlobRef;
import io.v.v23.services.syncbase.nosql.KeyValue;
import io.v.v23.services.syncbase.nosql.SyncgroupMemberInfo;
import io.v.v23.services.syncbase.nosql.SyncgroupSpec;
import io.v.v23.services.syncbase.nosql.TableRow;
import io.v.v23.services.watch.ResumeMarker;
import io.v.v23.syncbase.Syncbase;
import io.v.v23.syncbase.SyncbaseApp;
import io.v.v23.syncbase.SyncbaseService;
import io.v.v23.syncbase.nosql.BatchDatabase;
import io.v.v23.syncbase.nosql.BlobReader;
import io.v.v23.syncbase.nosql.BlobWriter;
import io.v.v23.syncbase.nosql.Database;
import io.v.v23.syncbase.nosql.RowRange;
import io.v.v23.syncbase.nosql.Syncgroup;
import io.v.v23.syncbase.nosql.Table;
import io.v.v23.syncbase.nosql.WatchChange;
import io.v.v23.verror.ExistException;
import io.v.v23.verror.VException;
import io.v.v23.vom.VomUtil;
/**
* A class representing the syncbase instance.
*/
public class SyncbaseDB implements DB {
private static final String TAG = SyncbaseDB.class.getSimpleName();
/**
* The intent result code for when we get blessings from the account manager.
* The value must not conflict with any other blessing result codes.
*/
private static final int BLESSING_REQUEST = 200;
private static final String GLOBAL_MOUNT_TABLE = "/ns.dev.v.io:8101";
private static final String SYNCBASE_APP = "reader";
private static final String SYNCBASE_DB = "db";
private static final String TABLE_FILES = "files";
private static final String TABLE_DEVICES = "devices";
private static final String TABLE_DEVICE_SETS = "deviceSets";
private Permissions mPermissions;
private Context mContext;
private VContext mVContext;
private SyncbaseHierarchy mLocalSB;
private boolean mInitialized;
private String mUsername;
private String mSyncgroupName;
SyncbaseDB(Context context) {
mContext = context;
}
@Override
public void init(Activity activity) {
if (isInitialized()) {
// Already initialized.
return;
}
if (mVContext == null) {
mVContext = V.init(mContext);
try {
mVContext = V.withListenSpec(
mVContext, V.getListenSpec(mVContext).withProxy("proxy"));
} catch (VException e) {
handleError("Couldn't setup vanadium proxy: " + e.getMessage());
}
}
AccessList acl = new AccessList(
ImmutableList.of(new BlessingPattern("...")), ImmutableList.<String>of());
mPermissions = new Permissions(ImmutableMap.of(
Constants.READ.getValue(), acl,
Constants.WRITE.getValue(), acl,
Constants.ADMIN.getValue(), acl,
Constants.RESOLVE.getValue(), acl,
Constants.DEBUG.getValue(), acl));
getBlessings(activity);
}
@Override
public boolean isInitialized() {
return mInitialized;
}
private void getBlessings(Activity activity) {
Blessings blessings = null;
try {
// See if there are blessings stored in shared preferences.
blessings = BlessingsManager.getBlessings(mContext);
} catch (VException e) {
handleError("Error getting blessings from shared preferences " + e.getMessage());
}
if (blessings == null) {
// Request new blessings from the account manager via an intent. This intent
// will call back to onActivityResult() which will continue with
// configurePrincipal().
refreshBlessings(activity);
return;
}
configurePrincipal(blessings);
}
private void refreshBlessings(Activity activity) {
Intent intent = BlessingService.newBlessingIntent(mContext);
activity.startActivityForResult(intent, BLESSING_REQUEST);
}
@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BLESSING_REQUEST) {
try {
byte[] blessingsVom = BlessingService.extractBlessingReply(resultCode, data);
Blessings blessings = (Blessings) VomUtil.decode(blessingsVom, Blessings.class);
BlessingsManager.addBlessings(mContext, blessings);
Toast.makeText(mContext, "Success", Toast.LENGTH_SHORT).show();
configurePrincipal(blessings);
} catch (BlessingCreationException e) {
handleError("Couldn't create blessing: " + e.getMessage());
} catch (VException e) {
handleError("Couldn't derive blessing: " + e.getMessage());
}
return true;
}
return false;
}
private void configurePrincipal(Blessings blessings) {
try {
VPrincipal p = V.getPrincipal(mVContext);
p.blessingStore().setDefaultBlessings(blessings);
p.blessingStore().set(blessings, new BlessingPattern("..."));
VSecurity.addToRoots(p, blessings);
// "<user_email>/android"
mUsername = mountNameFromBlessings(blessings);
} catch (VException e) {
handleError(String.format(
"Couldn't set local blessing %s: %s", blessings, e.getMessage()));
return;
}
setupLocalSyncbase();
}
private void setupLocalSyncbase() {
// "users/<user_email>/android/reader/<device_id>/syncbase"
final String syncbaseName = NamingUtil.join(
"users",
mUsername,
"reader",
DeviceInfoFactory.getDevice(mContext).getId(),
"syncbase"
);
Log.i(TAG, "SyncbaseName: " + syncbaseName);
// Prepare the syncbase storage directory.
java.io.File storageDir = new java.io.File(mContext.getFilesDir(), "syncbase");
storageDir.mkdirs();
try {
mVContext = SyncbaseServer.withNewServer(
mVContext,
new SyncbaseServer.Params()
.withName(syncbaseName)
.withPermissions(mPermissions)
.withStorageRootDir(storageDir.getAbsolutePath()));
} catch (SyncbaseServer.StartException e) {
handleError("Couldn't start syncbase server");
return;
}
try {
Server syncbaseServer = V.getServer(mVContext);
String serverName = "/" + syncbaseServer.getStatus().getEndpoints()[0];
Log.i(TAG, "Local Syncbase ServerName: " + serverName);
mLocalSB = createHierarchy(serverName, "local");
setupCloudSyncbase();
} catch (VException e) {
handleError("Couldn't setup syncbase service: " + e.getMessage());
}
}
/**
* This method assumes that there is a separate cloudsync instance running at:
* "users/[user_email]/reader/cloudsync"
*/
private void setupCloudSyncbase() {
try {
// "users/<user_email>/reader/cloudsync"
String cloudsyncName = NamingUtil.join(
"users",
NamingUtil.trimSuffix(mUsername, "android"),
"reader/cloudsync"
);
SyncbaseHierarchy cloudSB = createHierarchy(cloudsyncName, "cloud");
createSyncgroup(cloudSB.db);
} catch (VException e) {
handleError("Couldn't setup cloudsync: " + e.getMessage());
}
}
/**
* Creates a syncgroup at cloudsync with the following name:
* "users/[user_email]/reader/cloudsync/%%sync/cloudsync"
*/
private void createSyncgroup(Database db) {
mSyncgroupName = NamingUtil.join(
"users",
NamingUtil.trimSuffix(mUsername, "android"),
"reader/cloudsync/%%sync/cloudsync"
);
Syncgroup group = db.getSyncgroup(mSyncgroupName);
List<TableRow> prefixes = ImmutableList.of(
new TableRow(TABLE_FILES, ""),
new TableRow(TABLE_DEVICES, ""),
new TableRow(TABLE_DEVICE_SETS, "")
);
List<String> mountTables = ImmutableList.of(
NamingUtil.join(
GLOBAL_MOUNT_TABLE,
"users",
NamingUtil.trimSuffix(mUsername, "android"),
"reader/rendezvous"
)
);
SyncgroupSpec spec = new SyncgroupSpec(
"reader syncgroup",
mPermissions,
prefixes,
mountTables,
false
);
try {
group.create(mVContext, spec, new SyncgroupMemberInfo());
Log.i(TAG, "Syncgroup is created successfully.");
} catch (ExistException e) {
Log.i(TAG, "Syncgroup already exists.");
} catch (VException e) {
handleError("Syncgroup could not be created: " + e.getMessage());
return;
}
joinSyncgroup();
}
/**
* Sets up the local syncbase to join the syncgroup.
*/
private void joinSyncgroup() {
Syncgroup group = mLocalSB.db.getSyncgroup(mSyncgroupName);
try {
SyncgroupSpec spec = group.join(mVContext, new SyncgroupMemberInfo());
Log.i(TAG, "Successfully joined the syncgroup!");
Log.i(TAG, "Syncgroup spec: " + spec);
Map<String, SyncgroupMemberInfo> members = group.getMembers(mVContext);
for (String memberName : members.keySet()) {
Log.i(TAG, "Member: " + memberName);
}
} catch (VException e) {
handleError("Could not join the syncgroup: " + e.getMessage());
return;
}
mInitialized = true;
// When successfully joined the syncgroup, first register the device information.
registerDevice();
}
private void registerDevice() {
try {
Device thisDevice = DeviceInfoFactory.getDevice(mContext);
mLocalSB.devices.put(mVContext, thisDevice.getId(), thisDevice, Device.class);
Log.i(TAG, "Registered this device to the syncbase table: " + thisDevice);
} catch (VException e) {
handleError("Could not register this device: " + e.getMessage());
}
}
/**
* Creates the "[app]/[db]/[table]" hierarchy at the provided syncbase name.
*/
private SyncbaseHierarchy createHierarchy(
String syncbaseName, String debugName) throws VException {
SyncbaseService service = Syncbase.newService(syncbaseName);
SyncbaseHierarchy result = new SyncbaseHierarchy();
result.app = service.getApp(SYNCBASE_APP);
if (!result.app.exists(mVContext)) {
result.app.create(mVContext, mPermissions);
Log.i(TAG, String.format(
"\"%s\" app is created at %s", result.app.name(), debugName));
} else {
Log.i(TAG, String.format(
"\"%s\" app already exists at %s", result.app.name(), debugName));
}
result.db = result.app.getNoSqlDatabase(SYNCBASE_DB, null);
if (!result.db.exists(mVContext)) {
result.db.create(mVContext, mPermissions);
Log.i(TAG, String.format(
"\"%s\" db is created at %s", result.db.name(), debugName));
} else {
Log.i(TAG, String.format(
"\"%s\" db already exists at %s", result.db.name(), debugName));
}
result.files = result.db.getTable(TABLE_FILES);
if (!result.files.exists(mVContext)) {
result.files.create(mVContext, mPermissions);
Log.i(TAG, String.format(
"\"%s\" table is created at %s", result.files.name(), debugName));
} else {
Log.i(TAG, String.format(
"\"%s\" table already exists at %s", result.files.name(), debugName));
}
result.devices = result.db.getTable(TABLE_DEVICES);
if (!result.devices.exists(mVContext)) {
result.devices.create(mVContext, mPermissions);
Log.i(TAG, String.format(
"\"%s\" table is created at %s", result.devices.name(), debugName));
} else {
Log.i(TAG, String.format(
"\"%s\" table already exists at %s", result.devices.name(), debugName));
}
result.deviceSets = result.db.getTable(TABLE_DEVICE_SETS);
if (!result.deviceSets.exists(mVContext)) {
result.deviceSets.create(mVContext, mPermissions);
Log.i(TAG, String.format(
"\"%s\" table is created at %s", result.deviceSets.name(), debugName));
} else {
Log.i(TAG, String.format(
"\"%s\" table already exists at %s", result.deviceSets.name(), debugName));
}
return result;
}
/**
* This method finds the last certificate in our blessing's certificate
* chains whose extension contains an '@'. We will assume that extension to
* represent our username.
*/
private static String mountNameFromBlessings(Blessings blessings) {
for (List<VCertificate> chain : blessings.getCertificateChains()) {
for (VCertificate certificate : Lists.reverse(chain)) {
if (certificate.getExtension().contains("@")) {
return certificate.getExtension().replace(':', '/');
}
}
}
return "";
}
@Override
public DBList<File> getFileList() {
if (!mInitialized) {
return new EmptyList<>();
}
return new SyncbaseFileList(TABLE_FILES, File.class);
}
@Override
public DBList<Device> getDeviceList() {
if (!mInitialized) {
return new EmptyList<>();
}
return new SyncbaseDeviceList(TABLE_DEVICES, Device.class);
}
@Override
public DBList<DeviceSet> getDeviceSetList() {
if (!mInitialized) {
return new EmptyList<>();
}
return new SyncbaseDeviceSetList(TABLE_DEVICE_SETS, DeviceSet.class);
}
@Override
public void addFile(File file) {
try {
mLocalSB.files.put(mVContext, file.getId(), file, File.class);
} catch (VException e) {
handleError("Failed to add the file(" + file + "): " + e.getMessage());
}
}
@Override
public void deleteFile(String id) {
try {
mLocalSB.files.delete(mVContext, id);
} catch (VException e) {
handleError("Failed to delete the file with id " + id + ": " + e.getMessage());
}
}
@Override
public void addDeviceSet(DeviceSet ds) {
try {
mLocalSB.deviceSets.put(mVContext, ds.getId(), ds, DeviceSet.class);
} catch (VException e) {
handleError("Failed to add the device set(" + ds + "): " + e.getMessage());
}
}
@Override
public void updateDeviceSet(DeviceSet ds) {
try {
mLocalSB.deviceSets.put(mVContext, ds.getId(), ds, DeviceSet.class);
} catch (VException e) {
handleError("Failed to update the device set(" + ds + "): " + e.getMessage());
}
}
@Override
public void deleteDeviceSet(String id) {
try {
mLocalSB.deviceSets.delete(mVContext, id);
} catch (VException e) {
handleError("Failed to delete the device set with id " + id + ": " + e.getMessage());
}
}
@Override
public File storeBytes(byte[] bytes, String title) {
// In case of Syncbase DB, store the bytes as a blob.
// TODO(youngseokyoon): check if the same blob is already in the database.
try {
BlobWriter writer = mLocalSB.db.writeBlob(mVContext, null);
OutputStream out = writer.stream(mVContext);
out.write(bytes);
out.close();
writer.commit(mVContext);
BlobRef ref = writer.getRef();
return new File(
IdFactory.getFileId(bytes),
ref,
title,
bytes.length,
io.v.android.apps.reader.Constants.PDF_MIME_TYPE
);
} catch (VException | IOException e) {
handleError("Could not write the blob: " + e.getMessage());
}
return null;
}
@Override
public byte[] readBytes(File file) {
if (file == null || file.getRef() == null) {
return null;
}
try {
BlobReader reader = mLocalSB.db.readBlob(mVContext, file.getRef());
return ByteStreams.toByteArray(reader.stream(mVContext, 0L));
} catch (VException | IOException e) {
handleError("Could not read the blob " + file.getRef().toString()
+ ": " + e.getMessage());
}
return null;
}
private void handleError(String msg) {
Log.e(TAG, msg);
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
// TODO(youngseokyoon): Remove once the list is implemented properly.
private static class EmptyList<E> implements DBList<E> {
@Override
public int getItemCount() {
return 0;
}
@Override
public E getItem(int position) {
return null;
}
@Override
public E getItemById(String id) {
return null;
}
@Override
public void setListener(Listener listener) {
}
@Override
public void discard() {
}
}
private class SyncbaseFileList extends SyncbaseDBList<File> {
public SyncbaseFileList(String tableName, Class clazz) {
super(tableName, clazz);
}
@Override
protected String getId(File file) {
return file.getId();
}
}
private class SyncbaseDeviceList extends SyncbaseDBList<Device> {
public SyncbaseDeviceList(String tableName, Class clazz) {
super(tableName, clazz);
}
@Override
protected String getId(Device device) {
return device.getId();
}
}
private class SyncbaseDeviceSetList extends SyncbaseDBList<DeviceSet> {
public SyncbaseDeviceSetList(String tableName, Class clazz) {
super(tableName, clazz);
}
@Override
protected String getId(DeviceSet deviceSet) {
return deviceSet.getId();
}
}
private abstract class SyncbaseDBList<E> implements DBList<E> {
private final String TAG;
private CancelableVContext mCancelableVContext;
private Handler mHandler;
private Listener mListener;
private ResumeMarker mResumeMarker;
private String mTableName;
private Class mClass;
private List<E> mItems;
public SyncbaseDBList(String tableName, Class clazz) {
mCancelableVContext = mVContext.withCancel();
mTableName = tableName;
mClass = clazz;
mItems = new ArrayList<>();
mHandler = new Handler(Looper.getMainLooper());
TAG = String.format("%s<%s>",
SyncbaseDBList.class.getSimpleName(), mClass.getSimpleName());
readInitialData();
// Run this in a background thread
new Thread(new Runnable() {
@Override
public void run() {
watchForChanges();
}
}).start();
}
private void readInitialData() {
try {
Log.i(TAG, "Reading initial data from table: " + mTableName);
BatchDatabase batch = mLocalSB.db.beginBatch(
mCancelableVContext, new BatchOptions("fetch", true));
// Read existing data from the table.
Table table = batch.getTable(mTableName);
VIterable<KeyValue> kvs = table.scan(mCancelableVContext, RowRange.range("", ""));
for (KeyValue kv : kvs) {
@SuppressWarnings("unchecked")
E item = (E) VomUtil.decode(kv.getValue(), mClass);
mItems.add(item);
}
// Remember this resume marker for the watch call.
mResumeMarker = batch.getResumeMarker(mVContext);
batch.abort(mCancelableVContext);
Log.i(TAG, "Done reading initial data from table: " + mTableName);
} catch (Exception e) {
handleError(e.getMessage());
}
}
private void watchForChanges() {
try {
// Watch for new changes coming from other Syncbase peers.
VIterable<WatchChange> watchStream = mLocalSB.db.watch(
mCancelableVContext, mTableName, "", mResumeMarker);
Log.i(TAG, "Watching for changes of table: " + mTableName + "...");
for (final WatchChange wc : watchStream) {
printWatchChange(wc);
// Handle the watch change differently, depending on the change type.
switch (wc.getChangeType()) {
case PUT_CHANGE:
// Run this in the UI thread.
mHandler.post(new Runnable() {
@Override
public void run() {
handlePutChange(wc);
}
});
break;
case DELETE_CHANGE:
// Run this in the UI thread.
mHandler.post(new Runnable() {
@Override
public void run() {
handleDeleteChange(wc);
}
});
break;
}
}
} catch (Exception e) {
handleError(e.getMessage());
Log.e(TAG, "Stack Trace: ", e);
}
}
private void printWatchChange(WatchChange wc) {
Log.i(TAG, "*** New Watch Change ***");
Log.i(TAG, "- ChangeType: " + wc.getChangeType().toString());
Log.i(TAG, "- RowName: " + wc.getRowName());
Log.i(TAG, "- TableName: " + wc.getTableName());
Log.i(TAG, "- VomValue: " + VomUtil.bytesToHexString(wc.getVomValue()));
Log.i(TAG, "- isContinued: " + wc.isContinued());
Log.i(TAG, "- isFromSync: " + wc.isFromSync());
Log.i(TAG, "========================");
}
private void handlePutChange(WatchChange wc) {
E item = null;
try {
item = (E) VomUtil.decode(wc.getVomValue(), mClass);
} catch (VException e) {
handleError("Could not decode the Vom: " + e.getMessage());
}
if (item == null) {
return;
}
boolean handled = false;
for (int i = 0; i < mItems.size(); ++i) {
E e = mItems.get(i);
if (wc.getRowName().equals(getId(e))) {
// Update the file record here.
mItems.remove(i);
mItems.add(i, item);
if (mListener != null) {
mListener.notifyItemChanged(i);
}
handled = true;
}
}
if (handled) {
return;
}
// This is a new row added in the table.
mItems.add(item);
if (mListener != null) {
mListener.notifyItemInserted(mItems.size() - 1);
}
}
private void handleDeleteChange(WatchChange wc) {
boolean handled = false;
for (int i = 0; i < mItems.size(); ++i) {
E e = mItems.get(i);
if (wc.getRowName().equals(getId(e))) {
mItems.remove(i);
if (mListener != null) {
mListener.notifyItemRemoved(i);
}
handled = true;
}
}
if (!handled) {
handleError("DELETE_CHANGE arrived but no matching item found in the table.");
}
}
protected abstract String getId(E e);
@Override
public int getItemCount() {
return mItems.size();
}
@Override
public E getItem(int position) {
return mItems.get(position);
}
@Override
public E getItemById(String id) {
for (E e : mItems) {
if (getId(e).equals(id)) {
return e;
}
}
return null;
}
@Override
public void setListener(Listener listener) {
assert mListener == null;
mListener = listener;
}
@Override
public void discard() {
Log.i(TAG, "Cancelling the watch stream.");
mCancelableVContext.cancel();
}
}
private static class SyncbaseHierarchy {
public SyncbaseApp app;
public Database db;
public Table files;
public Table devices;
public Table deviceSets;
}
}
| android/app/src/main/java/io/v/android/apps/reader/db/SyncbaseDB.java | // Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package io.v.android.apps.reader.db;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import io.v.android.apps.reader.model.DeviceInfoFactory;
import io.v.android.apps.reader.model.IdFactory;
import io.v.android.apps.reader.model.Listener;
import io.v.android.apps.reader.vdl.Device;
import io.v.android.apps.reader.vdl.DeviceSet;
import io.v.android.apps.reader.vdl.File;
import io.v.android.libs.security.BlessingsManager;
import io.v.android.v23.V;
import io.v.android.v23.services.blessing.BlessingCreationException;
import io.v.android.v23.services.blessing.BlessingService;
import io.v.impl.google.naming.NamingUtil;
import io.v.impl.google.services.syncbase.SyncbaseServer;
import io.v.v23.VIterable;
import io.v.v23.context.CancelableVContext;
import io.v.v23.context.VContext;
import io.v.v23.rpc.Server;
import io.v.v23.security.BlessingPattern;
import io.v.v23.security.Blessings;
import io.v.v23.security.VCertificate;
import io.v.v23.security.VPrincipal;
import io.v.v23.security.VSecurity;
import io.v.v23.security.access.AccessList;
import io.v.v23.security.access.Constants;
import io.v.v23.security.access.Permissions;
import io.v.v23.services.syncbase.nosql.BatchOptions;
import io.v.v23.services.syncbase.nosql.BlobRef;
import io.v.v23.services.syncbase.nosql.KeyValue;
import io.v.v23.services.syncbase.nosql.SyncgroupMemberInfo;
import io.v.v23.services.syncbase.nosql.SyncgroupSpec;
import io.v.v23.services.syncbase.nosql.TableRow;
import io.v.v23.services.watch.ResumeMarker;
import io.v.v23.syncbase.Syncbase;
import io.v.v23.syncbase.SyncbaseApp;
import io.v.v23.syncbase.SyncbaseService;
import io.v.v23.syncbase.nosql.BatchDatabase;
import io.v.v23.syncbase.nosql.BlobReader;
import io.v.v23.syncbase.nosql.BlobWriter;
import io.v.v23.syncbase.nosql.Database;
import io.v.v23.syncbase.nosql.RowRange;
import io.v.v23.syncbase.nosql.Syncgroup;
import io.v.v23.syncbase.nosql.Table;
import io.v.v23.syncbase.nosql.WatchChange;
import io.v.v23.verror.ExistException;
import io.v.v23.verror.VException;
import io.v.v23.vom.VomUtil;
/**
* A class representing the syncbase instance.
*/
public class SyncbaseDB implements DB {
private static final String TAG = SyncbaseDB.class.getSimpleName();
/**
* The intent result code for when we get blessings from the account manager.
* The value must not conflict with any other blessing result codes.
*/
private static final int BLESSING_REQUEST = 200;
private static final String GLOBAL_MOUNT_TABLE = "/ns.dev.v.io:8101";
private static final String SYNCBASE_APP = "reader";
private static final String SYNCBASE_DB = "db";
private static final String TABLE_FILES = "files";
private static final String TABLE_DEVICES = "devices";
private static final String TABLE_DEVICE_SETS = "deviceSets";
private Permissions mPermissions;
private Context mContext;
private VContext mVContext;
private SyncbaseHierarchy mLocalSB;
private boolean mInitialized;
private String mUsername;
private String mSyncgroupName;
SyncbaseDB(Context context) {
mContext = context;
}
@Override
public void init(Activity activity) {
if (isInitialized()) {
// Already initialized.
return;
}
if (mVContext == null) {
mVContext = V.init(mContext);
try {
mVContext = V.withListenSpec(
mVContext, V.getListenSpec(mVContext).withProxy("proxy"));
} catch (VException e) {
handleError("Couldn't setup vanadium proxy: " + e.getMessage());
}
}
AccessList acl = new AccessList(
ImmutableList.of(new BlessingPattern("...")), ImmutableList.<String>of());
mPermissions = new Permissions(ImmutableMap.of(
Constants.READ.getValue(), acl,
Constants.WRITE.getValue(), acl,
Constants.ADMIN.getValue(), acl,
Constants.RESOLVE.getValue(), acl,
Constants.DEBUG.getValue(), acl));
getBlessings(activity);
}
@Override
public boolean isInitialized() {
return mInitialized;
}
private void getBlessings(Activity activity) {
Blessings blessings = null;
try {
// See if there are blessings stored in shared preferences.
blessings = BlessingsManager.getBlessings(mContext);
} catch (VException e) {
handleError("Error getting blessings from shared preferences " + e.getMessage());
}
if (blessings == null) {
// Request new blessings from the account manager via an intent. This intent
// will call back to onActivityResult() which will continue with
// configurePrincipal().
refreshBlessings(activity);
return;
}
configurePrincipal(blessings);
}
private void refreshBlessings(Activity activity) {
Intent intent = BlessingService.newBlessingIntent(mContext);
activity.startActivityForResult(intent, BLESSING_REQUEST);
}
@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BLESSING_REQUEST) {
try {
byte[] blessingsVom = BlessingService.extractBlessingReply(resultCode, data);
Blessings blessings = (Blessings) VomUtil.decode(blessingsVom, Blessings.class);
BlessingsManager.addBlessings(mContext, blessings);
Toast.makeText(mContext, "Success", Toast.LENGTH_SHORT).show();
configurePrincipal(blessings);
} catch (BlessingCreationException e) {
handleError("Couldn't create blessing: " + e.getMessage());
} catch (VException e) {
handleError("Couldn't derive blessing: " + e.getMessage());
}
return true;
}
return false;
}
private void configurePrincipal(Blessings blessings) {
try {
VPrincipal p = V.getPrincipal(mVContext);
p.blessingStore().setDefaultBlessings(blessings);
p.blessingStore().set(blessings, new BlessingPattern("..."));
VSecurity.addToRoots(p, blessings);
// "<user_email>/android"
mUsername = mountNameFromBlessings(blessings);
} catch (VException e) {
handleError(String.format(
"Couldn't set local blessing %s: %s", blessings, e.getMessage()));
return;
}
setupLocalSyncbase();
}
private void setupLocalSyncbase() {
// "users/<user_email>/android/reader/<device_id>/syncbase"
final String syncbaseName = NamingUtil.join(
"users",
mUsername,
"reader",
DeviceInfoFactory.getDevice(mContext).getId(),
"syncbase"
);
Log.i(TAG, "SyncbaseName: " + syncbaseName);
// Prepare the syncbase storage directory.
java.io.File storageDir = new java.io.File(mContext.getFilesDir(), "syncbase");
storageDir.mkdirs();
try {
mVContext = SyncbaseServer.withNewServer(
mVContext,
new SyncbaseServer.Params()
.withName(syncbaseName)
.withPermissions(mPermissions)
.withStorageRootDir(storageDir.getAbsolutePath()));
} catch (SyncbaseServer.StartException e) {
handleError("Couldn't start syncbase server");
return;
}
try {
Server syncbaseServer = V.getServer(mVContext);
String serverName = "/" + syncbaseServer.getStatus().getEndpoints()[0];
Log.i(TAG, "Local Syncbase ServerName: " + serverName);
mLocalSB = createHierarchy(serverName, "local");
setupCloudSyncbase();
} catch (VException e) {
handleError("Couldn't setup syncbase service: " + e.getMessage());
}
}
/**
* This method assumes that there is a separate cloudsync instance running at:
* "users/[user_email]/reader/cloudsync"
*/
private void setupCloudSyncbase() {
try {
// "users/<user_email>/reader/cloudsync"
String cloudsyncName = NamingUtil.join(
"users",
NamingUtil.trimSuffix(mUsername, "android"),
"reader/cloudsync"
);
SyncbaseHierarchy cloudSB = createHierarchy(cloudsyncName, "cloud");
createSyncgroup(cloudSB.db);
} catch (VException e) {
handleError("Couldn't setup cloudsync: " + e.getMessage());
}
}
/**
* Creates a syncgroup at cloudsync with the following name:
* "users/[user_email]/reader/cloudsync/%%sync/cloudsync"
*/
private void createSyncgroup(Database db) {
mSyncgroupName = NamingUtil.join(
"users",
NamingUtil.trimSuffix(mUsername, "android"),
"reader/cloudsync/%%sync/cloudsync"
);
Syncgroup group = db.getSyncgroup(mSyncgroupName);
List<TableRow> prefixes = ImmutableList.of(
new TableRow(TABLE_FILES, ""),
new TableRow(TABLE_DEVICES, ""),
new TableRow(TABLE_DEVICE_SETS, "")
);
List<String> mountTables = ImmutableList.of(
NamingUtil.join(
GLOBAL_MOUNT_TABLE,
"users",
NamingUtil.trimSuffix(mUsername, "android"),
"reader/rendezvous"
)
);
SyncgroupSpec spec = new SyncgroupSpec(
"reader syncgroup",
mPermissions,
prefixes,
mountTables,
false
);
try {
group.create(mVContext, spec, new SyncgroupMemberInfo());
Log.i(TAG, "Syncgroup is created successfully.");
} catch (ExistException e) {
Log.i(TAG, "Syncgroup already exists.");
} catch (VException e) {
handleError("Syncgroup could not be created: " + e.getMessage());
return;
}
joinSyncgroup();
}
/**
* Sets up the local syncbase to join the syncgroup.
*/
private void joinSyncgroup() {
Syncgroup group = mLocalSB.db.getSyncgroup(mSyncgroupName);
try {
SyncgroupSpec spec = group.join(mVContext, new SyncgroupMemberInfo());
Log.i(TAG, "Successfully joined the syncgroup!");
Log.i(TAG, "Syncgroup spec: " + spec);
Map<String, SyncgroupMemberInfo> members = group.getMembers(mVContext);
for (String memberName : members.keySet()) {
Log.i(TAG, "Member: " + memberName);
}
} catch (VException e) {
handleError("Could not join the syncgroup: " + e.getMessage());
return;
}
mInitialized = true;
// When successfully joined the syncgroup, first register the device information.
registerDevice();
}
private void registerDevice() {
try {
Device thisDevice = DeviceInfoFactory.getDevice(mContext);
mLocalSB.devices.put(mVContext, thisDevice.getId(), thisDevice, Device.class);
Log.i(TAG, "Registered this device to the syncbase table: " + thisDevice);
} catch (VException e) {
handleError("Could not register this device: " + e.getMessage());
}
}
/**
* Creates the "[app]/[db]/[table]" hierarchy at the provided syncbase name.
*/
private SyncbaseHierarchy createHierarchy(
String syncbaseName, String debugName) throws VException {
SyncbaseService service = Syncbase.newService(syncbaseName);
SyncbaseHierarchy result = new SyncbaseHierarchy();
result.app = service.getApp(SYNCBASE_APP);
if (!result.app.exists(mVContext)) {
result.app.create(mVContext, mPermissions);
Log.i(TAG, String.format(
"\"%s\" app is created at %s", result.app.name(), debugName));
} else {
Log.i(TAG, String.format(
"\"%s\" app already exists at %s", result.app.name(), debugName));
}
result.db = result.app.getNoSqlDatabase(SYNCBASE_DB, null);
if (!result.db.exists(mVContext)) {
result.db.create(mVContext, mPermissions);
Log.i(TAG, String.format(
"\"%s\" db is created at %s", result.db.name(), debugName));
} else {
Log.i(TAG, String.format(
"\"%s\" db already exists at %s", result.db.name(), debugName));
}
result.files = result.db.getTable(TABLE_FILES);
if (!result.files.exists(mVContext)) {
result.files.create(mVContext, mPermissions);
Log.i(TAG, String.format(
"\"%s\" table is created at %s", result.files.name(), debugName));
} else {
Log.i(TAG, String.format(
"\"%s\" table already exists at %s", result.files.name(), debugName));
}
result.devices = result.db.getTable(TABLE_DEVICES);
if (!result.devices.exists(mVContext)) {
result.devices.create(mVContext, mPermissions);
Log.i(TAG, String.format(
"\"%s\" table is created at %s", result.devices.name(), debugName));
} else {
Log.i(TAG, String.format(
"\"%s\" table already exists at %s", result.devices.name(), debugName));
}
result.deviceSets = result.db.getTable(TABLE_DEVICE_SETS);
if (!result.deviceSets.exists(mVContext)) {
result.deviceSets.create(mVContext, mPermissions);
Log.i(TAG, String.format(
"\"%s\" table is created at %s", result.deviceSets.name(), debugName));
} else {
Log.i(TAG, String.format(
"\"%s\" table already exists at %s", result.deviceSets.name(), debugName));
}
return result;
}
/**
* This method finds the last certificate in our blessing's certificate
* chains whose extension contains an '@'. We will assume that extension to
* represent our username.
*/
private static String mountNameFromBlessings(Blessings blessings) {
for (List<VCertificate> chain : blessings.getCertificateChains()) {
for (VCertificate certificate : Lists.reverse(chain)) {
if (certificate.getExtension().contains("@")) {
return certificate.getExtension();
}
}
}
return "";
}
@Override
public DBList<File> getFileList() {
if (!mInitialized) {
return new EmptyList<>();
}
return new SyncbaseFileList(TABLE_FILES, File.class);
}
@Override
public DBList<Device> getDeviceList() {
if (!mInitialized) {
return new EmptyList<>();
}
return new SyncbaseDeviceList(TABLE_DEVICES, Device.class);
}
@Override
public DBList<DeviceSet> getDeviceSetList() {
if (!mInitialized) {
return new EmptyList<>();
}
return new SyncbaseDeviceSetList(TABLE_DEVICE_SETS, DeviceSet.class);
}
@Override
public void addFile(File file) {
try {
mLocalSB.files.put(mVContext, file.getId(), file, File.class);
} catch (VException e) {
handleError("Failed to add the file(" + file + "): " + e.getMessage());
}
}
@Override
public void deleteFile(String id) {
try {
mLocalSB.files.delete(mVContext, id);
} catch (VException e) {
handleError("Failed to delete the file with id " + id + ": " + e.getMessage());
}
}
@Override
public void addDeviceSet(DeviceSet ds) {
try {
mLocalSB.deviceSets.put(mVContext, ds.getId(), ds, DeviceSet.class);
} catch (VException e) {
handleError("Failed to add the device set(" + ds + "): " + e.getMessage());
}
}
@Override
public void updateDeviceSet(DeviceSet ds) {
try {
mLocalSB.deviceSets.put(mVContext, ds.getId(), ds, DeviceSet.class);
} catch (VException e) {
handleError("Failed to update the device set(" + ds + "): " + e.getMessage());
}
}
@Override
public void deleteDeviceSet(String id) {
try {
mLocalSB.deviceSets.delete(mVContext, id);
} catch (VException e) {
handleError("Failed to delete the device set with id " + id + ": " + e.getMessage());
}
}
@Override
public File storeBytes(byte[] bytes, String title) {
// In case of Syncbase DB, store the bytes as a blob.
// TODO(youngseokyoon): check if the same blob is already in the database.
try {
BlobWriter writer = mLocalSB.db.writeBlob(mVContext, null);
OutputStream out = writer.stream(mVContext);
out.write(bytes);
out.close();
writer.commit(mVContext);
BlobRef ref = writer.getRef();
return new File(
IdFactory.getFileId(bytes),
ref,
title,
bytes.length,
io.v.android.apps.reader.Constants.PDF_MIME_TYPE
);
} catch (VException | IOException e) {
handleError("Could not write the blob: " + e.getMessage());
}
return null;
}
@Override
public byte[] readBytes(File file) {
if (file == null || file.getRef() == null) {
return null;
}
try {
BlobReader reader = mLocalSB.db.readBlob(mVContext, file.getRef());
return ByteStreams.toByteArray(reader.stream(mVContext, 0L));
} catch (VException | IOException e) {
handleError("Could not read the blob " + file.getRef().toString()
+ ": " + e.getMessage());
}
return null;
}
private void handleError(String msg) {
Log.e(TAG, msg);
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
// TODO(youngseokyoon): Remove once the list is implemented properly.
private static class EmptyList<E> implements DBList<E> {
@Override
public int getItemCount() {
return 0;
}
@Override
public E getItem(int position) {
return null;
}
@Override
public E getItemById(String id) {
return null;
}
@Override
public void setListener(Listener listener) {
}
@Override
public void discard() {
}
}
private class SyncbaseFileList extends SyncbaseDBList<File> {
public SyncbaseFileList(String tableName, Class clazz) {
super(tableName, clazz);
}
@Override
protected String getId(File file) {
return file.getId();
}
}
private class SyncbaseDeviceList extends SyncbaseDBList<Device> {
public SyncbaseDeviceList(String tableName, Class clazz) {
super(tableName, clazz);
}
@Override
protected String getId(Device device) {
return device.getId();
}
}
private class SyncbaseDeviceSetList extends SyncbaseDBList<DeviceSet> {
public SyncbaseDeviceSetList(String tableName, Class clazz) {
super(tableName, clazz);
}
@Override
protected String getId(DeviceSet deviceSet) {
return deviceSet.getId();
}
}
private abstract class SyncbaseDBList<E> implements DBList<E> {
private final String TAG;
private CancelableVContext mCancelableVContext;
private Handler mHandler;
private Listener mListener;
private ResumeMarker mResumeMarker;
private String mTableName;
private Class mClass;
private List<E> mItems;
public SyncbaseDBList(String tableName, Class clazz) {
mCancelableVContext = mVContext.withCancel();
mTableName = tableName;
mClass = clazz;
mItems = new ArrayList<>();
mHandler = new Handler(Looper.getMainLooper());
TAG = String.format("%s<%s>",
SyncbaseDBList.class.getSimpleName(), mClass.getSimpleName());
readInitialData();
// Run this in a background thread
new Thread(new Runnable() {
@Override
public void run() {
watchForChanges();
}
}).start();
}
private void readInitialData() {
try {
Log.i(TAG, "Reading initial data from table: " + mTableName);
BatchDatabase batch = mLocalSB.db.beginBatch(
mCancelableVContext, new BatchOptions("fetch", true));
// Read existing data from the table.
Table table = batch.getTable(mTableName);
VIterable<KeyValue> kvs = table.scan(mCancelableVContext, RowRange.range("", ""));
for (KeyValue kv : kvs) {
@SuppressWarnings("unchecked")
E item = (E) VomUtil.decode(kv.getValue(), mClass);
mItems.add(item);
}
// Remember this resume marker for the watch call.
mResumeMarker = batch.getResumeMarker(mVContext);
batch.abort(mCancelableVContext);
Log.i(TAG, "Done reading initial data from table: " + mTableName);
} catch (Exception e) {
handleError(e.getMessage());
}
}
private void watchForChanges() {
try {
// Watch for new changes coming from other Syncbase peers.
VIterable<WatchChange> watchStream = mLocalSB.db.watch(
mCancelableVContext, mTableName, "", mResumeMarker);
Log.i(TAG, "Watching for changes of table: " + mTableName + "...");
for (final WatchChange wc : watchStream) {
printWatchChange(wc);
// Handle the watch change differently, depending on the change type.
switch (wc.getChangeType()) {
case PUT_CHANGE:
// Run this in the UI thread.
mHandler.post(new Runnable() {
@Override
public void run() {
handlePutChange(wc);
}
});
break;
case DELETE_CHANGE:
// Run this in the UI thread.
mHandler.post(new Runnable() {
@Override
public void run() {
handleDeleteChange(wc);
}
});
break;
}
}
} catch (Exception e) {
handleError(e.getMessage());
Log.e(TAG, "Stack Trace: ", e);
}
}
private void printWatchChange(WatchChange wc) {
Log.i(TAG, "*** New Watch Change ***");
Log.i(TAG, "- ChangeType: " + wc.getChangeType().toString());
Log.i(TAG, "- RowName: " + wc.getRowName());
Log.i(TAG, "- TableName: " + wc.getTableName());
Log.i(TAG, "- VomValue: " + VomUtil.bytesToHexString(wc.getVomValue()));
Log.i(TAG, "- isContinued: " + wc.isContinued());
Log.i(TAG, "- isFromSync: " + wc.isFromSync());
Log.i(TAG, "========================");
}
private void handlePutChange(WatchChange wc) {
E item = null;
try {
item = (E) VomUtil.decode(wc.getVomValue(), mClass);
} catch (VException e) {
handleError("Could not decode the Vom: " + e.getMessage());
}
if (item == null) {
return;
}
boolean handled = false;
for (int i = 0; i < mItems.size(); ++i) {
E e = mItems.get(i);
if (wc.getRowName().equals(getId(e))) {
// Update the file record here.
mItems.remove(i);
mItems.add(i, item);
if (mListener != null) {
mListener.notifyItemChanged(i);
}
handled = true;
}
}
if (handled) {
return;
}
// This is a new row added in the table.
mItems.add(item);
if (mListener != null) {
mListener.notifyItemInserted(mItems.size() - 1);
}
}
private void handleDeleteChange(WatchChange wc) {
boolean handled = false;
for (int i = 0; i < mItems.size(); ++i) {
E e = mItems.get(i);
if (wc.getRowName().equals(getId(e))) {
mItems.remove(i);
if (mListener != null) {
mListener.notifyItemRemoved(i);
}
handled = true;
}
}
if (!handled) {
handleError("DELETE_CHANGE arrived but no matching item found in the table.");
}
}
protected abstract String getId(E e);
@Override
public int getItemCount() {
return mItems.size();
}
@Override
public E getItem(int position) {
return mItems.get(position);
}
@Override
public E getItemById(String id) {
for (E e : mItems) {
if (getId(e).equals(id)) {
return e;
}
}
return null;
}
@Override
public void setListener(Listener listener) {
assert mListener == null;
mListener = listener;
}
@Override
public void discard() {
Log.i(TAG, "Cancelling the watch stream.");
mCancelableVContext.cancel();
}
}
private static class SyncbaseHierarchy {
public SyncbaseApp app;
public Database db;
public Table files;
public Table devices;
public Table deviceSets;
}
}
| TBR: reader/android: change colons to slashes
Change-Id: Ifc5b8d774f63d9cb35eb1a9c0b2e93dba5174c2d
| android/app/src/main/java/io/v/android/apps/reader/db/SyncbaseDB.java | TBR: reader/android: change colons to slashes | <ide><path>ndroid/app/src/main/java/io/v/android/apps/reader/db/SyncbaseDB.java
<ide> for (List<VCertificate> chain : blessings.getCertificateChains()) {
<ide> for (VCertificate certificate : Lists.reverse(chain)) {
<ide> if (certificate.getExtension().contains("@")) {
<del> return certificate.getExtension();
<add> return certificate.getExtension().replace(':', '/');
<ide> }
<ide> }
<ide> } |
|
Java | mit | 881acd31d78895147443116e30c05c0d634a22b5 | 0 | elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin | package com.elmakers.mine.bukkit.magic;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;
public class MageParameters extends ParameterizedConfiguration {
private static Set<String> attributes;
private final @Nonnull
Mage mage;
public MageParameters(Mage mage, String context) {
super(context);
this.mage = mage;
}
public MageParameters(MageParameters copy) {
super(copy);
this.mage = copy.mage;
}
protected MageController getController() {
return mage.getController();
}
protected Mage getMage() {
return mage;
}
public static void initializeAttributes(Set<String> attrs) {
attributes = new HashSet<>(attrs);
}
@Override
@Nullable
protected Double evaluate(String expression) {
if (mage.isPlayer()) {
expression = getController().setPlaceholders(mage.getPlayer(), expression);
}
return super.evaluate(expression);
}
@Override
protected double getParameter(String parameter) {
Double value = mage.getAttribute(parameter);
return value == null || Double.isNaN(value) || Double.isInfinite(value) ? 0 : value;
}
@Override
protected Set<String> getParameters() {
return attributes;
}
}
| Magic/src/main/java/com/elmakers/mine/bukkit/magic/MageParameters.java | package com.elmakers.mine.bukkit.magic;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;
public class MageParameters extends ParameterizedConfiguration {
private static Set<String> attributes;
private final @Nonnull
Mage mage;
public MageParameters(Mage mage, String context) {
super(context);
this.mage = mage;
}
public MageParameters(MageParameters copy) {
super(copy);
this.mage = copy.mage;
}
protected MageController getController() {
return mage.getController();
}
protected Mage getMage() {
return mage;
}
public static void initializeAttributes(Set<String> attrs) {
attributes = new HashSet<>(attrs);
}
@Nullable
protected Double evaluate(String expression) {
if (mage.isPlayer()) {
expression = getController().setPlaceholders(mage.getPlayer(), expression);
}
return super.evaluate(expression);
}
@Override
protected double getParameter(String parameter) {
Double value = mage.getAttribute(parameter);
return value == null || Double.isNaN(value) || Double.isInfinite(value) ? 0 : value;
}
@Override
protected Set<String> getParameters() {
return attributes;
}
}
| Add missing @Override
| Magic/src/main/java/com/elmakers/mine/bukkit/magic/MageParameters.java | Add missing @Override | <ide><path>agic/src/main/java/com/elmakers/mine/bukkit/magic/MageParameters.java
<ide> attributes = new HashSet<>(attrs);
<ide> }
<ide>
<add> @Override
<ide> @Nullable
<ide> protected Double evaluate(String expression) {
<ide> if (mage.isPlayer()) { |
|
Java | bsd-3-clause | b80fdaebe6e0ab821f4cb3735645756254f2ffc1 | 0 | nka11/jintn3270 | package com.sf.jintn3270.awt;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import com.sf.jintn3270.TerminalModel;
public class DefaultTerminalRenderer extends Component implements TerminalRenderer {
FontRenderContext fontContext;
RenderingHints renderHints;
boolean scaleFont;
boolean stretchFont;
public DefaultTerminalRenderer() {
super();
setFont(Font.decode("Monospaced-12"));
renderHints = new RenderingHints(null);
renderHints.put(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
renderHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
scaleFont = true;
stretchFont = true;
}
public void paint(Graphics g, TerminalModel m) {
Graphics2D g2d = (Graphics2D)g;
g2d.setFont(calculateFont(g2d, m));
g2d.setRenderingHints(renderHints);
Rectangle2D charBound = g2d.getFontMetrics().getStringBounds("M", g2d);
LineMetrics lineMetrics = g2d.getFontMetrics().getLineMetrics("Mq", g2d);
g2d.setBackground(Color.BLACK);
g2d.setColor(Color.WHITE);
g2d.clearRect(0, 0, g2d.getClipBounds().width, g2d.getClipBounds().height);
Point2D p = new Point2D.Float();
for (int line = 0; line < m.getBufferHeight(); line++) {
// TODO: Use AttributedCharacterIterator to read/render the column.
for (int col = 0; col < m.getBufferWidth(); col++) {
p.setLocation(col * (charBound.getWidth() + 1),
(lineMetrics.getAscent() * (line + 1)) +
(line * (lineMetrics.getDescent() + lineMetrics.getLeading())));
g2d.drawString("" + m.getChar(line, col).getDisplay(), (float)p.getX(), (float)p.getY());
}
}
// Draw an underscore cursor
p.setLocation(m.cursor().column() * (charBound.getWidth() + 1),
(lineMetrics.getAscent() * (m.cursor().row() + 1)) +
(m.cursor().row() * (lineMetrics.getDescent() + lineMetrics.getLeading())));
Rectangle2D cursorRect = new Rectangle2D.Double(p.getX(), p.getY(), charBound.getWidth(), 2);
g2d.fill(cursorRect);
}
public Dimension getPreferredSize(TerminalModel m) {
if (m == null) {
return new Dimension(200, 150);
} else {
return getBufferSize(m, getFont().deriveFont(12.0f));
}
}
public Dimension getMinimumSize(TerminalModel m) {
if (m == null) {
return new Dimension(200, 150);
} else {
return getBufferSize(m, getFont().deriveFont(6.0f));
}
}
protected Font calculateFont(Graphics2D g2d, TerminalModel m) {
Font ret = getFont();
Rectangle bounds = g2d.getClipBounds();
if (bounds != null && (scaleFont || stretchFont)) {
// Given the height / width of the buffer, set the font size.
Rectangle2D.Double idealCharSize =
new Rectangle2D.Double(0d, 0d,
(bounds.getWidth() / m.getBufferWidth()) - 1,
(bounds.getHeight() / m.getBufferHeight()));
if (scaleFont) {
Font reference = Font.decode(getFont().getFontName() + "-" + getStyle(getFont()) + "-12").deriveFont(new AffineTransform());
Rectangle2D charSize = g2d.getFontMetrics(reference).getStringBounds("M", g2d);
float targetPt = (float)(idealCharSize.getWidth() / charSize.getWidth());
targetPt = (float)Math.round(targetPt * reference.getSize2D() * 10) / 10.0f;
ret = reference.deriveFont(targetPt);
}
if (stretchFont) {
double scaley = idealCharSize.getHeight() / g2d.getFontMetrics(ret).getLineMetrics("Mq", g2d).getHeight();
AffineTransform scaleTransform = new AffineTransform();
scaleTransform.setToScale(1.0, scaley);
ret = ret.deriveFont(scaleTransform);
}
}
return ret;
}
private String getStyle(Font f) {
if (f.getStyle() == Font.PLAIN) {
return "plain";
} else if (f.getStyle() == Font.BOLD) {
return "bold";
} else if (f.getStyle() == Font.ITALIC) {
return "italic";
} else {
return "bolditalic";
}
}
/**
* Calculate the required size to render given the model and font.
*
* @param m The TerminalModel to potentially render
* @param f The font to use for rendering.
*
* @return The required size to render the contents in the given font.
*/
Dimension getBufferSize(TerminalModel m, Font f) {
Rectangle2D charBound = f.getStringBounds("M", fontContext);
LineMetrics lineMetrics = f.getLineMetrics("Mq", fontContext);
double x = ((double)m.getBufferWidth() * (charBound.getWidth() + 1));
// Get the full line height for all rows, (ascent + descent) then add
// up the leading line space (between lines), which is always one line
// less than the full number of lines.
double y = ((double)((m.getBufferHeight() * (lineMetrics.getAscent() + lineMetrics.getDescent())) +
((m.getBufferHeight() - 1) * (lineMetrics.getLeading()))));
Dimension d = new Dimension();
d.setSize(x, y);
return d;
}
/**
* Overrides the parent class setFont to set the fontContext to approximate
* the proper FontRenderContext until the next paint() invocation.
*/
public void setFont(Font f) {
super.setFont(f);
fontContext = new FontRenderContext(new AffineTransform(), true, true);
}
} | src/com/sf/jintn3270/awt/DefaultTerminalRenderer.java | package com.sf.jintn3270.awt;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import com.sf.jintn3270.TerminalModel;
public class DefaultTerminalRenderer extends Component implements TerminalRenderer {
FontRenderContext fontContext;
RenderingHints renderHints;
public DefaultTerminalRenderer() {
super();
setFont(Font.decode("Monospaced-12"));
renderHints = new RenderingHints(null);
renderHints.put(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
renderHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
public void paint(Graphics g, TerminalModel m) {
Graphics2D g2d = (Graphics2D)g;
g2d.setFont(getFont());
g2d.setRenderingHints(renderHints);
if (!g2d.getFontRenderContext().equals(fontContext)) {
fontContext = g2d.getFontRenderContext();
}
Rectangle2D charBound = getFont().getStringBounds("M", fontContext);
LineMetrics lineMetrics = getFont().getLineMetrics("Mq", fontContext);
g2d.setBackground(Color.BLACK);
g2d.setColor(Color.WHITE);
g2d.clearRect(0, 0, g2d.getClipBounds().width, g2d.getClipBounds().height);
Point2D.Float p = new Point2D.Float();
for (int line = 0; line < m.getBufferHeight(); line++) {
// TODO: Use AttributedCharacterIterator to read/render the column.
for (int col = 0; col < m.getBufferWidth(); col++) {
p.setLocation(col * (charBound.getWidth() + 1),
(lineMetrics.getAscent() * (line + 1)) +
(line * (lineMetrics.getDescent() + lineMetrics.getLeading())));
g2d.drawString("" + m.getChar(line, col).getDisplay(), (float)p.getX(), (float)p.getY());
}
}
}
public Dimension getPreferredSize(TerminalModel m) {
if (m == null) {
return new Dimension(200, 150);
} else {
return getBufferSize(m, getFont().deriveFont(12.0f));
}
}
public Dimension getMinimumSize(TerminalModel m) {
if (m == null) {
return new Dimension(200, 150);
} else {
return getBufferSize(m, getFont().deriveFont(6.0f));
}
}
/**
* Calculate the required size to render given the model and font.
*
* @param m The TerminalModel to potentially render
* @param f The font to use for rendering.
*
* @return The required size to render the contents in the given font.
*/
Dimension getBufferSize(TerminalModel m, Font f) {
Rectangle2D charBound = f.getStringBounds("M", fontContext);
LineMetrics lineMetrics = f.getLineMetrics("Mq", fontContext);
double x = ((double)m.getBufferWidth() * (charBound.getWidth() + 1));
// Get the full line height for all rows, (ascent + descent) then add
// up the leading line space (between lines), which is always one line
// less than the full number of lines.
double y = ((double)((m.getBufferHeight() * (lineMetrics.getAscent() + lineMetrics.getDescent())) +
((m.getBufferHeight() - 1) * (lineMetrics.getLeading()))));
Dimension d = new Dimension();
d.setSize(x, y);
return d;
}
/**
* Overrides the parent class setFont to set the fontContext to approximate
* the proper FontRenderContext until the next paint() invocation.
*/
public void setFont(Font f) {
super.setFont(f);
fontContext = new FontRenderContext(new AffineTransform(), true, true);
}
} | Font scaling and stretching to match the size of the Terminal
git-svn-id: f76f0d361b8045537d852970971daaa7b3f7adae@40 d6bd4e80-8031-4e1d-bd39-93c407d940fc
| src/com/sf/jintn3270/awt/DefaultTerminalRenderer.java | Font scaling and stretching to match the size of the Terminal | <ide><path>rc/com/sf/jintn3270/awt/DefaultTerminalRenderer.java
<ide> FontRenderContext fontContext;
<ide> RenderingHints renderHints;
<ide>
<add> boolean scaleFont;
<add> boolean stretchFont;
<add>
<ide> public DefaultTerminalRenderer() {
<ide> super();
<ide> setFont(Font.decode("Monospaced-12"));
<ide> RenderingHints.VALUE_FRACTIONALMETRICS_ON);
<ide> renderHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
<ide> RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
<add> scaleFont = true;
<add> stretchFont = true;
<ide> }
<ide>
<ide> public void paint(Graphics g, TerminalModel m) {
<ide> Graphics2D g2d = (Graphics2D)g;
<del> g2d.setFont(getFont());
<add> g2d.setFont(calculateFont(g2d, m));
<ide> g2d.setRenderingHints(renderHints);
<del> if (!g2d.getFontRenderContext().equals(fontContext)) {
<del> fontContext = g2d.getFontRenderContext();
<del> }
<del> Rectangle2D charBound = getFont().getStringBounds("M", fontContext);
<del> LineMetrics lineMetrics = getFont().getLineMetrics("Mq", fontContext);
<add> Rectangle2D charBound = g2d.getFontMetrics().getStringBounds("M", g2d);
<add> LineMetrics lineMetrics = g2d.getFontMetrics().getLineMetrics("Mq", g2d);
<ide>
<ide> g2d.setBackground(Color.BLACK);
<ide> g2d.setColor(Color.WHITE);
<ide> g2d.clearRect(0, 0, g2d.getClipBounds().width, g2d.getClipBounds().height);
<ide>
<del> Point2D.Float p = new Point2D.Float();
<add> Point2D p = new Point2D.Float();
<ide> for (int line = 0; line < m.getBufferHeight(); line++) {
<ide> // TODO: Use AttributedCharacterIterator to read/render the column.
<ide> for (int col = 0; col < m.getBufferWidth(); col++) {
<ide> p.setLocation(col * (charBound.getWidth() + 1),
<ide> (lineMetrics.getAscent() * (line + 1)) +
<ide> (line * (lineMetrics.getDescent() + lineMetrics.getLeading())));
<add>
<ide> g2d.drawString("" + m.getChar(line, col).getDisplay(), (float)p.getX(), (float)p.getY());
<ide> }
<ide> }
<add>
<add> // Draw an underscore cursor
<add> p.setLocation(m.cursor().column() * (charBound.getWidth() + 1),
<add> (lineMetrics.getAscent() * (m.cursor().row() + 1)) +
<add> (m.cursor().row() * (lineMetrics.getDescent() + lineMetrics.getLeading())));
<add> Rectangle2D cursorRect = new Rectangle2D.Double(p.getX(), p.getY(), charBound.getWidth(), 2);
<add> g2d.fill(cursorRect);
<ide> }
<ide>
<ide> public Dimension getPreferredSize(TerminalModel m) {
<ide> return new Dimension(200, 150);
<ide> } else {
<ide> return getBufferSize(m, getFont().deriveFont(6.0f));
<add> }
<add> }
<add>
<add>
<add> protected Font calculateFont(Graphics2D g2d, TerminalModel m) {
<add> Font ret = getFont();
<add> Rectangle bounds = g2d.getClipBounds();
<add> if (bounds != null && (scaleFont || stretchFont)) {
<add> // Given the height / width of the buffer, set the font size.
<add> Rectangle2D.Double idealCharSize =
<add> new Rectangle2D.Double(0d, 0d,
<add> (bounds.getWidth() / m.getBufferWidth()) - 1,
<add> (bounds.getHeight() / m.getBufferHeight()));
<add> if (scaleFont) {
<add> Font reference = Font.decode(getFont().getFontName() + "-" + getStyle(getFont()) + "-12").deriveFont(new AffineTransform());
<add>
<add>
<add> Rectangle2D charSize = g2d.getFontMetrics(reference).getStringBounds("M", g2d);
<add>
<add> float targetPt = (float)(idealCharSize.getWidth() / charSize.getWidth());
<add> targetPt = (float)Math.round(targetPt * reference.getSize2D() * 10) / 10.0f;
<add> ret = reference.deriveFont(targetPt);
<add> }
<add>
<add> if (stretchFont) {
<add> double scaley = idealCharSize.getHeight() / g2d.getFontMetrics(ret).getLineMetrics("Mq", g2d).getHeight();
<add> AffineTransform scaleTransform = new AffineTransform();
<add> scaleTransform.setToScale(1.0, scaley);
<add> ret = ret.deriveFont(scaleTransform);
<add> }
<add> }
<add> return ret;
<add> }
<add>
<add>
<add> private String getStyle(Font f) {
<add> if (f.getStyle() == Font.PLAIN) {
<add> return "plain";
<add> } else if (f.getStyle() == Font.BOLD) {
<add> return "bold";
<add> } else if (f.getStyle() == Font.ITALIC) {
<add> return "italic";
<add> } else {
<add> return "bolditalic";
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 4fe81bcd9386ab6c7fc7dd60a9b12d5b405d7954 | 0 | mcdan/sling,headwirecom/sling,ist-dresden/sling,mmanski/sling,labertasch/sling,tyge68/sling,awadheshv/sling,ist-dresden/sling,headwirecom/sling,ieb/sling,mcdan/sling,tmaret/sling,awadheshv/sling,trekawek/sling,awadheshv/sling,tyge68/sling,wimsymons/sling,vladbailescu/sling,labertasch/sling,vladbailescu/sling,mmanski/sling,JEBailey/sling,tyge68/sling,ieb/sling,tmaret/sling,JEBailey/sling,trekawek/sling,tmaret/sling,tteofili/sling,mikibrv/sling,anchela/sling,vladbailescu/sling,Nimco/sling,roele/sling,roele/sling,roele/sling,mikibrv/sling,labertasch/sling,ist-dresden/sling,tteofili/sling,mikibrv/sling,wimsymons/sling,headwirecom/sling,mmanski/sling,JEBailey/sling,cleliameneghin/sling,Nimco/sling,trekawek/sling,tteofili/sling,tyge68/sling,ieb/sling,mmanski/sling,trekawek/sling,Nimco/sling,ist-dresden/sling,wimsymons/sling,cleliameneghin/sling,mikibrv/sling,wimsymons/sling,wimsymons/sling,mmanski/sling,mcdan/sling,awadheshv/sling,Nimco/sling,tyge68/sling,tteofili/sling,ist-dresden/sling,mcdan/sling,mcdan/sling,tyge68/sling,mikibrv/sling,labertasch/sling,ieb/sling,tteofili/sling,trekawek/sling,labertasch/sling,ieb/sling,tteofili/sling,cleliameneghin/sling,headwirecom/sling,cleliameneghin/sling,awadheshv/sling,mmanski/sling,anchela/sling,ieb/sling,roele/sling,headwirecom/sling,anchela/sling,roele/sling,tmaret/sling,anchela/sling,awadheshv/sling,wimsymons/sling,anchela/sling,cleliameneghin/sling,vladbailescu/sling,mcdan/sling,vladbailescu/sling,JEBailey/sling,JEBailey/sling,trekawek/sling,Nimco/sling,tmaret/sling,mikibrv/sling,Nimco/sling | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.jcr.resource;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.StringTokenizer;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.jcr.resource.internal.helper.LazyInputStream;
/**
* The <code>JcrResourceUtil</code> class provides helper methods used
* throughout this bundle.
*
* @deprecated Use the Resource API instead.
*/
@Deprecated
public class JcrResourceUtil {
/**
* Helper method to execute a JCR query.
*
* @param session the session
* @param query the query
* @param language the language
* @return the query's result
* @throws RepositoryException if the {@link QueryManager} cannot be retrieved
*/
public static QueryResult query(Session session, String query,
String language) throws RepositoryException {
QueryManager qManager = session.getWorkspace().getQueryManager();
Query q = qManager.createQuery(query, language);
return q.execute();
}
/**
* Converts a JCR Value to a corresponding Java Object
*
* @param value the JCR Value to convert
* @return the Java Object
* @throws RepositoryException if the value cannot be converted
*/
public static Object toJavaObject(Value value) throws RepositoryException {
switch (value.getType()) {
case PropertyType.DECIMAL:
return value.getDecimal();
case PropertyType.BINARY:
return new LazyInputStream(value);
case PropertyType.BOOLEAN:
return value.getBoolean();
case PropertyType.DATE:
return value.getDate();
case PropertyType.DOUBLE:
return value.getDouble();
case PropertyType.LONG:
return value.getLong();
case PropertyType.NAME: // fall through
case PropertyType.PATH: // fall through
case PropertyType.REFERENCE: // fall through
case PropertyType.STRING: // fall through
case PropertyType.UNDEFINED: // not actually expected
default: // not actually expected
return value.getString();
}
}
/**
* Converts the value(s) of a JCR Property to a corresponding Java Object.
* If the property has multiple values the result is an array of Java
* Objects representing the converted values of the property.
*
* @param property the property to be converted to the corresponding Java Object
* @throws RepositoryException if the conversion cannot take place
* @return the Object resulting from the conversion
*/
public static Object toJavaObject(Property property)
throws RepositoryException {
// multi-value property: return an array of values
if (property.isMultiple()) {
Value[] values = property.getValues();
final Object firstValue = values.length > 0 ? toJavaObject(values[0]) : null;
final Object[] result;
if ( firstValue instanceof Boolean ) {
result = new Boolean[values.length];
} else if ( firstValue instanceof Calendar ) {
result = new Calendar[values.length];
} else if ( firstValue instanceof Double ) {
result = new Double[values.length];
} else if ( firstValue instanceof Long ) {
result = new Long[values.length];
} else if ( firstValue instanceof BigDecimal) {
result = new BigDecimal[values.length];
} else if ( firstValue instanceof InputStream) {
result = new Object[values.length];
} else {
result = new String[values.length];
}
for (int i = 0; i < values.length; i++) {
Value value = values[i];
if (value != null) {
result[i] = toJavaObject(value);
}
}
return result;
}
// single value property
return toJavaObject(property.getValue());
}
/**
* Creates a {@link javax.jcr.Value JCR Value} for the given object with
* the given Session.
* Selects the the {@link javax.jcr.PropertyType PropertyType} according
* the instance of the object's Class
*
* @param value object
* @param session to create value for
* @return the value or null if not convertible to a valid PropertyType
* @throws RepositoryException in case of error, accessing the Repository
*/
public static Value createValue(final Object value, final Session session)
throws RepositoryException {
Value val;
ValueFactory fac = session.getValueFactory();
if(value instanceof Calendar) {
val = fac.createValue((Calendar)value);
} else if (value instanceof InputStream) {
val = fac.createValue(fac.createBinary((InputStream)value));
} else if (value instanceof Node) {
val = fac.createValue((Node)value);
} else if (value instanceof BigDecimal) {
val = fac.createValue((BigDecimal)value);
} else if (value instanceof Long) {
val = fac.createValue((Long)value);
} else if (value instanceof Short) {
val = fac.createValue((Short)value);
} else if (value instanceof Integer) {
val = fac.createValue((Integer)value);
} else if (value instanceof Number) {
val = fac.createValue(((Number)value).doubleValue());
} else if (value instanceof Boolean) {
val = fac.createValue((Boolean) value);
} else if ( value instanceof String ) {
val = fac.createValue((String)value);
} else {
val = null;
}
return val;
}
/**
* Sets the value of the property.
* Selects the {@link javax.jcr.PropertyType PropertyType} according
* to the instance of the object's class.
* @param node The node where the property will be set on.
* @param propertyName The name of the property.
* @param propertyValue The value for the property.
* @throws RepositoryException if the property cannot be set
*/
public static void setProperty(final Node node,
final String propertyName,
final Object propertyValue)
throws RepositoryException {
if ( propertyValue == null ) {
node.setProperty(propertyName, (String)null);
} else if ( propertyValue.getClass().isArray() ) {
final int length = Array.getLength(propertyValue);
final Value[] setValues = new Value[length];
for(int i=0; i<length; i++) {
final Object value = Array.get(propertyValue, i);
setValues[i] = createValue(value, node.getSession());
}
node.setProperty(propertyName, setValues);
} else {
node.setProperty(propertyName, createValue(propertyValue, node.getSession()));
}
}
/**
* Helper method, which returns the given resource type as returned from the
* {@link org.apache.sling.api.resource.Resource#getResourceType()} as a
* relative path.
*
* @param type The resource type to be converted into a path
* @return The resource type as a path.
* @deprecated Use {@link ResourceUtil#resourceTypeToPath(String)}
*/
@Deprecated
public static String resourceTypeToPath(String type) {
return type.replaceAll("\\:", "/");
}
/**
* Returns the super type of the given resource type. This is the result of
* adapting the child resource
* {@link JcrResourceConstants#SLING_RESOURCE_SUPER_TYPE_PROPERTY} of the
* <code>Resource</code> addressed by the <code>resourceType</code> to a
* string. If no such child resource exists or if the resource does not
* adapt to a string, this method returns <code>null</code>.
*
* @param resourceResolver The <code>ResourceResolver</code> used to
* access the resource whose path (relative or absolute) is given
* by the <code>resourceType</code> parameter.
* @param resourceType The resource type whose super type is to be returned.
* This type is turned into a path by calling the
* {@link #resourceTypeToPath(String)} method before trying to
* get the resource through the <code>resourceResolver</code>.
* @return the super type of the <code>resourceType</code> or
* <code>null</code> if the resource type does not have a child
* resource
* {@link JcrResourceConstants#SLING_RESOURCE_SUPER_TYPE_PROPERTY}
* adapting to a string.
* @deprecated Use {@link ResourceUtil#getResourceSuperType(ResourceResolver, String)}
*/
@SuppressWarnings("deprecation")
@Deprecated
public static String getResourceSuperType(
ResourceResolver resourceResolver, String resourceType) {
return ResourceUtil.getResourceSuperType(resourceResolver, resourceType);
}
/**
* Returns the resource super type of the given resource. This is either the
* child resource
* {@link JcrResourceConstants#SLING_RESOURCE_SUPER_TYPE_PROPERTY} if the
* given <code>resource</code> adapted to a string or the result of
* calling the {@link #getResourceSuperType(ResourceResolver, String)}
* method on the resource type of the <code>resource</code>.
* <p>
* This mechanism allows to specifically set the resource super type on a
* per-resource level overwriting any resource super type hierarchy
* pre-defined by the actual resource type of the resource.
*
* @param resource The <code>Resource</code> whose resource super type is
* requested.
* @return The resource super type or <code>null</code> if the algorithm
* described above does not yield a resource super type.
* @deprecated Call {@link ResourceUtil#findResourceSuperType(Resource)}
*/
@SuppressWarnings("deprecation")
@Deprecated
public static String getResourceSuperType(Resource resource) {
String resourceSuperType = resource.getResourceSuperType();
if ( resourceSuperType == null ) {
final ResourceResolver resolver = resource.getResourceResolver();
// try explicit resourceSuperType resource
final String resourceType = resource.getResourceType();
resourceSuperType = ResourceUtil.getResourceSuperType(resolver, resourceType);
}
return resourceSuperType;
}
/**
* Creates or gets the {@link javax.jcr.Node Node} at the given Path.
* In case it has to create the Node all non-existent intermediate path-elements
* will be create with the given intermediate node type and the returned node
* will be created with the given nodeType
*
* @param path to create
* @param intermediateNodeType to use for creation of intermediate nodes (or null)
* @param nodeType to use for creation of the final node (or null)
* @param session to use
* @param autoSave Should save be called when a new node is created?
* @return the Node at path
* @throws RepositoryException in case of exception accessing the Repository
*/
public static Node createPath(String path,
String intermediateNodeType,
String nodeType,
Session session,
boolean autoSave)
throws RepositoryException {
if (path == null || path.length() == 0 || "/".equals(path)) {
return session.getRootNode();
}
// sanitize path if it ends with a slash
if ( path.endsWith("/") ) {
path = path.substring(0, path.length() - 1);
}
if (!session.itemExists(path)) {
String existingPath = findExistingPath(path, session);
String relativePath = null;
Node parentNode = null;
if (existingPath != null) {
parentNode = session.getNode(existingPath);
relativePath = path.substring(existingPath.length() + 1);
} else {
relativePath = path.substring(1);
parentNode = session.getRootNode();
}
return createPath(parentNode,
relativePath,
intermediateNodeType,
nodeType,
autoSave);
} else {
return session.getNode(path);
}
}
/**
* Creates or gets the {@link javax.jcr.Node Node} at the given Path.
* In case it has to create the Node all non-existent intermediate path-elements
* will be create with the given intermediate node type and the returned node
* will be created with the given nodeType
*
* @param parentNode starting node
* @param relativePath to create
* @param intermediateNodeType to use for creation of intermediate nodes (or null)
* @param nodeType to use for creation of the final node (or null)
* @param autoSave Should save be called when a new node is created?
* @return the Node at path
* @throws RepositoryException in case of exception accessing the Repository
*/
public static Node createPath(Node parentNode,
String relativePath,
String intermediateNodeType,
String nodeType,
boolean autoSave)
throws RepositoryException {
if (relativePath == null || relativePath.length() == 0 || "/".equals(relativePath)) {
return parentNode;
}
// sanitize path if it ends with a slash
if ( relativePath.endsWith("/") ) {
relativePath = relativePath.substring(0, relativePath.length() - 1);
}
if (!parentNode.hasNode(relativePath)) {
Session session = parentNode.getSession();
String path = parentNode.getPath() + "/" + relativePath;
String existingPath = findExistingPath(path, session);
if (existingPath != null) {
parentNode = session.getNode(existingPath);
relativePath = path.substring(existingPath.length() + 1);
}
Node node = parentNode;
int pos = relativePath.lastIndexOf('/');
if ( pos != -1 ) {
final StringTokenizer st = new StringTokenizer(relativePath.substring(0, pos), "/");
while ( st.hasMoreTokens() ) {
final String token = st.nextToken();
if ( !node.hasNode(token) ) {
try {
if ( intermediateNodeType != null ) {
node.addNode(token, intermediateNodeType);
} else {
node.addNode(token);
}
if ( autoSave ) node.getSession().save();
} catch (RepositoryException re) {
// we ignore this as this folder might be created from a different task
node.refresh(false);
}
}
node = node.getNode(token);
}
relativePath = relativePath.substring(pos + 1);
}
if ( !node.hasNode(relativePath) ) {
if ( nodeType != null ) {
node.addNode(relativePath, nodeType);
} else {
node.addNode(relativePath);
}
if ( autoSave ) node.getSession().save();
}
return node.getNode(relativePath);
} else {
return parentNode.getNode(relativePath);
}
}
private static String findExistingPath(String path, Session session)
throws RepositoryException {
//find the parent that exists
// we can start from the youngest child in tree
int currentIndex = path.lastIndexOf('/');
String temp = path;
String existingPath = null;
while (currentIndex > 0) {
temp = temp.substring(0, currentIndex);
//break when first existing parent is found
if (session.itemExists(temp)) {
existingPath = temp;
break;
}
currentIndex = temp.lastIndexOf("/");
}
return existingPath;
}
}
| bundles/jcr/resource/src/main/java/org/apache/sling/jcr/resource/JcrResourceUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.jcr.resource;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.StringTokenizer;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.jcr.resource.internal.helper.LazyInputStream;
/**
* The <code>JcrResourceUtil</code> class provides helper methods used
* throughout this bundle.
*/
public class JcrResourceUtil {
/**
* Helper method to execute a JCR query.
*
* @param session the session
* @param query the query
* @param language the language
* @return the query's result
* @throws RepositoryException if the {@link QueryManager} cannot be retrieved
*/
public static QueryResult query(Session session, String query,
String language) throws RepositoryException {
QueryManager qManager = session.getWorkspace().getQueryManager();
Query q = qManager.createQuery(query, language);
return q.execute();
}
/**
* Converts a JCR Value to a corresponding Java Object
*
* @param value the JCR Value to convert
* @return the Java Object
* @throws RepositoryException if the value cannot be converted
*/
public static Object toJavaObject(Value value) throws RepositoryException {
switch (value.getType()) {
case PropertyType.DECIMAL:
return value.getDecimal();
case PropertyType.BINARY:
return new LazyInputStream(value);
case PropertyType.BOOLEAN:
return value.getBoolean();
case PropertyType.DATE:
return value.getDate();
case PropertyType.DOUBLE:
return value.getDouble();
case PropertyType.LONG:
return value.getLong();
case PropertyType.NAME: // fall through
case PropertyType.PATH: // fall through
case PropertyType.REFERENCE: // fall through
case PropertyType.STRING: // fall through
case PropertyType.UNDEFINED: // not actually expected
default: // not actually expected
return value.getString();
}
}
/**
* Converts the value(s) of a JCR Property to a corresponding Java Object.
* If the property has multiple values the result is an array of Java
* Objects representing the converted values of the property.
*
* @param property the property to be converted to the corresponding Java Object
* @throws RepositoryException if the conversion cannot take place
* @return the Object resulting from the conversion
*/
public static Object toJavaObject(Property property)
throws RepositoryException {
// multi-value property: return an array of values
if (property.isMultiple()) {
Value[] values = property.getValues();
final Object firstValue = values.length > 0 ? toJavaObject(values[0]) : null;
final Object[] result;
if ( firstValue instanceof Boolean ) {
result = new Boolean[values.length];
} else if ( firstValue instanceof Calendar ) {
result = new Calendar[values.length];
} else if ( firstValue instanceof Double ) {
result = new Double[values.length];
} else if ( firstValue instanceof Long ) {
result = new Long[values.length];
} else if ( firstValue instanceof BigDecimal) {
result = new BigDecimal[values.length];
} else if ( firstValue instanceof InputStream) {
result = new Object[values.length];
} else {
result = new String[values.length];
}
for (int i = 0; i < values.length; i++) {
Value value = values[i];
if (value != null) {
result[i] = toJavaObject(value);
}
}
return result;
}
// single value property
return toJavaObject(property.getValue());
}
/**
* Creates a {@link javax.jcr.Value JCR Value} for the given object with
* the given Session.
* Selects the the {@link javax.jcr.PropertyType PropertyType} according
* the instance of the object's Class
*
* @param value object
* @param session to create value for
* @return the value or null if not convertible to a valid PropertyType
* @throws RepositoryException in case of error, accessing the Repository
*/
public static Value createValue(final Object value, final Session session)
throws RepositoryException {
Value val;
ValueFactory fac = session.getValueFactory();
if(value instanceof Calendar) {
val = fac.createValue((Calendar)value);
} else if (value instanceof InputStream) {
val = fac.createValue(fac.createBinary((InputStream)value));
} else if (value instanceof Node) {
val = fac.createValue((Node)value);
} else if (value instanceof BigDecimal) {
val = fac.createValue((BigDecimal)value);
} else if (value instanceof Long) {
val = fac.createValue((Long)value);
} else if (value instanceof Short) {
val = fac.createValue((Short)value);
} else if (value instanceof Integer) {
val = fac.createValue((Integer)value);
} else if (value instanceof Number) {
val = fac.createValue(((Number)value).doubleValue());
} else if (value instanceof Boolean) {
val = fac.createValue((Boolean) value);
} else if ( value instanceof String ) {
val = fac.createValue((String)value);
} else {
val = null;
}
return val;
}
/**
* Sets the value of the property.
* Selects the {@link javax.jcr.PropertyType PropertyType} according
* to the instance of the object's class.
* @param node The node where the property will be set on.
* @param propertyName The name of the property.
* @param propertyValue The value for the property.
* @throws RepositoryException if the property cannot be set
*/
public static void setProperty(final Node node,
final String propertyName,
final Object propertyValue)
throws RepositoryException {
if ( propertyValue == null ) {
node.setProperty(propertyName, (String)null);
} else if ( propertyValue.getClass().isArray() ) {
final int length = Array.getLength(propertyValue);
final Value[] setValues = new Value[length];
for(int i=0; i<length; i++) {
final Object value = Array.get(propertyValue, i);
setValues[i] = createValue(value, node.getSession());
}
node.setProperty(propertyName, setValues);
} else {
node.setProperty(propertyName, createValue(propertyValue, node.getSession()));
}
}
/**
* Helper method, which returns the given resource type as returned from the
* {@link org.apache.sling.api.resource.Resource#getResourceType()} as a
* relative path.
*
* @param type The resource type to be converted into a path
* @return The resource type as a path.
* @deprecated Use {@link ResourceUtil#resourceTypeToPath(String)}
*/
@Deprecated
public static String resourceTypeToPath(String type) {
return type.replaceAll("\\:", "/");
}
/**
* Returns the super type of the given resource type. This is the result of
* adapting the child resource
* {@link JcrResourceConstants#SLING_RESOURCE_SUPER_TYPE_PROPERTY} of the
* <code>Resource</code> addressed by the <code>resourceType</code> to a
* string. If no such child resource exists or if the resource does not
* adapt to a string, this method returns <code>null</code>.
*
* @param resourceResolver The <code>ResourceResolver</code> used to
* access the resource whose path (relative or absolute) is given
* by the <code>resourceType</code> parameter.
* @param resourceType The resource type whose super type is to be returned.
* This type is turned into a path by calling the
* {@link #resourceTypeToPath(String)} method before trying to
* get the resource through the <code>resourceResolver</code>.
* @return the super type of the <code>resourceType</code> or
* <code>null</code> if the resource type does not have a child
* resource
* {@link JcrResourceConstants#SLING_RESOURCE_SUPER_TYPE_PROPERTY}
* adapting to a string.
* @deprecated Use {@link ResourceUtil#getResourceSuperType(ResourceResolver, String)}
*/
@SuppressWarnings("deprecation")
@Deprecated
public static String getResourceSuperType(
ResourceResolver resourceResolver, String resourceType) {
return ResourceUtil.getResourceSuperType(resourceResolver, resourceType);
}
/**
* Returns the resource super type of the given resource. This is either the
* child resource
* {@link JcrResourceConstants#SLING_RESOURCE_SUPER_TYPE_PROPERTY} if the
* given <code>resource</code> adapted to a string or the result of
* calling the {@link #getResourceSuperType(ResourceResolver, String)}
* method on the resource type of the <code>resource</code>.
* <p>
* This mechanism allows to specifically set the resource super type on a
* per-resource level overwriting any resource super type hierarchy
* pre-defined by the actual resource type of the resource.
*
* @param resource The <code>Resource</code> whose resource super type is
* requested.
* @return The resource super type or <code>null</code> if the algorithm
* described above does not yield a resource super type.
* @deprecated Call {@link ResourceUtil#findResourceSuperType(Resource)}
*/
@SuppressWarnings("deprecation")
@Deprecated
public static String getResourceSuperType(Resource resource) {
String resourceSuperType = resource.getResourceSuperType();
if ( resourceSuperType == null ) {
final ResourceResolver resolver = resource.getResourceResolver();
// try explicit resourceSuperType resource
final String resourceType = resource.getResourceType();
resourceSuperType = ResourceUtil.getResourceSuperType(resolver, resourceType);
}
return resourceSuperType;
}
/**
* Creates or gets the {@link javax.jcr.Node Node} at the given Path.
* In case it has to create the Node all non-existent intermediate path-elements
* will be create with the given intermediate node type and the returned node
* will be created with the given nodeType
*
* @param path to create
* @param intermediateNodeType to use for creation of intermediate nodes (or null)
* @param nodeType to use for creation of the final node (or null)
* @param session to use
* @param autoSave Should save be called when a new node is created?
* @return the Node at path
* @throws RepositoryException in case of exception accessing the Repository
*/
public static Node createPath(String path,
String intermediateNodeType,
String nodeType,
Session session,
boolean autoSave)
throws RepositoryException {
if (path == null || path.length() == 0 || "/".equals(path)) {
return session.getRootNode();
}
// sanitize path if it ends with a slash
if ( path.endsWith("/") ) {
path = path.substring(0, path.length() - 1);
}
if (!session.itemExists(path)) {
String existingPath = findExistingPath(path, session);
String relativePath = null;
Node parentNode = null;
if (existingPath != null) {
parentNode = session.getNode(existingPath);
relativePath = path.substring(existingPath.length() + 1);
} else {
relativePath = path.substring(1);
parentNode = session.getRootNode();
}
return createPath(parentNode,
relativePath,
intermediateNodeType,
nodeType,
autoSave);
} else {
return session.getNode(path);
}
}
/**
* Creates or gets the {@link javax.jcr.Node Node} at the given Path.
* In case it has to create the Node all non-existent intermediate path-elements
* will be create with the given intermediate node type and the returned node
* will be created with the given nodeType
*
* @param parentNode starting node
* @param relativePath to create
* @param intermediateNodeType to use for creation of intermediate nodes (or null)
* @param nodeType to use for creation of the final node (or null)
* @param autoSave Should save be called when a new node is created?
* @return the Node at path
* @throws RepositoryException in case of exception accessing the Repository
*/
public static Node createPath(Node parentNode,
String relativePath,
String intermediateNodeType,
String nodeType,
boolean autoSave)
throws RepositoryException {
if (relativePath == null || relativePath.length() == 0 || "/".equals(relativePath)) {
return parentNode;
}
// sanitize path if it ends with a slash
if ( relativePath.endsWith("/") ) {
relativePath = relativePath.substring(0, relativePath.length() - 1);
}
if (!parentNode.hasNode(relativePath)) {
Session session = parentNode.getSession();
String path = parentNode.getPath() + "/" + relativePath;
String existingPath = findExistingPath(path, session);
if (existingPath != null) {
parentNode = session.getNode(existingPath);
relativePath = path.substring(existingPath.length() + 1);
}
Node node = parentNode;
int pos = relativePath.lastIndexOf('/');
if ( pos != -1 ) {
final StringTokenizer st = new StringTokenizer(relativePath.substring(0, pos), "/");
while ( st.hasMoreTokens() ) {
final String token = st.nextToken();
if ( !node.hasNode(token) ) {
try {
if ( intermediateNodeType != null ) {
node.addNode(token, intermediateNodeType);
} else {
node.addNode(token);
}
if ( autoSave ) node.getSession().save();
} catch (RepositoryException re) {
// we ignore this as this folder might be created from a different task
node.refresh(false);
}
}
node = node.getNode(token);
}
relativePath = relativePath.substring(pos + 1);
}
if ( !node.hasNode(relativePath) ) {
if ( nodeType != null ) {
node.addNode(relativePath, nodeType);
} else {
node.addNode(relativePath);
}
if ( autoSave ) node.getSession().save();
}
return node.getNode(relativePath);
} else {
return parentNode.getNode(relativePath);
}
}
private static String findExistingPath(String path, Session session)
throws RepositoryException {
//find the parent that exists
// we can start from the youngest child in tree
int currentIndex = path.lastIndexOf('/');
String temp = path;
String existingPath = null;
while (currentIndex > 0) {
temp = temp.substring(0, currentIndex);
//break when first existing parent is found
if (session.itemExists(temp)) {
existingPath = temp;
break;
}
currentIndex = temp.lastIndexOf("/");
}
return existingPath;
}
}
| SLING-5513 : Deprecate JcrResourceUtil
git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@1729982 13f79535-47bb-0310-9956-ffa450edef68
| bundles/jcr/resource/src/main/java/org/apache/sling/jcr/resource/JcrResourceUtil.java | SLING-5513 : Deprecate JcrResourceUtil | <ide><path>undles/jcr/resource/src/main/java/org/apache/sling/jcr/resource/JcrResourceUtil.java
<ide> /**
<ide> * The <code>JcrResourceUtil</code> class provides helper methods used
<ide> * throughout this bundle.
<add> *
<add> * @deprecated Use the Resource API instead.
<ide> */
<add>@Deprecated
<ide> public class JcrResourceUtil {
<ide>
<ide> /** |
|
Java | apache-2.0 | 3bdfeae8f1749919d674117543929579d490db5c | 0 | OpenHFT/Chronicle-Map | /*
* Copyright 2014 Higher Frequency Trading
*
* http://www.higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.map.fromdocs;
import net.openhft.chronicle.map.ChronicleMap;
import net.openhft.chronicle.map.ChronicleMapBuilder;
import net.openhft.chronicle.map.ReadContext;
import net.openhft.chronicle.map.WriteContext;
import net.openhft.lang.model.DataValueClasses;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import static org.junit.Assert.assertEquals;
/**
* These code fragments will appear in an article on OpenHFT. These tests to ensure that the examples compile
* and behave as expected.
*/
public class OpenJDKAndHashMapExamplesTest {
private static final SimpleDateFormat YYYYMMDD = new SimpleDateFormat("yyyyMMdd");
private static final String TMP = System.getProperty("java.io.tmpdir");
private static long parseYYYYMMDD(String s) {
try {
return YYYYMMDD.parse(s).getTime();
} catch (ParseException e) {
throw new AssertionError(e);
}
}
@Test
public void bondExample() throws IOException, InterruptedException {
File file = new File(TMP + "/chm-myBondPortfolioCHM-" + System.nanoTime());
file.deleteOnExit();
ChronicleMap<String, BondVOInterface> chm = ChronicleMapBuilder
.of(String.class, DataValueClasses.directClassFor(BondVOInterface.class))
.keySize(10)
.createPersistedTo(file);
BondVOInterface bondVO = chm.newValueInstance();
try (WriteContext wc = chm.acquireUsingLocked("369604103", bondVO)) {
bondVO.setIssueDate(parseYYYYMMDD("20130915"));
bondVO.setMaturityDate(parseYYYYMMDD("20140915"));
bondVO.setCoupon(5.0 / 100); // 5.0%
BondVOInterface.MarketPx mpx930 = bondVO.getMarketPxIntraDayHistoryAt(0);
mpx930.setAskPx(109.2);
mpx930.setBidPx(106.9);
BondVOInterface.MarketPx mpx1030 = bondVO.getMarketPxIntraDayHistoryAt(1);
mpx1030.setAskPx(109.7);
mpx1030.setBidPx(107.6);
}
ChronicleMap<String, BondVOInterface> chmB = ChronicleMapBuilder
.of(String.class, BondVOInterface.class)
.keySize(10)
.createPersistedTo(file);
// ZERO Copy but creates a new off heap reference each time
// our reusable, mutable off heap reference, generated from the interface.
BondVOInterface bond = chm.newValueInstance();
try (ReadContext rc = chmB.getUsingLocked("369604103", bond)) {
if (rc.present()) {
assertEquals(5.0 / 100, bond.getCoupon(), 0.0);
BondVOInterface.MarketPx mpx930B = bond.getMarketPxIntraDayHistoryAt(0);
assertEquals(109.2, mpx930B.getAskPx(), 0.0);
assertEquals(106.9, mpx930B.getBidPx(), 0.0);
BondVOInterface.MarketPx mpx1030B = bond.getMarketPxIntraDayHistoryAt(1);
assertEquals(109.7, mpx1030B.getAskPx(), 0.0);
assertEquals(107.6, mpx1030B.getBidPx(), 0.0);
}
}
// lookup the key and give me a reference I can update in a thread safe way.
try (WriteContext wc = chm.acquireUsingLocked("369604103", bond)) {
// found a key and bond has been set
// get directly without touching the rest of the record.
long _matDate = bond.getMaturityDate();
// write just this field, again we need to assume we are the only writer.
bond.setMaturityDate(parseYYYYMMDD("20440315"));
//demo of how to do OpenHFT off-heap array[ ] processing
int tradingHour = 2; //current trading hour intra-day
BondVOInterface.MarketPx mktPx = bond.getMarketPxIntraDayHistoryAt(tradingHour);
if (mktPx.getCallPx() < 103.50) {
mktPx.setParPx(100.50);
mktPx.setAskPx(102.00);
mktPx.setBidPx(99.00);
// setMarketPxIntraDayHistoryAt is not needed as we are using zero copy,
// the original has been changed.
}
}
// bond will be full of default values and zero length string the first time.
// from this point, all operations are completely record/entry local,
// no other resource is involved.
// now perform thread safe operations on my reference
bond.addAtomicMaturityDate(16 * 24 * 3600 * 1000L); //20440331
bond.addAtomicCoupon(-1 * bond.getCoupon()); //MT-safe! now a Zero Coupon Bond.
// cleanup.
chm.close();
chmB.close();
file.delete();
}
}
| src/test/java/net/openhft/chronicle/map/fromdocs/OpenJDKAndHashMapExamplesTest.java | /*
* Copyright 2014 Higher Frequency Trading
*
* http://www.higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.map.fromdocs;
import net.openhft.chronicle.map.ChronicleMap;
import net.openhft.chronicle.map.ChronicleMapBuilder;
import net.openhft.chronicle.map.ReadContext;
import net.openhft.chronicle.map.WriteContext;
import net.openhft.lang.model.DataValueClasses;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import static org.junit.Assert.assertEquals;
/**
* These code fragments will appear in an article on OpenHFT. These tests to ensure that the examples compile
* and behave as expected.
*/
public class OpenJDKAndHashMapExamplesTest {
private static final SimpleDateFormat YYYYMMDD = new SimpleDateFormat("yyyyMMdd");
private static final String TMP = System.getProperty("java.io.tmpdir");
private static long parseYYYYMMDD(String s) {
try {
return YYYYMMDD.parse(s).getTime();
} catch (ParseException e) {
throw new AssertionError(e);
}
}
@Test
public void bondExample() throws IOException, InterruptedException {
File file = new File(TMP + "/chm-myBondPortfolioCHM-" + System.nanoTime());
file.deleteOnExit();
ChronicleMap<String, BondVOInterface> chm = ChronicleMapBuilder
.of(String.class, DataValueClasses.directClassFor(BondVOInterface.class))
.keySize(10)
.createPersistedTo(file);
BondVOInterface bondVO = DataValueClasses.newDirectReference(BondVOInterface.class);
try (WriteContext wc = chm.acquireUsingLocked("369604103", bondVO)) {
bondVO.setIssueDate(parseYYYYMMDD("20130915"));
bondVO.setMaturityDate(parseYYYYMMDD("20140915"));
bondVO.setCoupon(5.0 / 100); // 5.0%
BondVOInterface.MarketPx mpx930 = bondVO.getMarketPxIntraDayHistoryAt(0);
mpx930.setAskPx(109.2);
mpx930.setBidPx(106.9);
BondVOInterface.MarketPx mpx1030 = bondVO.getMarketPxIntraDayHistoryAt(1);
mpx1030.setAskPx(109.7);
mpx1030.setBidPx(107.6);
}
ChronicleMap<String, BondVOInterface> chmB = ChronicleMapBuilder
.of(String.class, BondVOInterface.class)
.keySize(10)
.createPersistedTo(file);
// ZERO Copy but creates a new off heap reference each time
// our reusable, mutable off heap reference, generated from the interface.
BondVOInterface bond = DataValueClasses.newDirectReference(BondVOInterface.class);
try (ReadContext rc = chmB.getUsingLocked("369604103", bond)) {
if (rc.present()) {
assertEquals(5.0 / 100, bond.getCoupon(), 0.0);
BondVOInterface.MarketPx mpx930B = bond.getMarketPxIntraDayHistoryAt(0);
assertEquals(109.2, mpx930B.getAskPx(), 0.0);
assertEquals(106.9, mpx930B.getBidPx(), 0.0);
BondVOInterface.MarketPx mpx1030B = bond.getMarketPxIntraDayHistoryAt(1);
assertEquals(109.7, mpx1030B.getAskPx(), 0.0);
assertEquals(107.6, mpx1030B.getBidPx(), 0.0);
}
}
// lookup the key and give me a reference I can update in a thread safe way.
try (WriteContext wc = chm.acquireUsingLocked("369604103", bond)) {
// found a key and bond has been set
// get directly without touching the rest of the record.
long _matDate = bond.getMaturityDate();
// write just this field, again we need to assume we are the only writer.
bond.setMaturityDate(parseYYYYMMDD("20440315"));
//demo of how to do OpenHFT off-heap array[ ] processing
int tradingHour = 2; //current trading hour intra-day
BondVOInterface.MarketPx mktPx = bond.getMarketPxIntraDayHistoryAt(tradingHour);
if (mktPx.getCallPx() < 103.50) {
mktPx.setParPx(100.50);
mktPx.setAskPx(102.00);
mktPx.setBidPx(99.00);
// setMarketPxIntraDayHistoryAt is not needed as we are using zero copy,
// the original has been changed.
}
}
// bond will be full of default values and zero length string the first time.
// from this point, all operations are completely record/entry local,
// no other resource is involved.
// now perform thread safe operations on my reference
bond.addAtomicMaturityDate(16 * 24 * 3600 * 1000L); //20440331
bond.addAtomicCoupon(-1 * bond.getCoupon()); //MT-safe! now a Zero Coupon Bond.
// cleanup.
chm.close();
chmB.close();
file.delete();
}
}
| updated to use - chm.newValueInstance();
| src/test/java/net/openhft/chronicle/map/fromdocs/OpenJDKAndHashMapExamplesTest.java | updated to use - chm.newValueInstance(); | <ide><path>rc/test/java/net/openhft/chronicle/map/fromdocs/OpenJDKAndHashMapExamplesTest.java
<ide> .keySize(10)
<ide> .createPersistedTo(file);
<ide>
<del> BondVOInterface bondVO = DataValueClasses.newDirectReference(BondVOInterface.class);
<add> BondVOInterface bondVO = chm.newValueInstance();
<ide> try (WriteContext wc = chm.acquireUsingLocked("369604103", bondVO)) {
<ide> bondVO.setIssueDate(parseYYYYMMDD("20130915"));
<ide> bondVO.setMaturityDate(parseYYYYMMDD("20140915"));
<ide>
<ide> // ZERO Copy but creates a new off heap reference each time
<ide> // our reusable, mutable off heap reference, generated from the interface.
<del> BondVOInterface bond = DataValueClasses.newDirectReference(BondVOInterface.class);
<add> BondVOInterface bond = chm.newValueInstance();
<ide> try (ReadContext rc = chmB.getUsingLocked("369604103", bond)) {
<ide> if (rc.present()) {
<ide> assertEquals(5.0 / 100, bond.getCoupon(), 0.0); |
|
Java | mit | 1b387221283f73d5a7ee7146d741df73595e45a4 | 0 | opentdc/resources-service-opencrx | /**
* The MIT License (MIT)
*
* Copyright (c) 2015 Arbalo AG
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.opentdc.resources.opencrx;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jmi.reflect.DuplicateException;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import org.opencrx.kernel.account1.cci2.ContactQuery;
import org.opencrx.kernel.account1.jmi1.Contact;
import org.opencrx.kernel.activity1.cci2.ResourceQuery;
import org.opencrx.kernel.activity1.jmi1.Resource;
import org.opencrx.kernel.utils.Utils;
import org.openmdx.base.exception.ServiceException;
import org.openmdx.base.persistence.cci.Queries;
import org.openmdx.base.rest.spi.Facades;
import org.openmdx.base.rest.spi.Query_2Facade;
import org.opentdc.opencrx.AbstractOpencrxServiceProvider;
import org.opentdc.opencrx.ActivitiesHelper;
import org.opentdc.resources.ResourceModel;
import org.opentdc.resources.ServiceProvider;
import org.opentdc.service.exception.InternalServerErrorException;
import org.opentdc.service.exception.NotFoundException;
/**
* OpencrxServiceProvider
*
*/
public class OpencrxServiceProvider extends AbstractOpencrxServiceProvider implements ServiceProvider {
protected static final Logger logger = Logger.getLogger(OpencrxServiceProvider.class.getName());
/**
* Constructor.
*
* @param context
* @param prefix
* @throws ServiceException
* @throws NamingException
*/
public OpencrxServiceProvider(
ServletContext context,
String prefix
) throws ServiceException, NamingException {
super(context, prefix);
}
/**
* Map resource to resource model.
*
* @param resource
* @return
*/
protected ResourceModel newResourceModel(
Resource resource
) {
ResourceModel _r = new ResourceModel();
_r.setName(resource.getName());
if(resource.getContact() != null) {
_r.setFirstName(resource.getContact().getFirstName());
_r.setLastName(resource.getContact().getLastName());
}
return _r;
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#listResources(java.lang.String, java.lang.String, long, long)
*/
@Override
public List<ResourceModel> listResources(
String queryType,
String query,
int position,
int size
) {
try {
PersistenceManager pm = this.getPersistenceManager();
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Query_2Facade resourcesQueryFacade = Facades.newQuery(null);
resourcesQueryFacade.setQueryType(
queryType == null || queryType.isEmpty()
? "org:opencrx:kernel:activity1:Resource"
: queryType
);
if(query != null && !query.isEmpty()) {
resourcesQueryFacade.setQuery(query);
}
ResourceQuery resourcesQuery = (ResourceQuery)pm.newQuery(
Queries.QUERY_LANGUAGE,
resourcesQueryFacade.getDelegate()
);
resourcesQuery.forAllDisabled().isFalse();
resourcesQuery.orderByName().ascending();
resourcesQuery.thereExistsCategory().equalTo(ActivitiesHelper.RESOURCE_CATEGORY_PROJECT);
List<Resource> resources = activitySegment.getResource(resourcesQuery);
List<ResourceModel> result = new ArrayList<ResourceModel>();
int count = 0;
for(Iterator<Resource> i = resources.listIterator(position); i.hasNext(); ) {
Resource resource = i.next();
result.add(this.newResourceModel(resource));
count++;
if(count > size) {
break;
}
}
return result;
} catch(ServiceException e) {
e.log();
throw new InternalServerErrorException(e.getMessage());
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#createResource(org.opentdc.resources.ResourceModel)
*/
@Override
public ResourceModel createResource(
ResourceModel r
) throws DuplicateException {
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
org.opencrx.kernel.account1.jmi1.Segment accountSegment = this.getAccountSegment();
if(r.getId() != null) {
Resource resource = null;
try {
resource = activitySegment.getResource(r.getId());
} catch(Exception ignore) {}
if(resource != null) {
throw new org.opentdc.service.exception.DuplicateException();
}
}
PersistenceManager pm = this.getPersistenceManager();
Contact contact = null;
// Find contact matching firstName, lastName
{
ContactQuery contactQuery = (ContactQuery)pm.newQuery(Contact.class);
contactQuery.thereExistsLastName().equalTo(r.getLastName());
contactQuery.thereExistsFirstName().equalTo(r.getFirstName());
contactQuery.forAllDisabled().isFalse();
List<Contact> contacts = accountSegment.getAccount(contactQuery);
if(contacts.isEmpty()) {
contact = pm.newInstance(Contact.class);
contact.setFirstName(r.getFirstName());
contact.setLastName(r.getLastName());
try {
pm.currentTransaction().begin();
accountSegment.addAccount(
Utils.getUidAsString(),
contact
);
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
}
} else {
contact = contacts.iterator().next();
}
}
// Create resource
Resource resource = null;
{
resource = pm.newInstance(Resource.class);
if(r.getName() == null || r.getName().isEmpty()) {
if(contact == null) {
resource.setName(r.getLastName() + ", " + r.getFirstName());
} else {
resource.setName(contact.getFullName());
}
} else {
resource.setName(r.getName());
}
resource.setContact(contact);
resource.getCategory().add(ActivitiesHelper.RESOURCE_CATEGORY_PROJECT);
try {
pm.currentTransaction().begin();
activitySegment.addResource(
Utils.getUidAsString(),
resource
);
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
throw new InternalServerErrorException("Unable to create resource");
}
}
return this.newResourceModel(resource);
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#readResource(java.lang.String)
*/
@Override
public ResourceModel readResource(
String id
) throws NotFoundException {
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Resource resource = null;
try {
resource = activitySegment.getResource(id);
} catch(Exception ignore) {}
if(resource == null) {
throw new org.opentdc.service.exception.NotFoundException(id);
} else {
return this.newResourceModel(resource);
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#updateResource(java.lang.String, org.opentdc.resources.ResourceModel)
*/
@Override
public ResourceModel updateResource(
String id,
ResourceModel r
) throws NotFoundException {
PersistenceManager pm = this.getPersistenceManager();
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Resource resource = activitySegment.getResource(id);
if(resource == null) {
throw new org.opentdc.service.exception.NotFoundException(id);
} else {
try {
pm.currentTransaction().begin();
resource.setName(r.getName());
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
throw new InternalServerErrorException("Unable to update resource");
}
return this.newResourceModel(resource);
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#deleteResource(java.lang.String)
*/
@Override
public void deleteResource(
String id
) throws NotFoundException {
PersistenceManager pm = this.getPersistenceManager();
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Resource resource = null;
try {
resource = activitySegment.getResource(id);
} catch(Exception ignore) {}
if(resource == null || Boolean.TRUE.equals(resource.isDisabled())) {
throw new org.opentdc.service.exception.NotFoundException(id);
} else {
try {
pm.currentTransaction().begin();
resource.setDisabled(true);
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
throw new InternalServerErrorException("Unable to delete resource");
}
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#countResources()
*/
@Override
public int countResources(
) {
return this.listResources(
null, // queryType
null, // query
0, // position
Integer.MAX_VALUE // size
).size();
}
}
| src/java/org/opentdc/resources/opencrx/OpencrxServiceProvider.java | /**
* The MIT License (MIT)
*
* Copyright (c) 2015 Arbalo AG
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.opentdc.resources.opencrx;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jmi.reflect.DuplicateException;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import org.opencrx.kernel.account1.cci2.ContactQuery;
import org.opencrx.kernel.account1.jmi1.Contact;
import org.opencrx.kernel.activity1.cci2.ResourceQuery;
import org.opencrx.kernel.activity1.jmi1.Resource;
import org.opencrx.kernel.utils.Utils;
import org.openmdx.base.exception.ServiceException;
import org.openmdx.base.persistence.cci.Queries;
import org.openmdx.base.rest.spi.Facades;
import org.openmdx.base.rest.spi.Query_2Facade;
import org.opentdc.opencrx.AbstractOpencrxServiceProvider;
import org.opentdc.opencrx.ActivitiesHelper;
import org.opentdc.resources.ResourceModel;
import org.opentdc.resources.ServiceProvider;
import org.opentdc.service.exception.InternalServerErrorException;
import org.opentdc.service.exception.NotFoundException;
/**
* OpencrxServiceProvider
*
*/
public class OpencrxServiceProvider extends AbstractOpencrxServiceProvider implements ServiceProvider {
protected static final Logger logger = Logger.getLogger(OpencrxServiceProvider.class.getName());
/**
* Constructor.
*
* @param context
* @param prefix
* @throws ServiceException
* @throws NamingException
*/
public OpencrxServiceProvider(
ServletContext context,
String prefix
) throws ServiceException, NamingException {
super(context, prefix);
}
/**
* Map resource to resource model.
*
* @param resource
* @return
*/
protected ResourceModel newResourceModel(
Resource resource
) {
ResourceModel r = new ResourceModel(resource.refGetPath().getLastSegment().toClassicRepresentation());
r.setXri(resource.refGetPath().toXRI());
r.setName(resource.getName());
if(resource.getContact() != null) {
r.setFirstName(resource.getContact().getFirstName());
r.setLastName(resource.getContact().getLastName());
}
return r;
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#listResources(java.lang.String, java.lang.String, long, long)
*/
@Override
public List<ResourceModel> listResources(
String queryType,
String query,
int position,
int size
) {
try {
PersistenceManager pm = this.getPersistenceManager();
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Query_2Facade resourcesQueryFacade = Facades.newQuery(null);
resourcesQueryFacade.setQueryType(
queryType == null || queryType.isEmpty()
? "org:opencrx:kernel:activity1:Resource"
: queryType
);
if(query != null && !query.isEmpty()) {
resourcesQueryFacade.setQuery(query);
}
ResourceQuery resourcesQuery = (ResourceQuery)pm.newQuery(
Queries.QUERY_LANGUAGE,
resourcesQueryFacade.getDelegate()
);
resourcesQuery.forAllDisabled().isFalse();
resourcesQuery.orderByName().ascending();
resourcesQuery.thereExistsCategory().equalTo(ActivitiesHelper.RESOURCE_CATEGORY_PROJECT);
List<Resource> resources = activitySegment.getResource(resourcesQuery);
List<ResourceModel> result = new ArrayList<ResourceModel>();
int count = 0;
for(Iterator<Resource> i = resources.listIterator(position); i.hasNext(); ) {
Resource resource = i.next();
result.add(this.newResourceModel(resource));
count++;
if(count > size) {
break;
}
}
return result;
} catch(ServiceException e) {
e.log();
throw new InternalServerErrorException(e.getMessage());
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#createResource(org.opentdc.resources.ResourceModel)
*/
@Override
public ResourceModel createResource(
ResourceModel r
) throws DuplicateException {
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
org.opencrx.kernel.account1.jmi1.Segment accountSegment = this.getAccountSegment();
if(r.getId() != null) {
Resource resource = null;
try {
resource = activitySegment.getResource(r.getId());
} catch(Exception ignore) {}
if(resource != null) {
throw new org.opentdc.service.exception.DuplicateException();
}
}
PersistenceManager pm = this.getPersistenceManager();
Contact contact = null;
// Find contact matching firstName, lastName
{
ContactQuery contactQuery = (ContactQuery)pm.newQuery(Contact.class);
contactQuery.thereExistsLastName().equalTo(r.getLastName());
contactQuery.thereExistsFirstName().equalTo(r.getFirstName());
contactQuery.forAllDisabled().isFalse();
List<Contact> contacts = accountSegment.getAccount(contactQuery);
if(contacts.isEmpty()) {
contact = pm.newInstance(Contact.class);
contact.setFirstName(r.getFirstName());
contact.setLastName(r.getLastName());
try {
pm.currentTransaction().begin();
accountSegment.addAccount(
Utils.getUidAsString(),
contact
);
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
}
} else {
contact = contacts.iterator().next();
}
}
// Create resource
Resource resource = null;
{
resource = pm.newInstance(Resource.class);
if(r.getName() == null || r.getName().isEmpty()) {
if(contact == null) {
resource.setName(r.getLastName() + ", " + r.getFirstName());
} else {
resource.setName(contact.getFullName());
}
} else {
resource.setName(r.getName());
}
resource.setContact(contact);
resource.getCategory().add(ActivitiesHelper.RESOURCE_CATEGORY_PROJECT);
try {
pm.currentTransaction().begin();
activitySegment.addResource(
Utils.getUidAsString(),
resource
);
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
throw new InternalServerErrorException("Unable to create resource");
}
}
return this.newResourceModel(resource);
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#readResource(java.lang.String)
*/
@Override
public ResourceModel readResource(
String id
) throws NotFoundException {
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Resource resource = null;
try {
resource = activitySegment.getResource(id);
} catch(Exception ignore) {}
if(resource == null) {
throw new org.opentdc.service.exception.NotFoundException(id);
} else {
return this.newResourceModel(resource);
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#updateResource(java.lang.String, org.opentdc.resources.ResourceModel)
*/
@Override
public ResourceModel updateResource(
String id,
ResourceModel r
) throws NotFoundException {
PersistenceManager pm = this.getPersistenceManager();
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Resource resource = activitySegment.getResource(id);
if(resource == null) {
throw new org.opentdc.service.exception.NotFoundException(id);
} else {
try {
pm.currentTransaction().begin();
resource.setName(r.getName());
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
throw new InternalServerErrorException("Unable to update resource");
}
return this.newResourceModel(resource);
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#deleteResource(java.lang.String)
*/
@Override
public void deleteResource(
String id
) throws NotFoundException {
PersistenceManager pm = this.getPersistenceManager();
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Resource resource = null;
try {
resource = activitySegment.getResource(id);
} catch(Exception ignore) {}
if(resource == null || Boolean.TRUE.equals(resource.isDisabled())) {
throw new org.opentdc.service.exception.NotFoundException(id);
} else {
try {
pm.currentTransaction().begin();
resource.setDisabled(true);
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
throw new InternalServerErrorException("Unable to delete resource");
}
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#countResources()
*/
@Override
public int countResources(
) {
return this.listResources(
null, // queryType
null, // query
0, // position
Integer.MAX_VALUE // size
).size();
}
}
| cleanup of opencrx impl: new constructor, removed xri added name field
| src/java/org/opentdc/resources/opencrx/OpencrxServiceProvider.java | cleanup of opencrx impl: new constructor, removed xri added name field | <ide><path>rc/java/org/opentdc/resources/opencrx/OpencrxServiceProvider.java
<ide> protected ResourceModel newResourceModel(
<ide> Resource resource
<ide> ) {
<del> ResourceModel r = new ResourceModel(resource.refGetPath().getLastSegment().toClassicRepresentation());
<del> r.setXri(resource.refGetPath().toXRI());
<del> r.setName(resource.getName());
<add> ResourceModel _r = new ResourceModel();
<add> _r.setName(resource.getName());
<ide> if(resource.getContact() != null) {
<del> r.setFirstName(resource.getContact().getFirstName());
<del> r.setLastName(resource.getContact().getLastName());
<del> }
<del> return r;
<add> _r.setFirstName(resource.getContact().getFirstName());
<add> _r.setLastName(resource.getContact().getLastName());
<add> }
<add> return _r;
<ide> }
<ide>
<ide> /* (non-Javadoc) |
|
Java | mit | 70ef26954777b63f29d9f6ee473d40d065f97a9a | 0 | dbuxo/CommandHelper,Techcable/CommandHelper,Techcable/CommandHelper,sk89q/CommandHelper,sk89q/CommandHelper,dbuxo/CommandHelper,sk89q/CommandHelper,dbuxo/CommandHelper,dbuxo/CommandHelper,Techcable/CommandHelper,sk89q/CommandHelper,Techcable/CommandHelper |
package com.laytonsmith.tools;
import com.laytonsmith.PureUtilities.ClassLoading.ClassDiscovery;
import com.laytonsmith.abstraction.Implementation;
import com.laytonsmith.abstraction.enums.MCChatColor;
import com.laytonsmith.annotations.api;
import com.laytonsmith.core.Documentation;
import com.laytonsmith.core.Static;
import com.laytonsmith.core.constructs.NativeTypeList;
import com.laytonsmith.core.events.Event;
import com.laytonsmith.core.functions.Exceptions;
import com.laytonsmith.core.functions.Function;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*
*/
public class SyntaxHighlighters {
public static String generate(String type, String theme) {
Implementation.forceServerType(Implementation.Type.BUKKIT);
if("npp".equals(type) || "notepad++".equals(type)){
if("default".equals(theme)){
return template("/syntax-templates/notepad++/default.xml");
}
if("obsidian".equals(theme)){
return template("/syntax-templates/notepad++/obsidian.xml");
}
if("solarized-dark".equals(theme)){
return template("/syntax-templates/notepad++/solarized_dark.xml");
}
if("solarized-light".equals(theme)){
return template("/syntax-templates/notepad++/solarized_light.xml");
}
return "Available themes for Notepad++: default, obsidian, solarized-dark, solarized-light";
}
if("textwrangler".equals(type)){
return template("/syntax-templates/text-wrangler/default.plist");
}
if("geshi".equals(type)){
return template("/syntax-templates/geshi/default.php");
}
if("vim".equals(type)){
return template("/syntax-templates/vim/default.vim");
}
if("nano".equals(type)){
return template("/syntax-templates/nano/default.txt");
}
if("atom".equals(type)){
return template("/syntax-templates/atom/default.cson");
}
if("sublime".equals(type)){
return template("/syntax-templates/sublime/default.xml");
}
return "File for the following syntax highlighters are currently available:\n"
+ "\tNotepad++ - Use type \"npp\". You may also select a theme, either \"default\" or \"obsidian\"\n"
+ "\tTextWrangler - Use type \"textwrangler\". Only the default theme is available.\n"
+ "\t\tTo install: put the generated file in ~/Library/Application Support/TextWrangler/Language Modules/\n"
+ "\t\tNote that this output file can also be used for BBEdit.\n"
+ "\tGeSHi - Use type \"geshi\". Only the default theme is available.\n"
+ "\tViM - Use type \"vim\". Only the default theme is available.\n"
+ "\t\tTo install: put in ~/.vim/syntax/commandhelper.vim then edit\n"
+ "\t\t~/.vim/ftdetect/commandhelper.vim and add the line \n"
+ "\t\tau BufRead,BufNewFile *.ms set filetype=commandhelper\n"
+ "\t\tThen, if you're on linux and use cmdline mode, in ~/.vim/scripts.vim, add the following lines:\n"
+ "\t\t\tif did_filetype()\n"
+ "\t\t\t\tfinish\n"
+ "\t\t\tendif\n"
+ "\t\t\tif getline(1) =~# '^#!.*\\(/bin/env\\s\\+mscript\\|/bin/mscript\\)\\>'\n"
+ "\t\t\t\tsetfiletype commandhelper\n"
+ "\t\t\tendif"
+ "\t\t(Create directories and files as needed)\n"
+ "\tnano - Use type\"nano\". Only the default theme is available.\n"
+ "\tSublime Text - Use type \"sublime\". Only the default theme is available.\n"
+ "\t\tTo install: Place in Sublime Text's ./SublimeText/data/Packages/User folder.\n"
+ "\tAtom - Use type \"atom\". Only the default theme is available.\n"
+ "\t\tTo install: Install package language-mscript from the Atom package manager."
+ "\n\n"
+ "Know how to write a syntax highlighter file for your favorite text editor? Let me know, and we\n"
+ "can work to get it included in CommandHelper!";
}
/**
* Available macros are listed in the code below.
* @param location
* @return
*/
private static String template(String location) {
String template = Static.GetStringResource(location);
//Replace all instances of ///! with nothing.
template = template.replace("///!", "");
Pattern p = Pattern.compile("%%(.*?)%%");
Matcher m = p.matcher(template);
while(m.find()){
template = template.replaceAll("%%" + m.group(1) + "%%", macro(m.group(1)));
}
return template;
}
private static String macro(String macroName){
String[] split = macroName.split(":");
String type = split[0];
String datalist = split[1];
List<String> params = new ArrayList<String>();
for(int i = 2; i < split.length; i++){
params.add(split[i].toLowerCase());
}
List<String> base = new ArrayList<String>();
if(datalist.equalsIgnoreCase("colors")){
for(MCChatColor c : MCChatColor.values()){
base.add(c.name());
}
} else if(datalist.equalsIgnoreCase("keywords")){
for(String keyword : SimpleSyntaxHighlighter.KEYWORDS){
base.add(keyword);
}
} else if(datalist.equalsIgnoreCase("functions")){
for(Function f : GetFunctions()){
if(SimpleSyntaxHighlighter.KEYWORDS.contains(f.getName())){
// Keywords override functions
continue;
}
if(!f.appearInDocumentation()){
continue;
}
if(params.contains("restricted") || params.contains("unrestricted")){
if(params.contains("restricted") && f.isRestricted()){
base.add(f.getName());
} else if(params.contains("unrestricted") && !f.isRestricted()){
base.add(f.getName());
}
} else {
base.add(f.getName());
}
}
} else if(datalist.equalsIgnoreCase("events")){
for(Documentation d : GetEvents()){
base.add(d.getName());
}
} else if(datalist.equalsIgnoreCase("exceptions")){
for(Exceptions.ExceptionType e : Exceptions.ExceptionType.values()){
base.add(e.name());
}
} else if(datalist.equalsIgnoreCase("types")){
base.addAll(NativeTypeList.getNativeTypeList());
base.remove("null"); // Null is technically in the list, but it shouldn't be added.
}
String header = "";
String spliter = "IMPROPER FORMATTING";
String footer = "";
if(type.equalsIgnoreCase("space")){
if(params.contains("quoted")){
header = "'";
spliter = "' '";
footer = "'";
} else {
spliter = " ";
}
} else if(type.equalsIgnoreCase("comma")){
if(params.contains("quoted")){
header = "'";
spliter = "', '";
footer = "'";
} else {
spliter = ", ";
}
} else if(type.equalsIgnoreCase("pipe")){
if(params.contains("quoted")){
header = "'";
spliter = "|";
footer = "'";
} else {
spliter = "|";
}
} else if(type.equalsIgnoreCase("xml")){
String tag = "PLEASE INCLUDE THE TAG NAME USING tag=tagname AS A PARAMETER";
for(String param : params){
//Find the tag name
if(param.matches("tag=.*")){
tag = param.substring(4);
break;
}
}
if(params.contains("quoted")){
header = "<" + tag + ">'";
spliter = "'</" + tag + "><" + tag + ">'";
footer = "'</" + tag + ">";
} else {
header = "<" + tag + ">";
spliter = "</" + tag + "><" + tag + ">";
footer = "</" + tag + ">";
}
}
return header + Join(base, spliter) + footer;
}
private static List<Documentation> GetEvents(){
List<Documentation> l = new ArrayList<Documentation>();
Set<Class> classes = ClassDiscovery.getDefaultInstance().loadClassesWithAnnotation(api.class);
for(Class c : classes){
if (Event.class.isAssignableFrom(c) && Documentation.class.isAssignableFrom(c)) {
try {
Constructor m = c.getConstructor();
Documentation e = (Documentation)m.newInstance();
l.add(e);
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
}
return l;
}
private static List<Function> GetFunctions(){
List<Function> fl = new ArrayList<Function>();
Set<Class> functions = ClassDiscovery.getDefaultInstance().loadClassesWithAnnotation(api.class);
for(Class c : functions){
if(Function.class.isAssignableFrom(c)){
try {
fl.add((Function)c.newInstance());
} catch (InstantiationException ex) {
Logger.getLogger(SyntaxHighlighters.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(SyntaxHighlighters.class.getName()).log(Level.SEVERE, null, ex);
} catch(NoClassDefFoundError e){
//Hmm. No real good way to handle this... echo out to stderr, I guess.
System.err.println(e.getMessage());
}
}
}
return fl;
}
private static String Join(List l, String joiner){
StringBuilder b = new StringBuilder();
for(int i = 0; i < l.size(); i++){
if(i == 0){
b.append(l.get(i).toString());
} else {
b.append(joiner).append(l.get(i).toString());
}
}
return b.toString();
}
}
| src/main/java/com/laytonsmith/tools/SyntaxHighlighters.java |
package com.laytonsmith.tools;
import com.laytonsmith.PureUtilities.ClassLoading.ClassDiscovery;
import com.laytonsmith.abstraction.Implementation;
import com.laytonsmith.abstraction.enums.MCChatColor;
import com.laytonsmith.annotations.api;
import com.laytonsmith.core.Documentation;
import com.laytonsmith.core.Static;
import com.laytonsmith.core.constructs.NativeTypeList;
import com.laytonsmith.core.events.Event;
import com.laytonsmith.core.functions.Exceptions;
import com.laytonsmith.core.functions.Function;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*
*/
public class SyntaxHighlighters {
public static String generate(String type, String theme) {
Implementation.forceServerType(Implementation.Type.BUKKIT);
if("npp".equals(type) || "notepad++".equals(type)){
if("default".equals(theme)){
return template("/syntax-templates/notepad++/default.xml");
}
if("obsidian".equals(theme)){
return template("/syntax-templates/notepad++/obsidian.xml");
}
if("solarized-dark".equals(theme)){
return template("/syntax-templates/notepad++/solarized_dark.xml");
}
if("solarized-light".equals(theme)){
return template("/syntax-templates/notepad++/solarized_light.xml");
}
return "Available themes for Notepad++: default, obsidian, solarized-dark, solarized-light";
}
if("textwrangler".equals(type)){
return template("/syntax-templates/text-wrangler/default.plist");
}
if("geshi".equals(type)){
return template("/syntax-templates/geshi/default.php");
}
if("vim".equals(type)){
return template("/syntax-templates/vim/default.vim");
}
if("nano".equals(type)){
return template("/syntax-templates/nano/default.txt");
}
if("atom".equals(type)){
return template("/syntax-templates/atom/default.cson");
}
if("sublime".equals(type)){
return template("/syntax-templates/sublime/default.xml");
}
return "File for the following syntax highlighters are currently available:\n"
+ "\tNotepad++ - Use type \"npp\". You may also select a theme, either \"default\" or \"obsidian\"\n"
+ "\tTextWrangler - Use type \"textwrangler\". Only the default theme is available.\n"
+ "\t\tTo install: put the generated file in ~/Library/Application Support/TextWrangler/Language Modules/\n"
+ "\t\tNote that this output file can also be used for BBEdit.\n"
+ "\tGeSHi - Use type \"geshi\". Only the default theme is available.\n"
+ "\tViM - Use type \"vim\". Only the default theme is available.\n"
+ "\t\tTo install: put in ~/.vim/syntax/commandhelper.vim then edit\n"
+ "\t\t~/.vim/ftdetect/commandhelper.vim and add the line \n"
+ "\t\tau BufRead,BufNewFile *.ms set filetype=commandhelper\n"
+ "\t\tThen, if you're on linux and use cmdline mode, in ~/.vim/scripts.vim, add the following lines:\n"
+ "\t\t\tif did_filetype()\n"
+ "\t\t\t\tfinish\n"
+ "\t\t\tendif\n"
+ "\t\t\tif getline(1) =~# '^#!.*\\(/bin/env\\s\\+mscript\\|/bin/mscript\\)\\>'\n"
+ "\t\t\t\tsetfiletype commandhelper\n"
+ "\t\t\tendif"
+ "\t\t(Create directories and files as needed)\n"
+ "\tnano - Use type\"nano\". Only the default theme is available.\n"
+ "\tSublime Text - Use type \"sublime\". Only the default theme is available.\n"
+ "\t\tTo install: Place in Sublime Text's ./SublimeText/data/Packages/User folder."
+ "\n\n"
+ "Know how to write a syntax highlighter file for your favorite text editor? Let me know, and we\n"
+ "can work to get it included in CommandHelper!";
}
/**
* Available macros are listed in the code below.
* @param location
* @return
*/
private static String template(String location) {
String template = Static.GetStringResource(location);
//Replace all instances of ///! with nothing.
template = template.replace("///!", "");
Pattern p = Pattern.compile("%%(.*?)%%");
Matcher m = p.matcher(template);
while(m.find()){
template = template.replaceAll("%%" + m.group(1) + "%%", macro(m.group(1)));
}
return template;
}
private static String macro(String macroName){
String[] split = macroName.split(":");
String type = split[0];
String datalist = split[1];
List<String> params = new ArrayList<String>();
for(int i = 2; i < split.length; i++){
params.add(split[i].toLowerCase());
}
List<String> base = new ArrayList<String>();
if(datalist.equalsIgnoreCase("colors")){
for(MCChatColor c : MCChatColor.values()){
base.add(c.name());
}
} else if(datalist.equalsIgnoreCase("keywords")){
for(String keyword : SimpleSyntaxHighlighter.KEYWORDS){
base.add(keyword);
}
} else if(datalist.equalsIgnoreCase("functions")){
for(Function f : GetFunctions()){
if(SimpleSyntaxHighlighter.KEYWORDS.contains(f.getName())){
// Keywords override functions
continue;
}
if(!f.appearInDocumentation()){
continue;
}
if(params.contains("restricted") || params.contains("unrestricted")){
if(params.contains("restricted") && f.isRestricted()){
base.add(f.getName());
} else if(params.contains("unrestricted") && !f.isRestricted()){
base.add(f.getName());
}
} else {
base.add(f.getName());
}
}
} else if(datalist.equalsIgnoreCase("events")){
for(Documentation d : GetEvents()){
base.add(d.getName());
}
} else if(datalist.equalsIgnoreCase("exceptions")){
for(Exceptions.ExceptionType e : Exceptions.ExceptionType.values()){
base.add(e.name());
}
} else if(datalist.equalsIgnoreCase("types")){
base.addAll(NativeTypeList.getNativeTypeList());
base.remove("null"); // Null is technically in the list, but it shouldn't be added.
}
String header = "";
String spliter = "IMPROPER FORMATTING";
String footer = "";
if(type.equalsIgnoreCase("space")){
if(params.contains("quoted")){
header = "'";
spliter = "' '";
footer = "'";
} else {
spliter = " ";
}
} else if(type.equalsIgnoreCase("comma")){
if(params.contains("quoted")){
header = "'";
spliter = "', '";
footer = "'";
} else {
spliter = ", ";
}
} else if(type.equalsIgnoreCase("pipe")){
if(params.contains("quoted")){
header = "'";
spliter = "|";
footer = "'";
} else {
spliter = "|";
}
} else if(type.equalsIgnoreCase("xml")){
String tag = "PLEASE INCLUDE THE TAG NAME USING tag=tagname AS A PARAMETER";
for(String param : params){
//Find the tag name
if(param.matches("tag=.*")){
tag = param.substring(4);
break;
}
}
if(params.contains("quoted")){
header = "<" + tag + ">'";
spliter = "'</" + tag + "><" + tag + ">'";
footer = "'</" + tag + ">";
} else {
header = "<" + tag + ">";
spliter = "</" + tag + "><" + tag + ">";
footer = "</" + tag + ">";
}
}
return header + Join(base, spliter) + footer;
}
private static List<Documentation> GetEvents(){
List<Documentation> l = new ArrayList<Documentation>();
Set<Class> classes = ClassDiscovery.getDefaultInstance().loadClassesWithAnnotation(api.class);
for(Class c : classes){
if (Event.class.isAssignableFrom(c) && Documentation.class.isAssignableFrom(c)) {
try {
Constructor m = c.getConstructor();
Documentation e = (Documentation)m.newInstance();
l.add(e);
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
}
return l;
}
private static List<Function> GetFunctions(){
List<Function> fl = new ArrayList<Function>();
Set<Class> functions = ClassDiscovery.getDefaultInstance().loadClassesWithAnnotation(api.class);
for(Class c : functions){
if(Function.class.isAssignableFrom(c)){
try {
fl.add((Function)c.newInstance());
} catch (InstantiationException ex) {
Logger.getLogger(SyntaxHighlighters.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(SyntaxHighlighters.class.getName()).log(Level.SEVERE, null, ex);
} catch(NoClassDefFoundError e){
//Hmm. No real good way to handle this... echo out to stderr, I guess.
System.err.println(e.getMessage());
}
}
}
return fl;
}
private static String Join(List l, String joiner){
StringBuilder b = new StringBuilder();
for(int i = 0; i < l.size(); i++){
if(i == 0){
b.append(l.get(i).toString());
} else {
b.append(joiner).append(l.get(i).toString());
}
}
return b.toString();
}
}
| Add atom to syntax help text
| src/main/java/com/laytonsmith/tools/SyntaxHighlighters.java | Add atom to syntax help text | <ide><path>rc/main/java/com/laytonsmith/tools/SyntaxHighlighters.java
<ide> + "\t\t(Create directories and files as needed)\n"
<ide> + "\tnano - Use type\"nano\". Only the default theme is available.\n"
<ide> + "\tSublime Text - Use type \"sublime\". Only the default theme is available.\n"
<del> + "\t\tTo install: Place in Sublime Text's ./SublimeText/data/Packages/User folder."
<add> + "\t\tTo install: Place in Sublime Text's ./SublimeText/data/Packages/User folder.\n"
<add> + "\tAtom - Use type \"atom\". Only the default theme is available.\n"
<add> + "\t\tTo install: Install package language-mscript from the Atom package manager."
<ide> + "\n\n"
<ide> + "Know how to write a syntax highlighter file for your favorite text editor? Let me know, and we\n"
<ide> + "can work to get it included in CommandHelper!"; |
|
Java | apache-2.0 | 3f8c8323c29c62f3c3c9d78c2f0e7a602c24be2a | 0 | cuba-platform/cuba,cuba-platform/cuba,dimone-kun/cuba,dimone-kun/cuba,dimone-kun/cuba,cuba-platform/cuba | /*
* Copyright (c) 2013 Haulmont Technology Ltd. All Rights Reserved.
* Haulmont Technology proprietary and confidential.
* Use is subject to license terms.
*/
package com.haulmont.cuba.web.sys;
import com.haulmont.cuba.core.app.DataService;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.gui.NoSuchScreenException;
import com.haulmont.cuba.gui.WindowManager;
import com.haulmont.cuba.gui.components.Action;
import com.haulmont.cuba.gui.components.Component;
import com.haulmont.cuba.gui.components.DialogAction;
import com.haulmont.cuba.gui.components.IFrame;
import com.haulmont.cuba.gui.config.WindowConfig;
import com.haulmont.cuba.gui.config.WindowInfo;
import com.haulmont.cuba.security.entity.User;
import com.haulmont.cuba.security.entity.UserSubstitution;
import com.haulmont.cuba.security.global.UserSession;
import com.haulmont.cuba.web.App;
import com.haulmont.cuba.web.actions.ChangeSubstUserAction;
import com.haulmont.cuba.web.actions.DoNotChangeSubstUserAction;
import com.haulmont.cuba.web.exception.AccessDeniedHandler;
import com.haulmont.cuba.web.exception.EntityAccessExceptionHandler;
import com.haulmont.cuba.web.exception.NoSuchScreenHandler;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import javax.annotation.ManagedBean;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Handles links from outside of the application.
* <p/> This bean is used particularly when a request URL contains one of
* {@link com.haulmont.cuba.web.WebConfig#getLinkHandlerActions()} actions.
*
* @author krivopustov
* @version $Id$
*/
@ManagedBean(LinkHandler.NAME)
@Scope("prototype")
public class LinkHandler {
public static final String NAME = "cuba_LinkHandler";
protected Log log = LogFactory.getLog(getClass());
@Inject
protected Messages messages;
@Inject
protected TimeSource timeSource;
@Inject
protected DataService dataService;
protected App app;
protected String action;
protected Map<String, String> requestParams;
public LinkHandler(App app, String action, Map<String, String> requestParams) {
this.app = app;
this.action = action;
this.requestParams = requestParams;
}
/**
* Called to handle the link.
*/
public void handle() {
try {
String screenName = requestParams.get("screen");
if (screenName == null) {
log.warn("ScreenId not found in request parameters");
return;
}
WindowConfig windowConfig = AppBeans.get(WindowConfig.class);
final WindowInfo windowInfo = windowConfig.getWindowInfo(screenName);
if (windowInfo == null) {
log.warn("WindowInfo not found for screen: " + screenName);
return;
}
UUID userId = getUUID(requestParams.get("user"));
UserSession userSession = app.getConnection().getSession();
if (userSession == null) {
log.warn("No user session");
return;
}
if (!(userId == null || userSession.getCurrentOrSubstitutedUser().getId().equals(userId))) {
substituteUserAndOpenWindow(windowInfo, userId);
} else
openWindow(windowInfo);
} catch (AccessDeniedException e) {
new AccessDeniedHandler().handle(e, app);
} catch (NoSuchScreenException e) {
new NoSuchScreenHandler().handle(e, app);
} catch (EntityAccessException e) {
new EntityAccessExceptionHandler().handle(e, app);
}
}
protected void substituteUserAndOpenWindow(final WindowInfo windowInfo, UUID userId) {
UserSession userSession = app.getConnection().getSession();
final User substitutedUser = loadUser(userId, userSession.getUser());
if (substitutedUser != null)
app.getWindowManager().showOptionDialog(
messages.getMessage(getClass(), "toSubstitutedUser.title"),
getDialogMessage(substitutedUser),
IFrame.MessageType.CONFIRMATION,
new Action[]{
new ChangeSubstUserAction(substitutedUser) {
@Override
public void doAfterChangeUser() {
super.doAfterChangeUser();
openWindow(windowInfo);
}
@Override
public void doRevert() {
super.doRevert();
app.getAppWindow().executeJavaScript("window.close();");
}
@Override
public String getCaption() {
return messages.getMessage(getClass(), "action.switch");
}
},
new DoNotChangeSubstUserAction() {
@Override
public void actionPerform(Component component) {
super.actionPerform(component);
app.getAppWindow().executeJavaScript("window.close();");
}
@Override
public String getCaption() {
return messages.getMessage(getClass(), "action.cancel");
}
}
});
else {
User user = loadUser(userId);
app.getWindowManager().showOptionDialog(
messages.getMessage(getClass(), "warning.title"),
getWarningMessage(user),
IFrame.MessageType.WARNING,
new Action[]{
new DialogAction(DialogAction.Type.OK) {
@Override
public void actionPerform(Component component) {
app.getAppWindow().executeJavaScript("window.close();");
}
}
});
}
}
protected UUID getUUID(String id) {
if (StringUtils.isBlank(id))
return null;
UUID uuid;
try {
uuid = UUID.fromString(id);
} catch (IllegalArgumentException e) {
uuid = null;
}
return uuid;
}
protected String getWarningMessage(User user) {
if (user == null)
return messages.getMessage(getClass(), "warning.userNotFound");
return messages.formatMessage(
getClass(),
"warning.msg",
StringUtils.isBlank(user.getName()) ? user.getLogin() : user.getName()
);
}
protected User loadUser(UUID userId, User user) {
if (user.getId().equals(userId))
return user;
LoadContext loadContext = new LoadContext(UserSubstitution.class);
LoadContext.Query query = new LoadContext.Query("select su from sec$UserSubstitution us join us.user u " +
"join us.substitutedUser su where u.id = :id and su.id = :userId and " +
"(us.endDate is null or us.endDate >= :currentDate) and (us.startDate is null or us.startDate <= :currentDate)");
query.addParameter("id", user);
query.addParameter("userId", userId);
query.addParameter("currentDate", timeSource.currentTimestamp());
loadContext.setQuery(query);
List<User> users = dataService.loadList(loadContext);
return users.isEmpty() ? null : users.get(0);
}
protected User loadUser(UUID userId) {
LoadContext loadContext = new LoadContext(User.class);
LoadContext.Query query = new LoadContext.Query("select u from sec$User u where u.id = :userId");
query.addParameter("userId", userId);
loadContext.setQuery(query);
List<User> users = dataService.loadList(loadContext);
return users.isEmpty() ? null : users.get(0);
}
protected String getDialogMessage(User user) {
return messages.formatMessage(
getClass(),
"toSubstitutedUser.msg",
StringUtils.isBlank(user.getName()) ? user.getLogin() : user.getName()
);
}
protected void openWindow(WindowInfo windowInfo) {
String itemStr = requestParams.get("item");
String openTypeParam = requestParams.get("openType");
WindowManager.OpenType openType = WindowManager.OpenType.NEW_TAB;
if (StringUtils.isNotBlank(openTypeParam)) {
try {
openType = WindowManager.OpenType.valueOf(openTypeParam);
} catch (IllegalArgumentException e) {
log.warn("Unknown open type (" + openTypeParam + ") in request parameters");
}
}
if (itemStr == null) {
app.getWindowManager().openWindow(windowInfo, openType, getParamsMap());
} else {
EntityLoadInfo info = EntityLoadInfo.parse(itemStr);
if (info == null) {
log.warn("Invalid item definition: " + itemStr);
} else {
Entity entity = loadEntityInstance(info);
if (entity != null)
app.getWindowManager().openEditor(windowInfo, entity, openType, getParamsMap());
else
throw new EntityAccessException();
}
}
}
protected Map<String, Object> getParamsMap() {
Map<String, Object> params = new HashMap<>();
String paramsStr = requestParams.get("params");
if (paramsStr == null)
return params;
String[] entries = paramsStr.split(",");
for (String entry : entries) {
String[] parts = entry.split(":");
if (parts.length != 2) {
log.warn("Invalid parameter: " + entry);
return params;
}
String name = parts[0];
String value = parts[1];
EntityLoadInfo info = EntityLoadInfo.parse(value);
if (info != null) {
Entity entity = loadEntityInstance(info);
if (entity != null)
params.put(name, entity);
} else if (Boolean.TRUE.toString().equals(value) || Boolean.FALSE.toString().equals(value)) {
params.put(name, BooleanUtils.toBoolean(value));
} else {
params.put(name, value);
}
}
return params;
}
protected Entity loadEntityInstance(EntityLoadInfo info) {
LoadContext ctx = new LoadContext(info.getMetaClass()).setId(info.getId());
if (info.getViewName() != null)
ctx.setView(info.getViewName());
Entity entity;
try {
entity = dataService.load(ctx);
} catch (Exception e) {
log.warn("Unable to load item: " + info, e);
return null;
}
return entity;
}
}
| modules/web/src/com/haulmont/cuba/web/sys/LinkHandler.java | /*
* Copyright (c) 2013 Haulmont Technology Ltd. All Rights Reserved.
* Haulmont Technology proprietary and confidential.
* Use is subject to license terms.
*/
package com.haulmont.cuba.web.sys;
import com.haulmont.cuba.core.app.DataService;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.gui.NoSuchScreenException;
import com.haulmont.cuba.gui.WindowManager;
import com.haulmont.cuba.gui.components.Action;
import com.haulmont.cuba.gui.components.Component;
import com.haulmont.cuba.gui.components.DialogAction;
import com.haulmont.cuba.gui.components.IFrame;
import com.haulmont.cuba.gui.config.WindowConfig;
import com.haulmont.cuba.gui.config.WindowInfo;
import com.haulmont.cuba.security.entity.User;
import com.haulmont.cuba.security.entity.UserSubstitution;
import com.haulmont.cuba.security.global.UserSession;
import com.haulmont.cuba.web.App;
import com.haulmont.cuba.web.actions.ChangeSubstUserAction;
import com.haulmont.cuba.web.actions.DoNotChangeSubstUserAction;
import com.haulmont.cuba.web.exception.AccessDeniedHandler;
import com.haulmont.cuba.web.exception.EntityAccessExceptionHandler;
import com.haulmont.cuba.web.exception.NoSuchScreenHandler;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import javax.annotation.ManagedBean;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Handles links from outside of the application.
* <p/> This bean is used particularly when a request URL contains one of
* {@link com.haulmont.cuba.web.WebConfig#getLinkHandlerActions()} actions.
*
* @author krivopustov
* @version $Id$
*/
@ManagedBean(LinkHandler.NAME)
@Scope("prototype")
public class LinkHandler {
public static final String NAME = "cuba_LinkHandler";
protected Log log = LogFactory.getLog(getClass());
@Inject
protected Messages messages;
@Inject
protected TimeSource timeSource;
@Inject
protected DataService dataService;
protected App app;
protected String action;
protected Map<String, String> requestParams;
public LinkHandler(App app, String action, Map<String, String> requestParams) {
this.app = app;
this.action = action;
this.requestParams = requestParams;
}
/**
* Called to handle the link.
*/
public void handle() {
try {
String screenName = requestParams.get("screen");
if (screenName == null) {
log.warn("ScreenId not found in request parameters");
return;
}
WindowConfig windowConfig = AppBeans.get(WindowConfig.class);
final WindowInfo windowInfo = windowConfig.getWindowInfo(screenName);
if (windowInfo == null) {
log.warn("WindowInfo not found for screen: " + screenName);
return;
}
UUID userId = getUUID(requestParams.get("user"));
UserSession userSession = app.getConnection().getSession();
if (userSession == null) {
log.warn("No user session");
return;
}
if (!(userId == null || userSession.getCurrentOrSubstitutedUser().getId().equals(userId))) {
substituteUserAndOpenWindow(windowInfo, userId);
} else
openWindow(windowInfo);
} catch (AccessDeniedException e) {
new AccessDeniedHandler().handle(e, app);
} catch (NoSuchScreenException e) {
new NoSuchScreenHandler().handle(e, app);
} catch (EntityAccessException e) {
new EntityAccessExceptionHandler().handle(e, app);
}
}
protected void substituteUserAndOpenWindow(final WindowInfo windowInfo, UUID userId) {
UserSession userSession = app.getConnection().getSession();
final User substitutedUser = loadUser(userId, userSession.getUser());
if (substitutedUser != null)
app.getWindowManager().showOptionDialog(
messages.getMessage(getClass(), "toSubstitutedUser.title"),
getDialogMessage(substitutedUser),
IFrame.MessageType.CONFIRMATION,
new Action[]{
new ChangeSubstUserAction(substitutedUser) {
@Override
public void doAfterChangeUser() {
super.doAfterChangeUser();
openWindow(windowInfo);
}
@Override
public void doRevert() {
super.doRevert();
app.getAppWindow().executeJavaScript("window.close();");
}
@Override
public String getCaption() {
return messages.getMessage(getClass(), "action.switch");
}
},
new DoNotChangeSubstUserAction() {
@Override
public void actionPerform(Component component) {
super.actionPerform(component);
app.getAppWindow().executeJavaScript("window.close();");
}
@Override
public String getCaption() {
return messages.getMessage(getClass(), "action.cancel");
}
}
});
else {
User user = loadUser(userId);
app.getWindowManager().showOptionDialog(
messages.getMessage(getClass(), "warning.title"),
getWarningMessage(user),
IFrame.MessageType.WARNING,
new Action[]{
new DialogAction(DialogAction.Type.OK) {
@Override
public void actionPerform(Component component) {
app.getAppWindow().executeJavaScript("window.close();");
}
}
});
}
}
protected UUID getUUID(String id) {
if (StringUtils.isBlank(id))
return null;
UUID uuid;
try {
uuid = UUID.fromString(id);
} catch (IllegalArgumentException e) {
uuid = null;
}
return uuid;
}
protected String getWarningMessage(User user) {
if (user == null)
return messages.getMessage(getClass(), "warning.userNotFound");
return messages.formatMessage(
getClass(),
"warning.msg",
StringUtils.isBlank(user.getName()) ? user.getLogin() : user.getName()
);
}
protected User loadUser(UUID userId, User user) {
if (user.getId().equals(userId))
return user;
LoadContext loadContext = new LoadContext(UserSubstitution.class);
LoadContext.Query query = new LoadContext.Query("select su from sec$UserSubstitution us join us.user u " +
"join us.substitutedUser su where u.id = :id and su.id = :userId and " +
"(us.endDate is null or us.endDate >= :currentDate) and (us.startDate is null or us.startDate <= :currentDate)");
query.addParameter("id", user);
query.addParameter("userId", userId);
query.addParameter("currentDate", timeSource.currentTimestamp());
loadContext.setQuery(query);
List<User> users = dataService.loadList(loadContext);
return users.isEmpty() ? null : users.get(0);
}
protected User loadUser(UUID userId) {
LoadContext loadContext = new LoadContext(User.class);
LoadContext.Query query = new LoadContext.Query("select u from sec$User u where u.id = :userId");
query.addParameter("userId", userId);
loadContext.setQuery(query);
List<User> users = dataService.loadList(loadContext);
return users.isEmpty() ? null : users.get(0);
}
protected String getDialogMessage(User user) {
return messages.formatMessage(
getClass(),
"toSubstitutedUser.msg",
StringUtils.isBlank(user.getName()) ? user.getLogin() : user.getName()
);
}
protected void openWindow(WindowInfo windowInfo) {
String itemStr = requestParams.get("item");
if (itemStr == null) {
app.getWindowManager().openWindow(windowInfo, WindowManager.OpenType.NEW_TAB, getParamsMap());
} else {
EntityLoadInfo info = EntityLoadInfo.parse(itemStr);
if (info == null) {
log.warn("Invalid item definition: " + itemStr);
} else {
Entity entity = loadEntityInstance(info);
if (entity != null)
app.getWindowManager().openEditor(windowInfo, entity, WindowManager.OpenType.NEW_TAB, getParamsMap());
else
throw new EntityAccessException();
}
}
}
protected Map<String, Object> getParamsMap() {
Map<String, Object> params = new HashMap<>();
String paramsStr = requestParams.get("params");
if (paramsStr == null)
return params;
String[] entries = paramsStr.split(",");
for (String entry : entries) {
String[] parts = entry.split(":");
if (parts.length != 2) {
log.warn("Invalid parameter: " + entry);
return params;
}
String name = parts[0];
String value = parts[1];
EntityLoadInfo info = EntityLoadInfo.parse(value);
if (info != null) {
Entity entity = loadEntityInstance(info);
if (entity != null)
params.put(name, entity);
} else if (Boolean.TRUE.toString().equals(value) || Boolean.FALSE.toString().equals(value)) {
params.put(name, BooleanUtils.toBoolean(value));
} else {
params.put(name, value);
}
}
return params;
}
protected Entity loadEntityInstance(EntityLoadInfo info) {
LoadContext ctx = new LoadContext(info.getMetaClass()).setId(info.getId());
if (info.getViewName() != null)
ctx.setView(info.getViewName());
Entity entity;
try {
entity = dataService.load(ctx);
} catch (Exception e) {
log.warn("Unable to load item: " + info, e);
return null;
}
return entity;
}
}
| Add processing of 'openType' parameter in LinkHandler #PL-2006
| modules/web/src/com/haulmont/cuba/web/sys/LinkHandler.java | Add processing of 'openType' parameter in LinkHandler #PL-2006 | <ide><path>odules/web/src/com/haulmont/cuba/web/sys/LinkHandler.java
<ide>
<ide> protected void openWindow(WindowInfo windowInfo) {
<ide> String itemStr = requestParams.get("item");
<add> String openTypeParam = requestParams.get("openType");
<add> WindowManager.OpenType openType = WindowManager.OpenType.NEW_TAB;
<add>
<add> if (StringUtils.isNotBlank(openTypeParam)) {
<add> try {
<add> openType = WindowManager.OpenType.valueOf(openTypeParam);
<add> } catch (IllegalArgumentException e) {
<add> log.warn("Unknown open type (" + openTypeParam + ") in request parameters");
<add> }
<add> }
<add>
<ide> if (itemStr == null) {
<del> app.getWindowManager().openWindow(windowInfo, WindowManager.OpenType.NEW_TAB, getParamsMap());
<add> app.getWindowManager().openWindow(windowInfo, openType, getParamsMap());
<ide> } else {
<ide> EntityLoadInfo info = EntityLoadInfo.parse(itemStr);
<ide> if (info == null) {
<ide> } else {
<ide> Entity entity = loadEntityInstance(info);
<ide> if (entity != null)
<del> app.getWindowManager().openEditor(windowInfo, entity, WindowManager.OpenType.NEW_TAB, getParamsMap());
<add> app.getWindowManager().openEditor(windowInfo, entity, openType, getParamsMap());
<ide> else
<ide> throw new EntityAccessException();
<ide> } |
|
Java | mit | 876b87158ac444382d4437f3eb6b5ac3106f7b5c | 0 | azuqua/azuqua.java,azuqua/azuqua.java,azuqua/azuqua.java | package com.azuqua.java.client;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.Vector;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.azuqua.java.client.model.*;
/**
* <p>Enables the caller to make requests to the Azuqua API.</p>
*
* <p>There's two ways to use this object:</p>
*
* <ul>
* <li>Pass your access key and access secret into the constructor.
* <pre>
Azuqua azuqua = new Azuqua(ACCESS_KEY, ACCESS_SECRET);
List<Flo> flos = azuqua.getFlos();
for(Flo flo : flos) {
flo.invoke(data);
}
* </pre>
* </li>
* <li>
* Use your logon credentials:
* <pre>
Azuqua azuqua = new Azuqua();
Orgs orgs = azuqua.login("[email protected]", "password");
for(Org org : orgs.getOrgs()) {
// set the access key and access secret from the
// specific org you're trying to invoke flos from.
azuqua.setAccessKey(org.getAccessKey());
azuqua.setAccessSecret(org.getAccessSecret());
for(Flo flo : org.getFlos()) {
o(method, "Alias: " + flo.getAlias());
o(method, "Name: " + flo.getName());
// Need to give a reference to the azuqua object so the
// the flo can make Http calls.
flo.setAzuqua(azuqua);
String resp = flo.invoke("{\"abc\":\"fooazuqua.com\"}");
o(method, "resp login method: " + resp);
}
}
* </pre>
* </li>
* @author quyle
*
*/
public class Azuqua {
private boolean DEBUG = false;
private Gson gson = new Gson();
private Vector<Flo> floCache = new Vector<Flo>();
// routes
public final static String invokeRoute = "/flo/:id/invoke";
public final static String listRoute = "/account/flos";
public final static String accountsInfoRoute = "/account/data";
// http options
private String host = "api.azuqua.com";
private String protocol = "https";
private int port = 443;
// account
private String accessKey;
private String accessSecret;
final private static char[] hexArray = "0123456789ABCDEF".toCharArray();
/**
* Custom implementation of DatatypeConverter.printHexBinary() method. Not as
* fast, but works just fine for this purpose. This method is needed because
* Android doesn't have the DatatypeConverter object. In the futute, we should
* use a cross platform implementation such as the Apache codec jar.
* @param bytes
* @return
*/
private String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private String signData(String data, String verb, String path, String timestamp) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException {
String method = "signData";
Mac hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec key = new SecretKeySpec(this.accessSecret.getBytes("UTF-8"), "HmacSHA256");
hmac.init(key);
String meta = verb + ":" + path + ":" + timestamp;
String dataToDigest = meta + data;
out(method, "data to digest " + dataToDigest);
byte[] digest = hmac.doFinal(dataToDigest.getBytes("UTF-8"));
String digestString = bytesToHex(digest).toLowerCase();
out(method, "digested string " + digestString);
return digestString;
}
private String getISOTime() {
TimeZone timezone = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
df.setTimeZone(timezone);
String timestamp = df.format(new Date());
return timestamp;
}
private void printHeaders(String verb, URLConnection connection, URL apiUrl) {
String method = "printHeaders";
out(method, "headers =====================");
String curl = "curl -i ";
for (Entry<String, List<String>> k : connection.getRequestProperties().entrySet()) {
for (String v : k.getValue()){
out(method, k.getKey() + ":" + v);
curl += "-H \"" + k.getKey() + ":" + v + "\" ";
}
}
curl += " --verbose ";
if (verb.toUpperCase().equals("POST")) {
curl += " -X POST -d \'{ \"abc\":\"this is a test.\" }' ";
}
curl += apiUrl.toString();
out(method, "curl: " + curl);
out(method, "headers =====================");
out(method, "DEBUG =======================");
out(method, "agent: " + connection.getRequestProperty("agent"));
out(method, "url: " + apiUrl.toString());
out(method, "METHOD: " + ((HttpURLConnection) connection).getRequestMethod());
out(method, "host " + apiUrl.getHost());
out(method, "DEBUG =======================");
}
/**
* Makes a request call to the Azuqua API.
* @param verb A String that is either GET or POST.
* @param Path REST API route.
* @param data Data to send to the Azuqua web service.
* @return
* @throws Exception
*/
public String makeRequest(String verb, String path, String data) throws Exception {
String method = "makeRequest";
URLConnection connection;
String timestamp = getISOTime();
String signedData = null;
if (accessKey != null && accessSecret != null) {
signedData = signData(data, verb.toLowerCase(), path, timestamp);
}
URL apiUrl = new URL(this.protocol, this.host, this.port, path);
connection = this.protocol.equals("https") ? (HttpsURLConnection) apiUrl.openConnection() : (HttpURLConnection) apiUrl.openConnection();
try {
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
((HttpURLConnection) connection).setRequestMethod(verb.toUpperCase());
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
connection.setRequestProperty("x-api-timestamp", timestamp);
if (signedData != null) {
connection.setRequestProperty("x-api-hash", signedData);
connection.setRequestProperty("x-api-accessKey", this.accessKey);
}
connection.setRequestProperty("host", this.host);
// printHeaders(verb, connection, apiUrl);
if (verb.toUpperCase().equals("POST")) {
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
}
int status = ((HttpURLConnection) connection).getResponseCode();
out(method, "response code " + status);
StringBuffer response = new StringBuffer();
if (verb.toUpperCase().equals("GET") || verb.toUpperCase().equals("POST")) {
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
}
out(method, "response " + response.toString());
return response.toString();
} catch(Exception e) {
throw e;
}
finally {
((HttpURLConnection) connection).disconnect();
}
}
/**
* Load config info for this class.
* @param accessKey
* @param accessSecret
* @param host
* @param port
* @param protocol
*/
public void loadConfig(String accessKey, String accessSecret, String host, int port, String protocol){
this.accessKey = accessKey;
this.accessSecret = accessSecret;
this.host = host;
this.port = port;
this.protocol = protocol;
}
public Azuqua(String accessKey, String accessSecret){
loadConfig(accessKey, accessSecret, host, port, protocol);
}
public Azuqua(String accessKey, String accessSecret, String _host){
loadConfig(accessKey, accessSecret, _host, port, protocol);
}
public Azuqua(String accessKey, String accessSecret, String _host, int _port){
loadConfig(accessKey, accessSecret, _host, _port, protocol);
}
public Azuqua(String accessKey, String accessSecret, String _host, int _port, String _protocol){
loadConfig(accessKey, accessSecret, _host, _port, _protocol);
}
public Azuqua(){}
/**
* Returns a collection of flos.
* @param refresh
* @return
* @throws AzuquaException
*/
public Collection<Flo> getFlos(boolean refresh) throws AzuquaException{
try {
if(refresh || floCache.size() < 1){
String path = listRoute;
String out = null;
try {
out = makeRequest("GET", path, "");
} catch (InvalidKeyException | NoSuchAlgorithmException |
IllegalStateException | IOException e) {
throw new AzuquaException(e);
}
Type collectionType = new TypeToken< Collection<Flo> >(){}.getType();
Collection<Flo> collection = gson.fromJson(out, collectionType);
// give each Flo a reference to this so it can make a request call
for (Flo flo : collection) {
flo.setAzuqua(this);
}
return collection;
}else{
return this.floCache;
}
} catch (Exception e) {
throw new AzuquaException(e);
}
}
public Collection<Flo> getFlos() throws AzuquaException{
try {
if(floCache.size() < 1){
String path = listRoute;
String out = null;
try {
out = makeRequest("GET", path, "");
} catch (InvalidKeyException | NoSuchAlgorithmException |
IllegalStateException | IOException e) {
throw new AzuquaException(e);
}
Type collectionType = new TypeToken< Collection<Flo> >(){}.getType();
Collection<Flo> collection = gson.fromJson(out, collectionType);
// give each Flo a reference to this so it can make a request call
for (Flo flo : collection) {
flo.setAzuqua(this);
}
return collection;
}else{
return this.floCache;
}
} catch(Exception e) {
throw new AzuquaException(e);
}
}
public Orgs login(String username, String password) throws Exception {
String method = "login";
String loginInfo = gson.toJson(new LoginInfo(username, password));
out(method, "username: " + username);
String accountInfo = makeRequest("POST", accountsInfoRoute, loginInfo);
out(method, "accountInfo: " + accountInfo);
Orgs orgs = gson.fromJson(accountInfo, Orgs.class);
return orgs;
}
/**
* Wrapper for System.out.println.
* @param objects
*/
public void out(String method, String msg) {
if (DEBUG) {
System.out.println(Azuqua.class.getName() + "." + method + ": " + msg);
}
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public void setAccessSecret(String accessSecret) {
this.accessSecret = accessSecret;
}
} | src/com/azuqua/java/client/Azuqua.java | package com.azuqua.java.client;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.Vector;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.bind.DatatypeConverter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.azuqua.java.client.model.*;
/**
* <p>Enables the caller to make requests to the Azuqua API.</p>
*
* <p>There's two ways to use this object:</p>
*
* <ul>
* <li>Pass your access key and access secret into the constructor.
* <pre>
Azuqua azuqua = new Azuqua(ACCESS_KEY, ACCESS_SECRET);
List<Flo> flos = azuqua.getFlos();
for(Flo flo : flos) {
flo.invoke(data);
}
* </pre>
* </li>
* <li>
* Use your logon credentials:
* <pre>
Azuqua azuqua = new Azuqua();
Orgs orgs = azuqua.login("[email protected]", "password");
for(Org org : orgs.getOrgs()) {
// set the access key and access secret from the
// specific org you're trying to invoke flos from.
azuqua.setAccessKey(org.getAccessKey());
azuqua.setAccessSecret(org.getAccessSecret());
for(Flo flo : org.getFlos()) {
o(method, "Alias: " + flo.getAlias());
o(method, "Name: " + flo.getName());
// Need to give a reference to the azuqua object so the
// the flo can make Http calls.
flo.setAzuqua(azuqua);
String resp = flo.invoke("{\"abc\":\"fooazuqua.com\"}");
o(method, "resp login method: " + resp);
}
}
* </pre>
* </li>
* @author quyle
*
*/
public class Azuqua {
private boolean DEBUG = false;
private Gson gson = new Gson();
private Vector<Flo> floCache = new Vector<Flo>();
// routes
public final static String invokeRoute = "/flo/:id/invoke";
public final static String listRoute = "/account/flos";
public final static String accountsInfoRoute = "/account/data";
// http options
private String host = "api.azuqua.com";
private String protocol = "https";
private int port = 443;
// account
private String accessKey;
private String accessSecret;
final private static char[] hexArray = "0123456789ABCDEF".toCharArray();
/**
* Custom implementation of DatatypeConverter.printHexBinary() method. Not as
* fast, but works just fine for this purpose. This method is needed because
* Android doesn't have the DatatypeConverter object. In the futute, we should
* use a cross platform implementation such as the Apache codec jar.
* @param bytes
* @return
*/
private String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private String signData(String data, String verb, String path, String timestamp) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException {
String method = "signData";
Mac hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec key = new SecretKeySpec(this.accessSecret.getBytes("UTF-8"), "HmacSHA256");
hmac.init(key);
String meta = verb + ":" + path + ":" + timestamp;
String dataToDigest = meta + data;
out(method, "data to digest " + dataToDigest);
byte[] digest = hmac.doFinal(dataToDigest.getBytes("UTF-8"));
String digestString = bytesToHex(digest).toLowerCase();
out(method, "digested string " + digestString);
return digestString;
}
private String getISOTime() {
TimeZone timezone = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
df.setTimeZone(timezone);
String timestamp = df.format(new Date());
return timestamp;
}
private void printHeaders(String verb, URLConnection connection, URL apiUrl) {
String method = "printHeaders";
out(method, "headers =====================");
String curl = "curl -i ";
for (Entry<String, List<String>> k : connection.getRequestProperties().entrySet()) {
for (String v : k.getValue()){
out(method, k.getKey() + ":" + v);
curl += "-H \"" + k.getKey() + ":" + v + "\" ";
}
}
curl += " --verbose ";
if (verb.toUpperCase().equals("POST")) {
curl += " -X POST -d \'{ \"abc\":\"this is a test.\" }' ";
}
curl += apiUrl.toString();
out(method, "curl: " + curl);
out(method, "headers =====================");
out(method, "DEBUG =======================");
out(method, "agent: " + connection.getRequestProperty("agent"));
out(method, "url: " + apiUrl.toString());
out(method, "METHOD: " + ((HttpURLConnection) connection).getRequestMethod());
out(method, "host " + apiUrl.getHost());
out(method, "DEBUG =======================");
}
/**
* Makes a request call to the Azuqua API.
* @param verb A String that is either GET or POST.
* @param Path REST API route.
* @param data Data to send to the Azuqua web service.
* @return
* @throws Exception
*/
public String makeRequest(String verb, String path, String data) throws Exception {
String method = "makeRequest";
URLConnection connection;
String timestamp = getISOTime();
String signedData = null;
if (accessKey != null && accessSecret != null) {
signedData = signData(data, verb.toLowerCase(), path, timestamp);
}
URL apiUrl = new URL(this.protocol, this.host, this.port, path);
connection = this.protocol.equals("https") ? (HttpsURLConnection) apiUrl.openConnection() : (HttpURLConnection) apiUrl.openConnection();
try {
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
((HttpURLConnection) connection).setRequestMethod(verb.toUpperCase());
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
connection.setRequestProperty("x-api-timestamp", timestamp);
if (signedData != null) {
connection.setRequestProperty("x-api-hash", signedData);
connection.setRequestProperty("x-api-accessKey", this.accessKey);
}
connection.setRequestProperty("host", this.host);
// printHeaders(verb, connection, apiUrl);
if (verb.toUpperCase().equals("POST")) {
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
}
int status = ((HttpURLConnection) connection).getResponseCode();
out(method, "response code " + status);
StringBuffer response = new StringBuffer();
if (verb.toUpperCase().equals("GET") || verb.toUpperCase().equals("POST")) {
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
}
out(method, "response " + response.toString());
return response.toString();
} catch(Exception e) {
throw e;
}
finally {
((HttpURLConnection) connection).disconnect();
}
}
/**
* Load config info for this class.
* @param accessKey
* @param accessSecret
* @param host
* @param port
* @param protocol
*/
public void loadConfig(String accessKey, String accessSecret, String host, int port, String protocol){
this.accessKey = accessKey;
this.accessSecret = accessSecret;
this.host = host;
this.port = port;
this.protocol = protocol;
}
public Azuqua(String accessKey, String accessSecret){
loadConfig(accessKey, accessSecret, host, port, protocol);
}
public Azuqua(String accessKey, String accessSecret, String _host){
loadConfig(accessKey, accessSecret, _host, port, protocol);
}
public Azuqua(String accessKey, String accessSecret, String _host, int _port){
loadConfig(accessKey, accessSecret, _host, _port, protocol);
}
public Azuqua(String accessKey, String accessSecret, String _host, int _port, String _protocol){
loadConfig(accessKey, accessSecret, _host, _port, _protocol);
}
public Azuqua(){}
/**
* Returns a collection of flos.
* @param refresh
* @return
* @throws AzuquaException
*/
public Collection<Flo> getFlos(boolean refresh) throws AzuquaException{
try {
if(refresh || floCache.size() < 1){
String path = listRoute;
String out = null;
try {
out = makeRequest("GET", path, "");
} catch (InvalidKeyException | NoSuchAlgorithmException |
IllegalStateException | IOException e) {
throw new AzuquaException(e);
}
Type collectionType = new TypeToken< Collection<Flo> >(){}.getType();
Collection<Flo> collection = gson.fromJson(out, collectionType);
// give each Flo a reference to this so it can make a request call
for (Flo flo : collection) {
flo.setAzuqua(this);
}
return collection;
}else{
return this.floCache;
}
} catch (Exception e) {
throw new AzuquaException(e);
}
}
public Collection<Flo> getFlos() throws AzuquaException{
try {
if(floCache.size() < 1){
String path = listRoute;
String out = null;
try {
out = makeRequest("GET", path, "");
} catch (InvalidKeyException | NoSuchAlgorithmException |
IllegalStateException | IOException e) {
throw new AzuquaException(e);
}
Type collectionType = new TypeToken< Collection<Flo> >(){}.getType();
Collection<Flo> collection = gson.fromJson(out, collectionType);
// give each Flo a reference to this so it can make a request call
for (Flo flo : collection) {
flo.setAzuqua(this);
}
return collection;
}else{
return this.floCache;
}
} catch(Exception e) {
throw new AzuquaException(e);
}
}
public Orgs login(String username, String password) throws Exception {
String method = "login";
String loginInfo = gson.toJson(new LoginInfo(username, password));
out(method, "username: " + username);
String accountInfo = makeRequest("POST", accountsInfoRoute, loginInfo);
out(method, "accountInfo: " + accountInfo);
Orgs orgs = gson.fromJson(accountInfo, Orgs.class);
return orgs;
}
/**
* Wrapper for System.out.println.
* @param objects
*/
public void out(String method, String msg) {
if (DEBUG) {
System.out.println(Azuqua.class.getName() + "." + method + ": " + msg);
}
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public void setAccessSecret(String accessSecret) {
this.accessSecret = accessSecret;
}
} | Delete import of DatatypeConverter
| src/com/azuqua/java/client/Azuqua.java | Delete import of DatatypeConverter | <ide><path>rc/com/azuqua/java/client/Azuqua.java
<ide> import javax.crypto.Mac;
<ide> import javax.crypto.spec.SecretKeySpec;
<ide> import javax.net.ssl.HttpsURLConnection;
<del>import javax.xml.bind.DatatypeConverter;
<ide>
<ide> import com.google.gson.Gson;
<ide> import com.google.gson.reflect.TypeToken; |
|
Java | apache-2.0 | 848466d51a132d570207bf8aee9c992934686d9f | 0 | Blazemeter/blazemeter-teamcity-plugin | package com.blaze.agent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import jetbrains.buildServer.RunBuildException;
import jetbrains.buildServer.agent.AgentRunningBuild;
import jetbrains.buildServer.agent.BuildAgent;
import jetbrains.buildServer.agent.BuildFinishedStatus;
import jetbrains.buildServer.agent.BuildProcess;
import jetbrains.buildServer.agent.BuildProgressLogger;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.artifacts.ArtifactsWatcher;
import jetbrains.buildServer.messages.DefaultMessagesInfo;
import jetbrains.buildServer.util.PropertiesUtil;
import com.blaze.api.BlazeBean;
import com.blaze.api.TestInfo;
import com.blaze.runner.BlazeMeterConstants;
/**
* @author Marcel Milea
*
*/
public class BlazeAgentProcessor implements BuildProcess{
private static final int CHECK_INTERVAL = 60000;
private BlazeBean blazeBean;
private AgentRunningBuild agentRunningBuild;
private BuildRunnerContext buildRunnerContext;
private ArtifactsWatcher artifactsWatcher;
private String validationError;
private String testId;
private int testDuration;
int errorUnstableThreshold;
int errorFailedThreshold;
int responseTimeUnstableThreshold;
int responseTimeFailedThreshold;
String dataFolder;
String mainJMX;
final BuildProgressLogger logger;
boolean finished;
boolean needTestUpload;
boolean interrupted;
public BlazeAgentProcessor(BuildAgent buildAgent, AgentRunningBuild agentRunningBuild, BuildRunnerContext buildRunnerContext, ArtifactsWatcher artifactsWatcher) {
this.agentRunningBuild = agentRunningBuild;
this.buildRunnerContext = buildRunnerContext;
this.artifactsWatcher = artifactsWatcher;
this.finished = false;
logger = agentRunningBuild.getBuildLogger();
Map<String, String> buildSharedMap = agentRunningBuild.getSharedConfigParameters();
String proxyPortStr=buildSharedMap.get(BlazeMeterConstants.PROXY_SERVER_PORT);
int proxyPortInt=0;
if(proxyPortStr!=null&&!proxyPortStr.isEmpty()){
proxyPortInt=Integer.parseInt(proxyPortStr);
}
blazeBean = new BlazeBean(
buildSharedMap.get(BlazeMeterConstants.USER_KEY),
buildSharedMap.get(BlazeMeterConstants.PROXY_SERVER_NAME),
proxyPortInt,
buildSharedMap.get(BlazeMeterConstants.PROXY_USERNAME),
buildSharedMap.get(BlazeMeterConstants.PROXY_PASSWORD));
}
private String validateParams(Map<String, String> params) {
testId = params.get(BlazeMeterConstants.SETTINGS_ALL_TESTS_ID);
if (isNullorEmpty(testId)) {
return "No test was defined in the configuration page.";
} else {
//verify if the test still exists on BlazeMeter server
HashMap<String, String> tests = blazeBean.getTests();
if (tests != null){
if (!tests.values().contains(testId)) {
return "Test removed from BlazeMeter server.";
}
}
}
String testDrt = params.get(BlazeMeterConstants.SETTINGS_TEST_DURATION);
if (isNullorEmpty(testDrt)) {
return "Test duration not set.";
} else {
try{
testDuration = Integer.valueOf(testDrt);
} catch (NumberFormatException nfe){
return "Test duration not a numbers.";
}
}
String errorUnstable = params.get(BlazeMeterConstants.SETTINGS_ERROR_THRESHOLD_UNSTABLE);
String errorFail = params.get(BlazeMeterConstants.SETTINGS_ERROR_THRESHOLD_FAIL);
String timeUnstable = params.get(BlazeMeterConstants.SETTINGS_RESPONSE_TIME_UNSTABLE);
String timeFail = params.get(BlazeMeterConstants.SETTINGS_RESPONSE_TIME_FAIL);
errorFailedThreshold = Integer.valueOf(errorFail);
errorUnstableThreshold = Integer.valueOf(errorUnstable);
responseTimeFailedThreshold = Integer.valueOf(timeFail);
responseTimeUnstableThreshold = Integer.valueOf(timeUnstable);
dataFolder = params.get(BlazeMeterConstants.SETTINGS_DATA_FOLDER);
if (PropertiesUtil.isEmptyOrNull(dataFolder)){
dataFolder = "";
}
dataFolder = dataFolder.trim();
mainJMX = params.get(BlazeMeterConstants.SETTINGS_MAIN_JMX);
logger.warning("File separator should be " + File.separator);
if (isNullorEmpty(mainJMX)) {
needTestUpload = false;
} else {
String agentCheckoutDir = agentRunningBuild.getCheckoutDirectory().getAbsolutePath();
if (!((agentCheckoutDir.endsWith("/") || agentCheckoutDir.endsWith("\\")))){//if the path doesn't have folder separator
agentCheckoutDir += File.separator;//make sure that the path ends with '/'
}
if (!isFullPath(dataFolder)){//full path
dataFolder = agentCheckoutDir + dataFolder;
}
File folder = new File(dataFolder);
if (!folder.exists() || !folder.isDirectory()){
return dataFolder + " could not be found on local file system, please check that the folder exists.";
}
needTestUpload = true;
}
return null;
}
private boolean isFullPath(String path){
if (path.startsWith("/")){
return true;
}
if (path.length() < 3) {
return false;
}
if (path.substring(0,1).matches("[a-zA-Z]")){//like D:/
if (path.substring(1, 2).equals(":") && (path.substring(2, 3).equals("/") || path.substring(2, 3).equals("\\"))){
return true;
}
}
return false;
}
/**
* Check if the value is null or empty
* @param value
* @return true if the value is null or empty, false otherwise
*/
private boolean isNullorEmpty(String value){
if ((value == null) || ("".equals(value))){
return true;
}
return false;
}
@Override
public void interrupt() {
logger.message("BlazeMeter agent interrupted.");
interrupted = true;
}
@Override
public boolean isFinished() {
return finished;
}
@Override
public boolean isInterrupted() {
return interrupted;
}
@Override
public void start() throws RunBuildException {
logger.message("BlazeMeter agent started.");
logger.activityStarted("Parameter validation", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
Map<String, String> runnerParams = buildRunnerContext.getRunnerParameters();
validationError = validateParams(runnerParams);
if (validationError != null){
logger.error(validationError);
} else {
logger.message("Validation passed.");
}
logger.activityFinished("Parameter validation", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
if (needTestUpload){
uploadDataFolderFiles();
}
if (validationError != null ){
throw new RunBuildException(validationError);
}
}
@SuppressWarnings("static-access")
@Override
public BuildFinishedStatus waitFor() throws RunBuildException {
logger.message("Attempting to start test with id:"+testId);
boolean started = blazeBean.startTest(testId, logger);
if (!started){
return BuildFinishedStatus.FINISHED_FAILED;
} else {
try {
//TODO nu cred ca e nevoie de file.separator
File file = new File(agentRunningBuild.getAgentTempDirectory().getAbsolutePath()+File.separator+"blaze_session.id");
if (!file.exists()){
file.createNewFile();
}
FileWriter fw;
fw = new FileWriter(file);
fw.write(blazeBean.getSession());
fw.flush();
fw.close();
artifactsWatcher.addNewArtifactsPath(file.getAbsolutePath());
} catch (IOException e) {
logger.error("Failed to save test session id! Error is:"+e.getMessage());
return BuildFinishedStatus.FINISHED_FAILED;
}
logger.message("Test started. Waiting " + testDuration + " minutes to finish!");
}
long totalWaitTime = (testDuration+2) * 60 * 1000;//the duration is in minutes so we multiply to get the value in ms
long nrOfCheckInterval = totalWaitTime / CHECK_INTERVAL;//
long currentCheck = 0;
logger.activityStarted("Check", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
TestInfo testInfo;
while (currentCheck++ < nrOfCheckInterval){
try {
Thread.currentThread().sleep(CHECK_INTERVAL);
} catch (InterruptedException e) {
}
logger.message("Check if the test is still running. Time passed since start:"+((currentCheck*CHECK_INTERVAL)/1000/60) + " minutes.");
testInfo = blazeBean.getTestStatus(testId);
if (testInfo.getStatus().equals(BlazeMeterConstants.TestStatus.NotRunning)){
logger.warning("Test is finished earlier then estimated! Time passed since start:"+((currentCheck*CHECK_INTERVAL)/1000/60) + " minutes.");
break;
}
else
if (testInfo.getStatus().equals(BlazeMeterConstants.TestStatus.NotFound)){
logger.error("Test not found!");
return BuildFinishedStatus.FINISHED_FAILED;
}
}
//BlazeMeter test stopped due to user test duration setup reached
logger.message("Stopping test...");
blazeBean.stopTest(testId, logger);
logger.activityFinished("Check", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
logger.message("Test finised. Checking for test report...");
//get testGetArchive information
boolean waitForReport = blazeBean.waitForReport(logger);
if (waitForReport){
int reportStatus = blazeBean.getReport(errorFailedThreshold, errorUnstableThreshold, responseTimeFailedThreshold, responseTimeUnstableThreshold, logger);
if (reportStatus != -1){
blazeBean.publishReportArtifact(agentRunningBuild.getAgentTempDirectory().getAbsolutePath() + File.separator + "teamcity-info.xml");
artifactsWatcher.addNewArtifactsPath(agentRunningBuild.getAgentTempDirectory().getAbsolutePath() + File.separator + "teamcity-info.xml");
}
switch (reportStatus) {
case -1:
return BuildFinishedStatus.FINISHED_FAILED;
case 0:
return BuildFinishedStatus.FINISHED_SUCCESS;
case 1:
return BuildFinishedStatus.FINISHED_WITH_PROBLEMS;
default:
return BuildFinishedStatus.FINISHED_WITH_PROBLEMS;
}
} else {
return BuildFinishedStatus.FINISHED_WITH_PROBLEMS;
}
}
/**
* Upload main JMX file and all the files from the data folder
*/
private void uploadDataFolderFiles() {
logger.activityStarted("Uploading data files", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
if (dataFolder == null || dataFolder.isEmpty()){
logger.error("Empty data folder. Please enter the path to your data folder or '.' for main folder where the files are checked out.");
logger.activityFinished("Uploading data files", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
return;
}
File folder = new File(dataFolder);
if (!folder.exists() || !folder.isDirectory()){
logger.error("dataFolder " + dataFolder + " could not be found on local file system, please check that the folder exists.");
logger.activityFinished("Uploading data files", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
return ;
} else {
logger.message("DataFolder "+dataFolder+" exists.");
}
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String file;
if (listOfFiles[i].isFile()) {
file = listOfFiles[i].getName();
if (file.endsWith(mainJMX)){
logger.message("Uploading main JMX "+mainJMX);
blazeBean.uploadJMX(testId, mainJMX, dataFolder + File.separator + mainJMX);
}
else {
logger.message("Uploading data files "+file);
blazeBean.uploadFile(testId, dataFolder, file, logger);
}
}
}
logger.activityFinished("Uploading data files", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
}
} | agent/src/com/blaze/agent/BlazeAgentProcessor.java | package com.blaze.agent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import jetbrains.buildServer.RunBuildException;
import jetbrains.buildServer.agent.AgentRunningBuild;
import jetbrains.buildServer.agent.BuildAgent;
import jetbrains.buildServer.agent.BuildFinishedStatus;
import jetbrains.buildServer.agent.BuildProcess;
import jetbrains.buildServer.agent.BuildProgressLogger;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.artifacts.ArtifactsWatcher;
import jetbrains.buildServer.messages.DefaultMessagesInfo;
import jetbrains.buildServer.util.PropertiesUtil;
import com.blaze.api.BlazeBean;
import com.blaze.api.TestInfo;
import com.blaze.runner.BlazeMeterConstants;
/**
* @author Marcel Milea
*
*/
public class BlazeAgentProcessor implements BuildProcess{
private static final int CHECK_INTERVAL = 60000;
private BlazeBean blazeBean;
private AgentRunningBuild agentRunningBuild;
private BuildRunnerContext buildRunnerContext;
private ArtifactsWatcher artifactsWatcher;
private String validationError;
private String testId;
private int testDuration;
int errorUnstableThreshold;
int errorFailedThreshold;
int responseTimeUnstableThreshold;
int responseTimeFailedThreshold;
String dataFolder;
String mainJMX;
final BuildProgressLogger logger;
boolean finished;
boolean needTestUpload;
boolean interrupted;
public BlazeAgentProcessor(BuildAgent buildAgent, AgentRunningBuild agentRunningBuild, BuildRunnerContext buildRunnerContext, ArtifactsWatcher artifactsWatcher) {
this.agentRunningBuild = agentRunningBuild;
this.buildRunnerContext = buildRunnerContext;
this.artifactsWatcher = artifactsWatcher;
this.finished = false;
logger = agentRunningBuild.getBuildLogger();
Map<String, String> buildSharedMap = agentRunningBuild.getSharedConfigParameters();
blazeBean = new BlazeBean(
buildSharedMap.get(BlazeMeterConstants.USER_KEY),
buildSharedMap.get(BlazeMeterConstants.PROXY_SERVER_NAME),
Integer.parseInt(buildSharedMap.get(BlazeMeterConstants.PROXY_SERVER_PORT)),
buildSharedMap.get(BlazeMeterConstants.PROXY_USERNAME),
buildSharedMap.get(BlazeMeterConstants.PROXY_PASSWORD));
}
private String validateParams(Map<String, String> params) {
testId = params.get(BlazeMeterConstants.SETTINGS_ALL_TESTS_ID);
if (isNullorEmpty(testId)) {
return "No test was defined in the configuration page.";
} else {
//verify if the test still exists on BlazeMeter server
HashMap<String, String> tests = blazeBean.getTests();
if (tests != null){
if (!tests.values().contains(testId)) {
return "Test removed from BlazeMeter server.";
}
}
}
String testDrt = params.get(BlazeMeterConstants.SETTINGS_TEST_DURATION);
if (isNullorEmpty(testDrt)) {
return "Test duration not set.";
} else {
try{
testDuration = Integer.valueOf(testDrt);
} catch (NumberFormatException nfe){
return "Test duration not a numbers.";
}
}
String errorUnstable = params.get(BlazeMeterConstants.SETTINGS_ERROR_THRESHOLD_UNSTABLE);
String errorFail = params.get(BlazeMeterConstants.SETTINGS_ERROR_THRESHOLD_FAIL);
String timeUnstable = params.get(BlazeMeterConstants.SETTINGS_RESPONSE_TIME_UNSTABLE);
String timeFail = params.get(BlazeMeterConstants.SETTINGS_RESPONSE_TIME_FAIL);
errorFailedThreshold = Integer.valueOf(errorFail);
errorUnstableThreshold = Integer.valueOf(errorUnstable);
responseTimeFailedThreshold = Integer.valueOf(timeFail);
responseTimeUnstableThreshold = Integer.valueOf(timeUnstable);
dataFolder = params.get(BlazeMeterConstants.SETTINGS_DATA_FOLDER);
if (PropertiesUtil.isEmptyOrNull(dataFolder)){
dataFolder = "";
}
dataFolder = dataFolder.trim();
mainJMX = params.get(BlazeMeterConstants.SETTINGS_MAIN_JMX);
logger.warning("File separator should be " + File.separator);
if (isNullorEmpty(mainJMX)) {
needTestUpload = false;
} else {
String agentCheckoutDir = agentRunningBuild.getCheckoutDirectory().getAbsolutePath();
if (!((agentCheckoutDir.endsWith("/") || agentCheckoutDir.endsWith("\\")))){//if the path doesn't have folder separator
agentCheckoutDir += File.separator;//make sure that the path ends with '/'
}
if (!isFullPath(dataFolder)){//full path
dataFolder = agentCheckoutDir + dataFolder;
}
File folder = new File(dataFolder);
if (!folder.exists() || !folder.isDirectory()){
return dataFolder + " could not be found on local file system, please check that the folder exists.";
}
needTestUpload = true;
}
return null;
}
private boolean isFullPath(String path){
if (path.startsWith("/")){
return true;
}
if (path.length() < 3) {
return false;
}
if (path.substring(0,1).matches("[a-zA-Z]")){//like D:/
if (path.substring(1, 2).equals(":") && (path.substring(2, 3).equals("/") || path.substring(2, 3).equals("\\"))){
return true;
}
}
return false;
}
/**
* Check if the value is null or empty
* @param value
* @return true if the value is null or empty, false otherwise
*/
private boolean isNullorEmpty(String value){
if ((value == null) || ("".equals(value))){
return true;
}
return false;
}
@Override
public void interrupt() {
logger.message("BlazeMeter agent interrupted.");
interrupted = true;
}
@Override
public boolean isFinished() {
return finished;
}
@Override
public boolean isInterrupted() {
return interrupted;
}
@Override
public void start() throws RunBuildException {
logger.message("BlazeMeter agent started.");
logger.activityStarted("Parameter validation", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
Map<String, String> runnerParams = buildRunnerContext.getRunnerParameters();
validationError = validateParams(runnerParams);
if (validationError != null){
logger.error(validationError);
} else {
logger.message("Validation passed.");
}
logger.activityFinished("Parameter validation", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
if (needTestUpload){
uploadDataFolderFiles();
}
if (validationError != null ){
throw new RunBuildException(validationError);
}
}
@SuppressWarnings("static-access")
@Override
public BuildFinishedStatus waitFor() throws RunBuildException {
logger.message("Attempting to start test with id:"+testId);
boolean started = blazeBean.startTest(testId, logger);
if (!started){
return BuildFinishedStatus.FINISHED_FAILED;
} else {
try {
//TODO nu cred ca e nevoie de file.separator
File file = new File(agentRunningBuild.getAgentTempDirectory().getAbsolutePath()+File.separator+"blaze_session.id");
if (!file.exists()){
file.createNewFile();
}
FileWriter fw;
fw = new FileWriter(file);
fw.write(blazeBean.getSession());
fw.flush();
fw.close();
artifactsWatcher.addNewArtifactsPath(file.getAbsolutePath());
} catch (IOException e) {
logger.error("Failed to save test session id! Error is:"+e.getMessage());
return BuildFinishedStatus.FINISHED_FAILED;
}
logger.message("Test started. Waiting " + testDuration + " minutes to finish!");
}
long totalWaitTime = (testDuration+2) * 60 * 1000;//the duration is in minutes so we multiply to get the value in ms
long nrOfCheckInterval = totalWaitTime / CHECK_INTERVAL;//
long currentCheck = 0;
logger.activityStarted("Check", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
TestInfo testInfo;
while (currentCheck++ < nrOfCheckInterval){
try {
Thread.currentThread().sleep(CHECK_INTERVAL);
} catch (InterruptedException e) {
}
logger.message("Check if the test is still running. Time passed since start:"+((currentCheck*CHECK_INTERVAL)/1000/60) + " minutes.");
testInfo = blazeBean.getTestStatus(testId);
if (testInfo.getStatus().equals(BlazeMeterConstants.TestStatus.NotRunning)){
logger.warning("Test is finished earlier then estimated! Time passed since start:"+((currentCheck*CHECK_INTERVAL)/1000/60) + " minutes.");
break;
}
else
if (testInfo.getStatus().equals(BlazeMeterConstants.TestStatus.NotFound)){
logger.error("Test not found!");
return BuildFinishedStatus.FINISHED_FAILED;
}
}
//BlazeMeter test stopped due to user test duration setup reached
logger.message("Stopping test...");
blazeBean.stopTest(testId, logger);
logger.activityFinished("Check", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
logger.message("Test finised. Checking for test report...");
//get testGetArchive information
boolean waitForReport = blazeBean.waitForReport(logger);
if (waitForReport){
int reportStatus = blazeBean.getReport(errorFailedThreshold, errorUnstableThreshold, responseTimeFailedThreshold, responseTimeUnstableThreshold, logger);
if (reportStatus != -1){
blazeBean.publishReportArtifact(agentRunningBuild.getAgentTempDirectory().getAbsolutePath() + File.separator + "teamcity-info.xml");
artifactsWatcher.addNewArtifactsPath(agentRunningBuild.getAgentTempDirectory().getAbsolutePath() + File.separator + "teamcity-info.xml");
}
switch (reportStatus) {
case -1:
return BuildFinishedStatus.FINISHED_FAILED;
case 0:
return BuildFinishedStatus.FINISHED_SUCCESS;
case 1:
return BuildFinishedStatus.FINISHED_WITH_PROBLEMS;
default:
return BuildFinishedStatus.FINISHED_WITH_PROBLEMS;
}
} else {
return BuildFinishedStatus.FINISHED_WITH_PROBLEMS;
}
}
/**
* Upload main JMX file and all the files from the data folder
*/
private void uploadDataFolderFiles() {
logger.activityStarted("Uploading data files", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
if (dataFolder == null || dataFolder.isEmpty()){
logger.error("Empty data folder. Please enter the path to your data folder or '.' for main folder where the files are checked out.");
logger.activityFinished("Uploading data files", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
return;
}
File folder = new File(dataFolder);
if (!folder.exists() || !folder.isDirectory()){
logger.error("dataFolder " + dataFolder + " could not be found on local file system, please check that the folder exists.");
logger.activityFinished("Uploading data files", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
return ;
} else {
logger.message("DataFolder "+dataFolder+" exists.");
}
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String file;
if (listOfFiles[i].isFile()) {
file = listOfFiles[i].getName();
if (file.endsWith(mainJMX)){
logger.message("Uploading main JMX "+mainJMX);
blazeBean.uploadJMX(testId, mainJMX, dataFolder + File.separator + mainJMX);
}
else {
logger.message("Uploading data files "+file);
blazeBean.uploadFile(testId, dataFolder, file, logger);
}
}
}
logger.activityFinished("Uploading data files", DefaultMessagesInfo.BLOCK_TYPE_BUILD_STEP);
}
} | JEN-24
| agent/src/com/blaze/agent/BlazeAgentProcessor.java | JEN-24 | <ide><path>gent/src/com/blaze/agent/BlazeAgentProcessor.java
<ide>
<ide> logger = agentRunningBuild.getBuildLogger();
<ide> Map<String, String> buildSharedMap = agentRunningBuild.getSharedConfigParameters();
<del> blazeBean = new BlazeBean(
<add> String proxyPortStr=buildSharedMap.get(BlazeMeterConstants.PROXY_SERVER_PORT);
<add> int proxyPortInt=0;
<add> if(proxyPortStr!=null&&!proxyPortStr.isEmpty()){
<add> proxyPortInt=Integer.parseInt(proxyPortStr);
<add> }
<add> blazeBean = new BlazeBean(
<ide> buildSharedMap.get(BlazeMeterConstants.USER_KEY),
<ide> buildSharedMap.get(BlazeMeterConstants.PROXY_SERVER_NAME),
<del> Integer.parseInt(buildSharedMap.get(BlazeMeterConstants.PROXY_SERVER_PORT)),
<del> buildSharedMap.get(BlazeMeterConstants.PROXY_USERNAME),
<add> proxyPortInt,
<add> buildSharedMap.get(BlazeMeterConstants.PROXY_USERNAME),
<ide> buildSharedMap.get(BlazeMeterConstants.PROXY_PASSWORD));
<ide> }
<ide> |
|
Java | bsd-3-clause | 9552ea2d171aaff8790fcc34cd70e148e83383b7 | 0 | ox-it/gaboto,ox-it/gaboto | /**
* Copyright 2009 University of Oxford
*
* Written by Arno Mittelbach for the Erewhon Project
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.oucs.gaboto.model.query;
import java.io.StringWriter;
import org.apache.log4j.Logger;
import org.oucs.gaboto.entities.pool.GabotoEntityPool;
import org.oucs.gaboto.entities.pool.GabotoEntityPoolConfiguration;
import org.oucs.gaboto.exceptions.GabotoException;
import org.oucs.gaboto.exceptions.GabotoRuntimeException;
import org.oucs.gaboto.exceptions.QueryAlreadyPreparedException;
import org.oucs.gaboto.exceptions.UnsupportedFormatException;
import org.oucs.gaboto.model.Gaboto;
import org.oucs.gaboto.model.GabotoFactory;
import org.oucs.gaboto.transformation.RDFPoolTransformerFactory;
import org.oucs.gaboto.transformation.json.JSONPoolTransformer;
import org.oucs.gaboto.transformation.kml.KMLPoolTransformer;
import com.hp.hpl.jena.rdf.model.Model;
/**
* Provides a base class to easily write queries against the Gaboto system
* that can then be transformed into different output formats.
*
*
* @author Arno Mittelbach
* @version 0.2
*/
abstract public class GabotoQueryImpl implements GabotoQuery {
private static Logger logger = Logger.getLogger(GabotoQueryImpl.class.getName());
private boolean prepared = false;
/**
* Describes that a Query creates a Jena {@link Model}
*/
protected final static int RESULT_TYPE_MODEL = 1;
/**
* Describes that a Query creates an {@link GabotoEntityPool}
*/
protected final static int RESULT_TYPE_ENTITY_POOL = 2;
/**
* Stores a reference to the Gaboto system that is to be used.
*/
private Gaboto gaboto;
/**
* Constructs the query and grabs an in-memory Gaboto object from the GabotoFactory.
*
* @throws GabotoException
*/
public GabotoQueryImpl() throws GabotoException{
this.gaboto = GabotoFactory.getInMemoryGaboto();
}
/**
* Constructor that allows to specifically set the Gaboto object this query object
* is working with.
*
* @param gaboto
*/
public GabotoQueryImpl(Gaboto gaboto){
this.gaboto = gaboto;
}
/**
* Returns the Gaboto model this query is working on.
*
* @return The Gaboto model this query is working on.
*/
public Gaboto getGaboto(){
return gaboto;
}
/**
* Sets the Gaboto model this query should be working on.
* @param gaboto The Gaboto model this query should be working on.
*/
public void setGaboto(Gaboto gaboto){
this.gaboto = gaboto;
}
/**
* Defines whether we are working with a EntityPool or a model.
*
* @return The return type of our execute method.
*
* @see #RESULT_TYPE_ENTITY_POOL
* @see #RESULT_TYPE_MODEL
*/
abstract public int getResultType();
/**
* Performs the actual query work and returns either a Jena {@link Model} or an {@link GabotoEntityPool} as defined by {@link #getResultType()}.
*
* @return Either a Jena Model or an GabotoEntityPool.
*
* @throws GabotoException
* @see #getResultType()
* @see #execute(String)
*/
abstract protected Object execute() throws GabotoException;
final public void prepare() throws QueryAlreadyPreparedException, GabotoException{
if(prepared)
throw new QueryAlreadyPreparedException();
// call prepare method
doPrepare();
// set flag
prepared = true;
}
abstract protected void doPrepare() throws GabotoException;
final public boolean isPrepared(){
return prepared;
}
/**
* Executes a query and transforms the result into the asked for output format (if supported).
*
* @param format The output format.
* @throws GabotoException
*/
public Object execute(String format) throws GabotoException {
logger.debug("Execute query " + this.getClass().getName() + " with requested format: " + format);
// prepare if it is not prepared
if(! isPrepared())
prepare();
if(! isSupportedFormat(format))
throw new UnsupportedFormatException(format);
Object result = execute();
switch(getResultType()){
case RESULT_TYPE_MODEL:
return formatResult((Model) result, format);
case RESULT_TYPE_ENTITY_POOL:
return formatResult((GabotoEntityPool)result, format);
default:
return result;
}
}
/**
* Formats results of the type {@link GabotoEntityPool} into the specified output format.
*
* @param pool The entity pool to be transformed.
* @param format The output format.
*
* @return The transformed pool.
*/
protected Object formatResult(GabotoEntityPool pool, String format) {
if(format.equals(GabotoQuery.FORMAT_JENA_MODEL))
return pool.createJenaModel();
if(format.equals(GabotoQuery.FORMAT_ENTITY_POOL))
return pool;
if(format.equals(GabotoQuery.FORMAT_RDF_XML) ||
format.equals(GabotoQuery.FORMAT_RDF_XML_ABBREV) ||
format.equals(GabotoQuery.FORMAT_RDF_TURTLE) ||
format.equals(GabotoQuery.FORMAT_RDF_N_TRIPLE) ||
format.equals(GabotoQuery.FORMAT_RDF_N3)){
try {
return RDFPoolTransformerFactory.getRDFPoolTransformer(format).transform(pool);
} catch (UnsupportedFormatException e) {
new GabotoRuntimeException(e);
}
}
if(format.equals(GabotoQuery.FORMAT_KML))
return new KMLPoolTransformer().transform(pool);
if(format.equals(GabotoQuery.FORMAT_JSON))
return new JSONPoolTransformer().transform(pool);
return formatResult_customFormat(pool, format);
}
/**
* Called if a supported output format was specified that cannot be handled by this abstract class.
*
* <p>
* Queries can override this method to implement custom transformations.
* </p>
*
* @param pool The pool to be transformed.
* @param format The output format.
* @return The pool per default.
*/
protected Object formatResult_customFormat(GabotoEntityPool pool, String format) {
return pool;
}
/**
* Formats results of the type Jena {@link Model} into the specified output format.
*
* @param model The Jena Model to be transformed.
* @param format The output format.
*
* @return The formatted model.
*/
protected Object formatResult(Model model, String format) {
if(format.equals(GabotoQuery.FORMAT_JENA_MODEL))
return model;
if(format.equals(GabotoQuery.FORMAT_ENTITY_POOL)){
return GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model));
}
if(format.equals(GabotoQuery.FORMAT_RDF_XML) ||
format.equals(GabotoQuery.FORMAT_RDF_XML_ABBREV) ||
format.equals(GabotoQuery.FORMAT_RDF_TURTLE) ||
format.equals(GabotoQuery.FORMAT_RDF_N_TRIPLE) ||
format.equals(GabotoQuery.FORMAT_RDF_N3)){
StringWriter sWriter = new StringWriter();
model.write(sWriter, format);
return sWriter.toString();
}
if(format.equals(GabotoQuery.FORMAT_KML)){
return new KMLPoolTransformer().transform(
GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model)));
}
if(format.equals(GabotoQuery.FORMAT_JSON)){
return new JSONPoolTransformer().transform(
GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model)));
}
return formatResult_customFormat(model, format);
}
/**
* Called if a supported output format was specified that cannot be handled by this abstract class.
*
* <p>
* Queries can override this method to implement custom transformations.
* </p>
*
* @param model The model to be transformed.
* @param format The output format.
* @return The model per default.
*/
protected Object formatResult_customFormat(Model model, String format) {
return model;
}
/**
* Tests if the query supports the passed output format.
*
* @param format The format
* @return True, if the format is supported.
*/
public boolean isSupportedFormat(String format){
for(String s : getSupportedFormats())
if(s.equals(format))
return true;
return false;
}
/**
* Defines the possible output formats that this query supports.
*
* @return An array with all output formats.
*/
public String[] getSupportedFormats() {
return new String[]{
GabotoQuery.FORMAT_JENA_MODEL,
GabotoQuery.FORMAT_ENTITY_POOL,
GabotoQuery.FORMAT_RDF_XML,
GabotoQuery.FORMAT_RDF_XML_ABBREV,
GabotoQuery.FORMAT_RDF_N3,
GabotoQuery.FORMAT_RDF_N_TRIPLE,
GabotoQuery.FORMAT_RDF_TURTLE,
GabotoQuery.FORMAT_TEI_XML,
GabotoQuery.FORMAT_KML,
GabotoQuery.FORMAT_JSON
};
}
}
| src/main/java/org/oucs/gaboto/model/query/GabotoQueryImpl.java | /**
* Copyright 2009 University of Oxford
*
* Written by Arno Mittelbach for the Erewhon Project
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.oucs.gaboto.model.query;
import java.io.StringWriter;
import org.apache.log4j.Logger;
import org.oucs.gaboto.entities.pool.GabotoEntityPool;
import org.oucs.gaboto.entities.pool.GabotoEntityPoolConfiguration;
import org.oucs.gaboto.exceptions.EntityPoolInvalidConfigurationException;
import org.oucs.gaboto.exceptions.GabotoException;
import org.oucs.gaboto.exceptions.QueryAlreadyPreparedException;
import org.oucs.gaboto.exceptions.UnsupportedFormatException;
import org.oucs.gaboto.model.Gaboto;
import org.oucs.gaboto.model.GabotoFactory;
import org.oucs.gaboto.transformation.RDFPoolTransformerFactory;
import org.oucs.gaboto.transformation.json.JSONPoolTransformer;
import org.oucs.gaboto.transformation.kml.KMLPoolTransformer;
import com.hp.hpl.jena.rdf.model.Model;
/**
* Provides a base class to easily write queries against the Gaboto system
* that can then be transformed into different output formats.
*
*
* @author Arno Mittelbach
* @version 0.2
*/
abstract public class GabotoQueryImpl implements GabotoQuery {
private static Logger logger = Logger.getLogger(GabotoQueryImpl.class.getName());
private boolean prepared = false;
/**
* Describes that a Query creates a Jena {@link Model}
*/
protected final static int RESULT_TYPE_MODEL = 1;
/**
* Describes that a Query creates an {@link GabotoEntityPool}
*/
protected final static int RESULT_TYPE_ENTITY_POOL = 2;
/**
* Stores a reference to the Gaboto system that is to be used.
*/
private Gaboto gaboto;
/**
* Constructs the query and grabs an in-memory Gaboto object from the GabotoFactory.
*
* @throws GabotoException
*/
public GabotoQueryImpl() throws GabotoException{
this.gaboto = GabotoFactory.getInMemoryGaboto();
}
/**
* Constructor that allows to specifically set the Gaboto object this query object
* is working with.
*
* @param gaboto
*/
public GabotoQueryImpl(Gaboto gaboto){
this.gaboto = gaboto;
}
/**
* Returns the Gaboto model this query is working on.
*
* @return The Gaboto model this query is working on.
*/
public Gaboto getGaboto(){
return gaboto;
}
/**
* Sets the Gaboto model this query should be working on.
* @param gaboto The Gaboto model this query should be working on.
*/
public void setGaboto(Gaboto gaboto){
this.gaboto = gaboto;
}
/**
* Defines whether we are working with a EntityPool or a model.
*
* @return The return type of our execute method.
*
* @see #RESULT_TYPE_ENTITY_POOL
* @see #RESULT_TYPE_MODEL
*/
abstract public int getResultType();
/**
* Performs the actual query work and returns either a Jena {@link Model} or an {@link GabotoEntityPool} as defined by {@link #getResultType()}.
*
* @return Either a Jena Model or an GabotoEntityPool.
*
* @throws GabotoException
* @see #getResultType()
* @see #execute(String)
*/
abstract protected Object execute() throws GabotoException;
final public void prepare() throws QueryAlreadyPreparedException, GabotoException{
if(prepared)
throw new QueryAlreadyPreparedException();
// call prepare method
doPrepare();
// set flag
prepared = true;
}
abstract protected void doPrepare() throws GabotoException;
final public boolean isPrepared(){
return prepared;
}
/**
* Executes a query and transforms the result into the asked for output format (if supported).
*
* @param format The output format.
* @throws GabotoException
*/
public Object execute(String format) throws GabotoException {
logger.debug("Execute query " + this.getClass().getName() + " with requested format: " + format);
// prepare if it is not prepared
if(! isPrepared())
prepare();
if(! isSupportedFormat(format))
throw new UnsupportedFormatException(format);
Object result = execute();
switch(getResultType()){
case RESULT_TYPE_MODEL:
return formatResult((Model) result, format);
case RESULT_TYPE_ENTITY_POOL:
return formatResult((GabotoEntityPool)result, format);
default:
return result;
}
}
/**
* Formats results of the type {@link GabotoEntityPool} into the specified output format.
*
* @param pool The entity pool to be transformed.
* @param format The output format.
*
* @return The transformed pool.
*/
protected Object formatResult(GabotoEntityPool pool, String format) {
if(format.equals(GabotoQuery.FORMAT_JENA_MODEL))
return pool.createJenaModel();
if(format.equals(GabotoQuery.FORMAT_ENTITY_POOL))
return pool;
if(format.equals(GabotoQuery.FORMAT_RDF_XML) ||
format.equals(GabotoQuery.FORMAT_RDF_XML_ABBREV) ||
format.equals(GabotoQuery.FORMAT_RDF_TURTLE) ||
format.equals(GabotoQuery.FORMAT_RDF_N_TRIPLE) ||
format.equals(GabotoQuery.FORMAT_RDF_N3)){
try {
return RDFPoolTransformerFactory.getRDFPoolTransformer(format).transform(pool);
} catch (UnsupportedFormatException e) {
e.printStackTrace();
}
}
if(format.equals(GabotoQuery.FORMAT_KML))
return new KMLPoolTransformer().transform(pool);
if(format.equals(GabotoQuery.FORMAT_JSON))
return new JSONPoolTransformer().transform(pool);
return formatResult_customFormat(pool, format);
}
/**
* Called if a supported output format was specified that cannot be handled by this abstract class.
*
* <p>
* Queries can override this method to implement custom transformations.
* </p>
*
* @param pool The pool to be transformed.
* @param format The output format.
* @return The pool per default.
*/
protected Object formatResult_customFormat(GabotoEntityPool pool, String format) {
return pool;
}
/**
* Formats results of the type Jena {@link Model} into the specified output format.
*
* @param model The Jena Model to be transformed.
* @param format The output format.
*
* @return The formatted model.
*/
protected Object formatResult(Model model, String format) {
if(format.equals(GabotoQuery.FORMAT_JENA_MODEL))
return model;
if(format.equals(GabotoQuery.FORMAT_ENTITY_POOL)){
try {
return GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model));
} catch (EntityPoolInvalidConfigurationException e) {
e.printStackTrace();
}
}
if(format.equals(GabotoQuery.FORMAT_RDF_XML) ||
format.equals(GabotoQuery.FORMAT_RDF_XML_ABBREV) ||
format.equals(GabotoQuery.FORMAT_RDF_TURTLE) ||
format.equals(GabotoQuery.FORMAT_RDF_N_TRIPLE) ||
format.equals(GabotoQuery.FORMAT_RDF_N3)){
StringWriter sWriter = new StringWriter();
model.write(sWriter, format);
return sWriter.toString();
}
if(format.equals(GabotoQuery.FORMAT_KML)){
try{
return new KMLPoolTransformer().transform(
GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model))
);
} catch (EntityPoolInvalidConfigurationException e) {
e.printStackTrace();
}
}
if(format.equals(GabotoQuery.FORMAT_JSON)){
try {
return new JSONPoolTransformer().transform(
GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model))
);
} catch (EntityPoolInvalidConfigurationException e) {
e.printStackTrace();
}
}
return formatResult_customFormat(model, format);
}
/**
* Called if a supported output format was specified that cannot be handled by this abstract class.
*
* <p>
* Queries can override this method to implement custom transformations.
* </p>
*
* @param model The model to be transformed.
* @param format The output format.
* @return The model per default.
*/
protected Object formatResult_customFormat(Model model, String format) {
return model;
}
/**
* Tests if the query supports the passed output format.
*
* @param format The format
* @return True, if the format is supported.
*/
public boolean isSupportedFormat(String format){
for(String s : getSupportedFormats())
if(s.equals(format))
return true;
return false;
}
/**
* Defines the possible output formats that this query supports.
*
* @return An array with all output formats.
*/
public String[] getSupportedFormats() {
return new String[]{
GabotoQuery.FORMAT_JENA_MODEL,
GabotoQuery.FORMAT_ENTITY_POOL,
GabotoQuery.FORMAT_RDF_XML,
GabotoQuery.FORMAT_RDF_XML_ABBREV,
GabotoQuery.FORMAT_RDF_N3,
GabotoQuery.FORMAT_RDF_N_TRIPLE,
GabotoQuery.FORMAT_RDF_TURTLE,
GabotoQuery.FORMAT_TEI_XML,
GabotoQuery.FORMAT_KML,
GabotoQuery.FORMAT_JSON
};
}
}
| Exception handling
| src/main/java/org/oucs/gaboto/model/query/GabotoQueryImpl.java | Exception handling | <ide><path>rc/main/java/org/oucs/gaboto/model/query/GabotoQueryImpl.java
<ide> import org.apache.log4j.Logger;
<ide> import org.oucs.gaboto.entities.pool.GabotoEntityPool;
<ide> import org.oucs.gaboto.entities.pool.GabotoEntityPoolConfiguration;
<del>import org.oucs.gaboto.exceptions.EntityPoolInvalidConfigurationException;
<ide> import org.oucs.gaboto.exceptions.GabotoException;
<add>import org.oucs.gaboto.exceptions.GabotoRuntimeException;
<ide> import org.oucs.gaboto.exceptions.QueryAlreadyPreparedException;
<ide> import org.oucs.gaboto.exceptions.UnsupportedFormatException;
<ide> import org.oucs.gaboto.model.Gaboto;
<ide> try {
<ide> return RDFPoolTransformerFactory.getRDFPoolTransformer(format).transform(pool);
<ide> } catch (UnsupportedFormatException e) {
<del> e.printStackTrace();
<add> new GabotoRuntimeException(e);
<ide> }
<ide> }
<ide>
<ide> return model;
<ide>
<ide> if(format.equals(GabotoQuery.FORMAT_ENTITY_POOL)){
<del> try {
<del> return GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model));
<del> } catch (EntityPoolInvalidConfigurationException e) {
<del> e.printStackTrace();
<del> }
<add> return GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model));
<ide> }
<ide>
<ide> if(format.equals(GabotoQuery.FORMAT_RDF_XML) ||
<ide> }
<ide>
<ide> if(format.equals(GabotoQuery.FORMAT_KML)){
<del> try{
<del> return new KMLPoolTransformer().transform(
<del> GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model))
<del> );
<del> } catch (EntityPoolInvalidConfigurationException e) {
<del> e.printStackTrace();
<del> }
<del> }
<add> return new KMLPoolTransformer().transform(
<add> GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model)));
<add> }
<ide>
<ide> if(format.equals(GabotoQuery.FORMAT_JSON)){
<del> try {
<del> return new JSONPoolTransformer().transform(
<del> GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model))
<del> );
<del> } catch (EntityPoolInvalidConfigurationException e) {
<del> e.printStackTrace();
<del> }
<add> return new JSONPoolTransformer().transform(
<add> GabotoEntityPool.createFrom(new GabotoEntityPoolConfiguration(getGaboto(), model)));
<ide> }
<ide>
<ide> return formatResult_customFormat(model, format); |
|
Java | apache-2.0 | 36adebc6ba30e19fc5b40175d723b03ba873923f | 0 | joobn72/qi4j-sdk,Qi4j/qi4j-sdk,apache/zest-qi4j,ramtej/Qi4j.Repo.4.Sync,Qi4j/qi4j-libraries,apache/zest-qi4j,Qi4j/qi4j-sdk,joobn72/qi4j-sdk,apache/zest-qi4j,Qi4j/qi4j-libraries,ramtej/Qi4j.Repo.4.Sync,Qi4j/qi4j-libraries,apache/zest-qi4j,apache/zest-qi4j,joobn72/qi4j-sdk,joobn72/qi4j-sdk,Qi4j/qi4j-sdk,joobn72/qi4j-sdk,Qi4j/qi4j-sdk,ramtej/Qi4j.Repo.4.Sync,ramtej/Qi4j.Repo.4.Sync,Qi4j/qi4j-sdk,ramtej/Qi4j.Repo.4.Sync,ramtej/Qi4j.Repo.4.Sync,Qi4j/qi4j-libraries,joobn72/qi4j-sdk,Qi4j/qi4j-libraries | /*
* Copyright 2008 Wen Tao. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qi4j.library.beans.properties;
import java.lang.reflect.Method;
import org.qi4j.composite.AppliesToFilter;
public final class OrAppliesToFilter
implements AppliesToFilter
{
private final AppliesToFilter[] filters;
public OrAppliesToFilter( AppliesToFilter... filters )
{
this.filters = filters;
}
public final boolean appliesTo( Method method, Class<?> mixin, Class<?> compositeType, Class<?> fragmentClass )
{
for( AppliesToFilter filter : filters )
{
if( filter.appliesTo( method, mixin, compositeType, fragmentClass ) )
{
return true;
}
}
return false;
}
}
| beans/src/main/java/org/qi4j/library/beans/properties/OrAppliesToFilter.java | /*
* Copyright 2008 Wen Tao. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qi4j.library.beans.properties;
import org.qi4j.composite.AppliesToFilter;
import java.lang.reflect.Method;
public final class OrAppliesToFilter implements AppliesToFilter
{
private final AppliesToFilter[] filters;
public OrAppliesToFilter( AppliesToFilter... filters )
{
this.filters = filters;
}
public boolean appliesTo( Method method, Class<?> mixin, Class<?> compositeType, Class<?> fragmentClass )
{
for( AppliesToFilter filter : filters )
{
if( !filter.appliesTo( method, mixin, compositeType, fragmentClass ) )
{
return false;
}
}
return true;
}
}
| Fix bug where OrAppliesToFilter behaves like 'and' instead of 'or'
git-svn-id: c1a2cac32c804c97d56fc837c7a57bdf32d4af98@13421 9b982a3c-3ae5-0310-a4bc-d9a3335569bd
| beans/src/main/java/org/qi4j/library/beans/properties/OrAppliesToFilter.java | Fix bug where OrAppliesToFilter behaves like 'and' instead of 'or' | <ide><path>eans/src/main/java/org/qi4j/library/beans/properties/OrAppliesToFilter.java
<ide> */
<ide> package org.qi4j.library.beans.properties;
<ide>
<add>import java.lang.reflect.Method;
<ide> import org.qi4j.composite.AppliesToFilter;
<del>import java.lang.reflect.Method;
<ide>
<del>public final class OrAppliesToFilter implements AppliesToFilter
<add>public final class OrAppliesToFilter
<add> implements AppliesToFilter
<ide> {
<ide> private final AppliesToFilter[] filters;
<ide>
<ide> this.filters = filters;
<ide> }
<ide>
<del> public boolean appliesTo( Method method, Class<?> mixin, Class<?> compositeType, Class<?> fragmentClass )
<add> public final boolean appliesTo( Method method, Class<?> mixin, Class<?> compositeType, Class<?> fragmentClass )
<ide> {
<ide> for( AppliesToFilter filter : filters )
<ide> {
<del> if( !filter.appliesTo( method, mixin, compositeType, fragmentClass ) )
<add> if( filter.appliesTo( method, mixin, compositeType, fragmentClass ) )
<ide> {
<del> return false;
<add> return true;
<ide> }
<ide> }
<del> return true;
<add> return false;
<ide> }
<ide> } |
|
Java | apache-2.0 | e3c1ceddf4df05bd434deec40d65c30c8050167c | 0 | hurricup/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,kool79/intellij-community,ernestp/consulo,xfournet/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,caot/intellij-community,diorcety/intellij-community,ernestp/consulo,lucafavatella/intellij-community,clumsy/intellij-community,blademainer/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,slisson/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,joewalnes/idea-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,xfournet/intellij-community,blademainer/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,jexp/idea2,tmpgit/intellij-community,retomerz/intellij-community,semonte/intellij-community,allotria/intellij-community,da1z/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,jexp/idea2,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,diorcety/intellij-community,vladmm/intellij-community,ryano144/intellij-community,samthor/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,holmes/intellij-community,semonte/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,diorcety/intellij-community,clumsy/intellij-community,allotria/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,semonte/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,asedunov/intellij-community,robovm/robovm-studio,samthor/intellij-community,caot/intellij-community,dslomov/intellij-community,ryano144/intellij-community,holmes/intellij-community,retomerz/intellij-community,xfournet/intellij-community,da1z/intellij-community,da1z/intellij-community,joewalnes/idea-community,holmes/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,clumsy/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,jagguli/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,holmes/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,allotria/intellij-community,slisson/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,robovm/robovm-studio,fnouama/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,consulo/consulo,michaelgallacher/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,consulo/consulo,asedunov/intellij-community,adedayo/intellij-community,samthor/intellij-community,xfournet/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,ibinti/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,allotria/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,izonder/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,samthor/intellij-community,dslomov/intellij-community,semonte/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ibinti/intellij-community,jexp/idea2,izonder/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,asedunov/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,kool79/intellij-community,allotria/intellij-community,fitermay/intellij-community,allotria/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,caot/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,supersven/intellij-community,signed/intellij-community,holmes/intellij-community,nicolargo/intellij-community,allotria/intellij-community,Distrotech/intellij-community,jexp/idea2,adedayo/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,slisson/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,fitermay/intellij-community,blademainer/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,jexp/idea2,nicolargo/intellij-community,ibinti/intellij-community,kool79/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,slisson/intellij-community,izonder/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,signed/intellij-community,apixandru/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,ryano144/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,consulo/consulo,blademainer/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,asedunov/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,hurricup/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ernestp/consulo,da1z/intellij-community,apixandru/intellij-community,adedayo/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,apixandru/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,ernestp/consulo,xfournet/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,consulo/consulo,semonte/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,da1z/intellij-community,izonder/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,ryano144/intellij-community,retomerz/intellij-community,FHannes/intellij-community,diorcety/intellij-community,asedunov/intellij-community,holmes/intellij-community,jagguli/intellij-community,kool79/intellij-community,FHannes/intellij-community,da1z/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,da1z/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,signed/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,allotria/intellij-community,jagguli/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,dslomov/intellij-community,signed/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,fnouama/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,signed/intellij-community,dslomov/intellij-community,FHannes/intellij-community,joewalnes/idea-community,izonder/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,fnouama/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,jexp/idea2,kdwink/intellij-community,amith01994/intellij-community,ryano144/intellij-community,kool79/intellij-community,slisson/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,supersven/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,samthor/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,slisson/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,vladmm/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,signed/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,signed/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,signed/intellij-community,xfournet/intellij-community,caot/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,amith01994/intellij-community,caot/intellij-community,petteyg/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,fitermay/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,xfournet/intellij-community,kool79/intellij-community,fitermay/intellij-community,diorcety/intellij-community,kool79/intellij-community,fnouama/intellij-community,jagguli/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,samthor/intellij-community,caot/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,signed/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,jexp/idea2,pwoodworth/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,adedayo/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,slisson/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,FHannes/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,amith01994/intellij-community,caot/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,caot/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,signed/intellij-community,vladmm/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,clumsy/intellij-community,adedayo/intellij-community,samthor/intellij-community,Distrotech/intellij-community,supersven/intellij-community,signed/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,consulo/consulo,ftomassetti/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ibinti/intellij-community,asedunov/intellij-community,robovm/robovm-studio,FHannes/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,izonder/intellij-community,retomerz/intellij-community,supersven/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,samthor/intellij-community,consulo/consulo,allotria/intellij-community,signed/intellij-community,holmes/intellij-community,ernestp/consulo,holmes/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,amith01994/intellij-community,petteyg/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,allotria/intellij-community,robovm/robovm-studio,kdwink/intellij-community,caot/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,diorcety/intellij-community,kool79/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,kool79/intellij-community,ernestp/consulo,fnouama/intellij-community,caot/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community | package com.intellij.psi.formatter.java;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.formatter.common.AbstractBlock;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.parsing.ChameleonTransforming;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.impl.source.tree.java.ClassElement;
import com.intellij.psi.jsp.JspElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.AbstractJavaBlock");
protected final CodeStyleSettings mySettings;
private final Indent myIndent;
protected Indent myChildIndent;
protected Alignment myChildAlignment;
protected boolean myUseChildAttributes = false;
private boolean myIsAfterClassKeyword = false;
private Wrap myAnnotationWrap = null;
protected AbstractJavaBlock(final ASTNode node,
final Wrap wrap,
final Alignment alignment,
final Indent indent,
final CodeStyleSettings settings) {
super(node, wrap, alignment);
mySettings = settings;
myIndent = indent;
}
public static Block createJavaBlock(final ASTNode child,
final CodeStyleSettings settings,
final Indent indent,
Wrap wrap,
Alignment alignment) {
return createJavaBlock(child, settings, indent, wrap, alignment, -1);
}
public static Block createJavaBlock(final ASTNode child,
final CodeStyleSettings settings,
final Indent indent,
Wrap wrap,
Alignment alignment,
int startOffset
) {
Indent actualIndent = indent == null ? getDefaultSubtreeIndent(child) : indent;
final IElementType elementType = child.getElementType();
if (child.getPsi() instanceof PsiWhiteSpace) {
String text = child.getText();
int start = CharArrayUtil.shiftForward(text, 0, " \t\n");
int end = CharArrayUtil.shiftBackward(text, text.length() - 1, " \t\n") + 1;
LOG.assertTrue(start < end);
return new PartialWhitespaceBlock(child, new TextRange(start + child.getStartOffset(), end + child.getStartOffset()),
wrap, alignment, actualIndent, settings);
}
if (child.getPsi() instanceof PsiClass) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings);
}
if (isBlockType(elementType)) {
return new BlockContainingJavaBlock(child, wrap, alignment, actualIndent, settings);
}
if (isStatement(child, child.getTreeParent())) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings);
}
if (child instanceof LeafElement) {
final LeafBlock block = new LeafBlock(child, wrap, alignment, actualIndent);
block.setStartOffset(startOffset);
return block;
}
else if (isLikeExtendsList(elementType)) {
return new ExtendsListBlock(child, wrap, alignment, settings);
}
else if (elementType == JavaElementType.CODE_BLOCK) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings);
}
else if (elementType == JavaElementType.LABELED_STATEMENT) {
return new LabeledJavaBlock(child, wrap, alignment, actualIndent, settings);
}
else if (elementType == JavaDocElementType.DOC_COMMENT) {
return new DocCommentBlock(child, wrap, alignment, actualIndent, settings);
}
else {
final SimpleJavaBlock simpleJavaBlock = new SimpleJavaBlock(child, wrap, alignment, actualIndent, settings);
simpleJavaBlock.setStartOffset(startOffset);
return simpleJavaBlock;
}
}
private static boolean isLikeExtendsList(final IElementType elementType) {
return elementType == JavaElementType.EXTENDS_LIST
|| elementType == JavaElementType.IMPLEMENTS_LIST
|| elementType == JavaElementType.THROWS_LIST;
}
private static boolean isBlockType(final IElementType elementType) {
return elementType == JavaElementType.SWITCH_STATEMENT
|| elementType == JavaElementType.FOR_STATEMENT
|| elementType == JavaElementType.WHILE_STATEMENT
|| elementType == JavaElementType.DO_WHILE_STATEMENT
|| elementType == JavaElementType.TRY_STATEMENT
|| elementType == JavaElementType.CATCH_SECTION
|| elementType == JavaElementType.IF_STATEMENT
|| elementType == JavaElementType.METHOD
|| elementType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION
|| elementType == JavaElementType.CLASS_INITIALIZER
|| elementType == JavaElementType.SYNCHRONIZED_STATEMENT
|| elementType == JavaElementType.FOREACH_STATEMENT;
}
public static Block createJavaBlock(final ASTNode child, final CodeStyleSettings settings) {
return createJavaBlock(child, settings, getDefaultSubtreeIndent(child), null, null);
}
@Nullable
private static Indent getDefaultSubtreeIndent(final ASTNode child) {
final ASTNode parent = child.getTreeParent();
final IElementType childNodeType = child.getElementType();
if (childNodeType == JavaElementType.ANNOTATION) return Indent.getNoneIndent();
final ASTNode prevElement = getPrevElement(child);
if (prevElement != null && prevElement.getElementType() == JavaElementType.MODIFIER_LIST) {
return Indent.getNoneIndent();
}
if (childNodeType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (childNodeType == JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS) return Indent.getSpaceIndent(1);
if (child.getPsi() instanceof PsiFile) return Indent.getNoneIndent();
if (parent != null) {
final Indent defaultChildIndent = getChildIndent(parent);
if (defaultChildIndent != null) return defaultChildIndent;
}
return null;
}
@Nullable
private static Indent getChildIndent(final ASTNode parent) {
final IElementType parentType = parent.getElementType();
if (parentType == JavaElementType.MODIFIER_LIST) return Indent.getNoneIndent();
if (parentType == JspElementType.JSP_CODE_BLOCK) return Indent.getNormalIndent();
if (parentType == JspElementType.JSP_CLASS_LEVEL_DECLARATION_STATEMENT) return Indent.getNormalIndent();
if (parentType == ElementType.DUMMY_HOLDER) return Indent.getNoneIndent();
if (parentType == JavaElementType.CLASS) return Indent.getNoneIndent();
if (parentType == JavaElementType.IF_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.TRY_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.CATCH_SECTION) return Indent.getNoneIndent();
if (parentType == JavaElementType.FOR_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.FOREACH_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.BLOCK_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.DO_WHILE_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.WHILE_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.SWITCH_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.METHOD) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_COMMENT) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_INLINE_TAG) return Indent.getNoneIndent();
if (parentType == JavaElementType.IMPORT_LIST) return Indent.getNoneIndent();
if (SourceTreeToPsiMap.treeElementToPsi(parent) instanceof PsiFile) {
return Indent.getNoneIndent();
}
else {
return null;
}
}
public Spacing getSpacing(Block child1, Block child2) {
return JavaSpacePropertyProcessor.getSpacing(getTreeNode(child2), mySettings);
}
public ASTNode getFirstTreeNode() {
return myNode;
}
public Indent getIndent() {
return myIndent;
}
protected static boolean isStatement(final ASTNode child, final ASTNode parentNode) {
if (parentNode != null) {
final IElementType parentType = parentNode.getElementType();
if (parentType == JavaElementType.CODE_BLOCK) return false;
final int role = ((CompositeElement)parentNode).getChildRole(child);
if (parentType == JavaElementType.IF_STATEMENT) return role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH;
if (parentType == JavaElementType.FOR_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.DO_WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.FOREACH_STATEMENT) return role == ChildRole.LOOP_BODY;
}
return false;
}
@Nullable
protected Wrap createChildWrap() {
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.EXTENDS_LIST_WRAP), false);
}
else if (nodeType == JavaElementType.BINARY_EXPRESSION) {
Wrap actualWrap = myWrap != null ? myWrap : getReservedWrap();
if (actualWrap == null) {
return Wrap.createWrap(getWrapType(mySettings.BINARY_OPERATION_WRAP), false);
}
else {
if (!hasTheSamePriority(myNode.getTreeParent())) {
return Wrap.createChildWrap(actualWrap, getWrapType(mySettings.BINARY_OPERATION_WRAP), false);
}
else {
return actualWrap;
}
}
}
else if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
return Wrap.createWrap(getWrapType(mySettings.TERNARY_OPERATION_WRAP), false);
}
else if (nodeType == JavaElementType.ASSERT_STATEMENT) {
return Wrap.createWrap(getWrapType(mySettings.ASSERT_STATEMENT_WRAP), false);
}
else if (nodeType == JavaElementType.FOR_STATEMENT) {
return Wrap.createWrap(getWrapType(mySettings.FOR_STATEMENT_WRAP), false);
}
else if (nodeType == JavaElementType.THROWS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.THROWS_LIST_WRAP), true);
}
else if (nodeType == JavaElementType.CODE_BLOCK) {
return Wrap.createWrap(Wrap.NORMAL, false);
}
else if (isAssignment()) {
return Wrap.createWrap(getWrapType(mySettings.ASSIGNMENT_WRAP), true);
}
else {
return null;
}
}
private boolean isAssignment() {
final IElementType nodeType = myNode.getElementType();
return nodeType == JavaElementType.ASSIGNMENT_EXPRESSION || nodeType == JavaElementType.LOCAL_VARIABLE
|| nodeType == JavaElementType.FIELD;
}
@Nullable
protected Alignment createChildAlignment() {
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) {
if (myNode.getTreeParent() != null
&& myNode.getTreeParent().getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION
&& myAlignment != null) {
return myAlignment;
}
else {
return createAlignment(mySettings.ALIGN_MULTILINE_ASSIGNMENT, null);
}
}
else if (nodeType == JavaElementType.PARENTH_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION, null);
}
else if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_TERNARY_OPERATION, null);
}
else if (nodeType == JavaElementType.FOR_STATEMENT) {
return createAlignment(mySettings.ALIGN_MULTILINE_FOR, null);
}
else if (nodeType == JavaElementType.EXTENDS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null);
}
else if (nodeType == JavaElementType.IMPLEMENTS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null);
}
else if (nodeType == JavaElementType.THROWS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_THROWS_LIST, null);
}
else if (nodeType == JavaElementType.PARAMETER_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARAMETERS, null);
}
else if (nodeType == JavaElementType.BINARY_EXPRESSION) {
Alignment defaultAlignment = null;
if (shouldInheritAlignment()) {
defaultAlignment = myAlignment;
}
return createAlignment(mySettings.ALIGN_MULTILINE_BINARY_OPERATION, defaultAlignment);
}
else if (nodeType == JavaElementType.CLASS) {
return Alignment.createAlignment();
}
else if (nodeType == JavaElementType.METHOD) {
return Alignment.createAlignment();
}
else {
return null;
}
}
private boolean shouldInheritAlignment() {
if (myNode.getElementType() == JavaElementType.BINARY_EXPRESSION) {
final ASTNode treeParent = myNode.getTreeParent();
if (treeParent != null && treeParent.getElementType() == JavaElementType.BINARY_EXPRESSION) {
return hasTheSamePriority(treeParent);
}
}
return false;
}
protected ASTNode processChild(final ArrayList<Block> result,
ASTNode child,
Alignment defaultAlignment,
final Wrap defaultWrap,
final Indent childIndent) {
return processChild(result, child, defaultAlignment, defaultWrap, childIndent, -1);
}
protected ASTNode processChild(final ArrayList<Block> result,
ASTNode child,
Alignment defaultAlignment,
final Wrap defaultWrap,
final Indent childIndent,
int childOffset) {
final IElementType childType = child.getElementType();
if (childType == JavaTokenType.CLASS_KEYWORD || childType == JavaTokenType.INTERFACE_KEYWORD) {
myIsAfterClassKeyword = true;
}
if (childType == JavaElementType.METHOD_CALL_EXPRESSION) {
result.add(createMethodCallExpressiobBlock(child,
arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment)));
}
else {
final IElementType nodeType = myNode.getElementType();
if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
child = processParenBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE,
result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.EXPRESSION_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
if (mySettings.PREFER_PARAMETERS_WRAP) {
wrap.ignoreParentWraps();
}
child = processParenBlock(result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARAMETER_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
child = processParenBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.ANNOTATION_PARAMETER_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
child = processParenBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARENTH_EXPRESSION) {
child = processParenBlock(result, child,
WrappingStrategy.DO_NOT_WRAP,
mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION);
}
else if (childType == JavaElementType.ENUM_CONSTANT && myNode instanceof ClassElement) {
child = processEnumBlock(result, child, ((ClassElement)myNode).findEnumConstantListDelimiterPlace());
}
else if (mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE && isTernaryOperationSign(child)) {
child = processTernaryOperationRange(result, child, defaultAlignment, defaultWrap, childIndent);
}
else if (childType == JavaElementType.FIELD) {
child = processField(result, child, defaultAlignment, defaultWrap, childIndent);
}
else {
final Block block =
createJavaBlock(child, mySettings, childIndent, arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment), childOffset);
if (childType == JavaElementType.MODIFIER_LIST && containsAnnotations(child)) {
myAnnotationWrap = Wrap.createWrap(getWrapType(getAnnotationWrapType()), true);
}
if (block instanceof AbstractJavaBlock) {
final AbstractJavaBlock javaBlock = (AbstractJavaBlock)block;
if (nodeType == JavaElementType.METHOD_CALL_EXPRESSION && childType == JavaElementType.REFERENCE_EXPRESSION) {
javaBlock.setReservedWrap(getReservedWrap());
}
else if (nodeType == JavaElementType.REFERENCE_EXPRESSION &&
childType == JavaElementType.METHOD_CALL_EXPRESSION) {
javaBlock.setReservedWrap(getReservedWrap());
}
else if (nodeType == JavaElementType.BINARY_EXPRESSION) {
javaBlock.setReservedWrap(defaultWrap);
}
else if (childType == JavaElementType.MODIFIER_LIST) {
javaBlock.setReservedWrap(myAnnotationWrap);
if (!lastChildIsAnnotation(child)) {
myAnnotationWrap = null;
}
}
}
result.add(block);
}
}
return child;
}
private ASTNode processField(final ArrayList<Block> result, ASTNode child, final Alignment defaultAlignment, final Wrap defaultWrap,
final Indent childIndent) {
ASTNode lastFieldInGroup = findLastFieldInGroup(child);
if (lastFieldInGroup == child) {
result.add(createJavaBlock(child, getSettings(), childIndent, arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment)));
return child;
}
else {
final ArrayList<Block> localResult = new ArrayList<Block>();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
localResult.add(createJavaBlock(child, getSettings(), Indent.getContinuationWithoutFirstIndent(), arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment)));
}
if (child == lastFieldInGroup) break;
child = child.getTreeNext();
}
if (!localResult.isEmpty()) {
result.add(new SyntheticCodeBlock(localResult, null, getSettings(), childIndent, null));
}
return lastFieldInGroup;
}
}
@NotNull private static ASTNode findLastFieldInGroup(final ASTNode child) {
final PsiTypeElement typeElement = ((PsiVariable)child.getPsi()).getTypeElement();
if (typeElement == null) return child;
ASTNode lastChildNode = child.getLastChildNode();
if (lastChildNode == null) return child;
if (lastChildNode.getElementType() == JavaTokenType.SEMICOLON) return child;
ASTNode currentResult = child;
ASTNode currentNode = child.getTreeNext();
while (currentNode != null) {
if (currentNode.getElementType() == TokenType.WHITE_SPACE
|| currentNode.getElementType() == JavaTokenType.COMMA
|| StdTokenSets.COMMENT_BIT_SET.contains(currentNode.getElementType())) {
}
else if (currentNode.getElementType() == JavaElementType.FIELD) {
if (((PsiVariable)currentNode.getPsi()).getTypeElement() != typeElement) {
return currentResult;
}
else {
currentResult = currentNode;
}
}
else {
return currentResult;
}
currentNode = currentNode.getTreeNext();
}
return currentResult;
}
private ASTNode processTernaryOperationRange(final ArrayList<Block> result,
final ASTNode child,
final Alignment defaultAlignment,
final Wrap defaultWrap, final Indent childIndent) {
final ArrayList<Block> localResult = new ArrayList<Block>();
final Wrap wrap = arrangeChildWrap(child, defaultWrap);
final Alignment alignment = arrangeChildAlignment(child, defaultAlignment);
localResult.add(new LeafBlock(child, wrap, alignment, childIndent));
ASTNode current = child.getTreeNext();
while (current != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(current) && current.getTextLength() > 0) {
if (isTernaryOperationSign(current)) break;
current = processChild(localResult, current, defaultAlignment, defaultWrap, childIndent);
}
if (current != null) {
current = current.getTreeNext();
}
}
result.add(new SyntheticCodeBlock(localResult, alignment, getSettings(), null, wrap));
if (current == null) {
return null;
}
else {
return current.getTreePrev();
}
}
private boolean isTernaryOperationSign(final ASTNode child) {
if (myNode.getElementType() != JavaElementType.CONDITIONAL_EXPRESSION) return false;
final int role = ((CompositeElement)child.getTreeParent()).getChildRole(child);
return role == ChildRole.OPERATION_SIGN || role == ChildRole.COLON;
}
private Block createMethodCallExpressiobBlock(final ASTNode node, final Wrap blockWrap, final Alignment alignment) {
final ArrayList<ASTNode> nodes = new ArrayList<ASTNode>();
final ArrayList<Block> subBlocks = new ArrayList<Block>();
collectNodes(nodes, node);
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.METHOD_CALL_CHAIN_WRAP), false);
while (!nodes.isEmpty()) {
ArrayList<ASTNode> subNodes = readToNextDot(nodes);
subBlocks.add(createSynthBlock(subNodes, wrap));
}
return new SyntheticCodeBlock(subBlocks, alignment, mySettings, Indent.getContinuationWithoutFirstIndent(),
blockWrap);
}
private Block createSynthBlock(final ArrayList<ASTNode> subNodes, final Wrap wrap) {
final ArrayList<Block> subBlocks = new ArrayList<Block>();
final ASTNode firstNode = subNodes.get(0);
if (firstNode.getElementType() == JavaTokenType.DOT) {
subBlocks.add(createJavaBlock(firstNode, getSettings(), Indent.getNoneIndent(),
null,
null));
subNodes.remove(0);
if (!subNodes.isEmpty()) {
subBlocks.add(createSynthBlock(subNodes, wrap));
}
return new SyntheticCodeBlock(subBlocks, null, mySettings, Indent.getContinuationIndent(), wrap);
}
else {
return new SyntheticCodeBlock(createJavaBlocks(subNodes), null, mySettings,
Indent.getContinuationWithoutFirstIndent(), null);
}
}
private List<Block> createJavaBlocks(final ArrayList<ASTNode> subNodes) {
final ArrayList<Block> result = new ArrayList<Block>();
for (ASTNode node : subNodes) {
result.add(createJavaBlock(node, getSettings(), Indent.getContinuationWithoutFirstIndent(), null, null));
}
return result;
}
private static ArrayList<ASTNode> readToNextDot(final ArrayList<ASTNode> nodes) {
final ArrayList<ASTNode> result = new ArrayList<ASTNode>();
result.add(nodes.remove(0));
for (Iterator<ASTNode> iterator = nodes.iterator(); iterator.hasNext();) {
ASTNode node = iterator.next();
if (node.getElementType() == JavaTokenType.DOT) return result;
result.add(node);
iterator.remove();
}
return result;
}
private static void collectNodes(List<ASTNode> nodes, ASTNode node) {
ChameleonTransforming.transformChildren(node);
ASTNode child = node.getFirstChildNode();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
if (child.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION || child.getElementType() ==
JavaElementType
.REFERENCE_EXPRESSION) {
collectNodes(nodes, child);
}
else {
nodes.add(child);
}
}
child = child.getTreeNext();
}
}
private static boolean lastChildIsAnnotation(final ASTNode child) {
ASTNode current = child.getLastChildNode();
while (current != null && current.getElementType() == TokenType.WHITE_SPACE) {
current = current.getTreePrev();
}
return current != null && current.getElementType() == JavaElementType.ANNOTATION;
}
private static boolean containsAnnotations(final ASTNode child) {
return ((PsiModifierList)child.getPsi()).getAnnotations().length > 0;
}
private int getAnnotationWrapType() {
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.METHOD) {
return mySettings.METHOD_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.CLASS) {
return mySettings.CLASS_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.FIELD) {
return mySettings.FIELD_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.PARAMETER) {
return mySettings.PARAMETER_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.LOCAL_VARIABLE) {
return mySettings.VARIABLE_ANNOTATION_WRAP;
}
return CodeStyleSettings.DO_NOT_WRAP;
}
@Nullable
private Alignment arrangeChildAlignment(final ASTNode child, final Alignment defaultAlignment) {
int role = ((CompositeElement)child.getTreeParent()).getChildRole(child);
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.FOR_STATEMENT) {
if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) {
return defaultAlignment;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST || role == ChildRole.IMPLEMENTS_KEYWORD) {
return defaultAlignment;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.THROWS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return defaultAlignment;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.CLASS) {
if (role == ChildRole.CLASS_OR_INTERFACE_KEYWORD) return defaultAlignment;
if (myIsAfterClassKeyword) return null;
if (role == ChildRole.MODIFIER_LIST) return defaultAlignment;
if (role == ChildRole.DOC_COMMENT) return defaultAlignment;
return null;
}
else if (nodeType == JavaElementType.METHOD) {
if (role == ChildRole.MODIFIER_LIST) return defaultAlignment;
if (role == ChildRole.TYPE) return defaultAlignment;
if (role == ChildRole.NAME) return defaultAlignment;
return null;
}
else if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) {
if (role == ChildRole.LOPERAND) return defaultAlignment;
if (role == ChildRole.ROPERAND && child.getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION) {
return defaultAlignment;
}
else {
return null;
}
}
else {
return defaultAlignment;
}
}
/*
private boolean isAfterClassKeyword(final ASTNode child) {
ASTNode treePrev = child.getTreePrev();
while (treePrev != null) {
if (treePrev.getElementType() == ElementType.CLASS_KEYWORD ||
treePrev.getElementType() == ElementType.INTERFACE_KEYWORD) {
return true;
}
treePrev = treePrev.getTreePrev();
}
return false;
}
*/
private static Alignment createAlignment(final boolean alignOption, final Alignment defaultAlignment) {
return alignOption ? createAlignmentOrDefault(defaultAlignment) : defaultAlignment;
}
@Nullable
protected Wrap arrangeChildWrap(final ASTNode child, Wrap defaultWrap) {
if (myAnnotationWrap != null) {
try {
return myAnnotationWrap;
}
finally {
myAnnotationWrap = null;
}
}
final ASTNode parent = child.getTreeParent();
int role = ((CompositeElement)parent).getChildRole(child);
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.BINARY_EXPRESSION) {
if (role == ChildRole.OPERATION_SIGN && !mySettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) return null;
if (role == ChildRole.ROPERAND && mySettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) return null;
return defaultWrap;
}
final IElementType childType = child.getElementType();
if (childType == JavaElementType.EXTENDS_LIST || childType == JavaElementType.IMPLEMENTS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.EXTENDS_KEYWORD_WRAP), true);
}
else if (childType == JavaElementType.THROWS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.THROWS_KEYWORD_WRAP), true);
}
else if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return defaultWrap;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.THROWS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return defaultWrap;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
if (role == ChildRole.COLON && !mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
if (role == ChildRole.QUEST && !mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
if (role == ChildRole.THEN_EXPRESSION && mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
if (role == ChildRole.ELSE_EXPRESSION && mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
return defaultWrap;
}
else if (isAssignment()) {
if (role == ChildRole.INITIALIZER_EQ && mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
if (role == ChildRole.OPERATION_SIGN && mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
if (role == ChildRole.INITIALIZER && !mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
if (role == ChildRole.ROPERAND && !mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
return null;
}
else if (nodeType == JavaElementType.REFERENCE_EXPRESSION) {
if (role == ChildRole.DOT) {
return getReservedWrap();
}
else {
return defaultWrap;
}
}
else if (nodeType == JavaElementType.FOR_STATEMENT) {
if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) {
return defaultWrap;
}
if (role == ChildRole.LOOP_BODY) {
final boolean dontWrap = (childType == JavaElementType.CODE_BLOCK || childType == JavaElementType.BLOCK_STATEMENT) &&
mySettings.BRACE_STYLE == CodeStyleSettings.END_OF_LINE;
return Wrap.createWrap(dontWrap ? WrapType.NONE : WrapType.NORMAL, true);
}
else {
return null;
}
}
else if (nodeType == JavaElementType.METHOD) {
if (role == ChildRole.THROWS_LIST) {
return defaultWrap;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.MODIFIER_LIST) {
if (childType == JavaElementType.ANNOTATION) {
return getReservedWrap();
}
ASTNode prevElement = getPrevElement(child);
if (prevElement != null && prevElement.getElementType() == JavaElementType.ANNOTATION) {
return getReservedWrap();
}
else {
return null;
}
}
else if (nodeType == JavaElementType.ASSERT_STATEMENT) {
if (role == ChildRole.CONDITION) {
return defaultWrap;
}
if (role == ChildRole.ASSERT_DESCRIPTION && !mySettings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE) {
return defaultWrap;
}
if (role == ChildRole.COLON && mySettings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE) {
return defaultWrap;
}
return null;
}
else if (nodeType == JavaElementType.CODE_BLOCK) {
if (role == ChildRole.STATEMENT_IN_BLOCK) {
return defaultWrap;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.IF_STATEMENT) {
if (role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH) {
if (childType == JavaElementType.BLOCK_STATEMENT) {
return null;
}
else {
return Wrap.createWrap(WrapType.NORMAL, true);
}
}
}
else if (nodeType == JavaElementType.FOREACH_STATEMENT || nodeType == JavaElementType.WHILE_STATEMENT) {
if (role == ChildRole.LOOP_BODY) {
if (childType == JavaElementType.BLOCK_STATEMENT) {
return null;
}
else {
return Wrap.createWrap(WrapType.NORMAL, true);
}
}
}
else if (nodeType == JavaElementType.DO_WHILE_STATEMENT) {
if (role == ChildRole.LOOP_BODY) {
return Wrap.createWrap(WrapType.NORMAL, true);
} else if (role == ChildRole.WHILE_KEYWORD) {
return Wrap.createWrap(WrapType.NORMAL, true);
}
} else if (nodeType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER) {
if (role == ChildRole.ANNOTATION_VALUE) {
return Wrap.createWrap(WrapType.NORMAL, true);
}
}
return defaultWrap;
}
private static ASTNode getPrevElement(final ASTNode child) {
ASTNode result = child.getTreePrev();
while (result != null && result.getElementType() == TokenType.WHITE_SPACE) {
result = result.getTreePrev();
}
return result;
}
private boolean hasTheSamePriority(final ASTNode node) {
if (node == null) return false;
if (node.getElementType() != JavaElementType.BINARY_EXPRESSION) {
return false;
}
else {
final PsiBinaryExpression expr1 = (PsiBinaryExpression)SourceTreeToPsiMap.treeElementToPsi(myNode);
final PsiBinaryExpression expr2 = (PsiBinaryExpression)SourceTreeToPsiMap.treeElementToPsi(node);
final PsiJavaToken op1 = expr1.getOperationSign();
final PsiJavaToken op2 = expr2.getOperationSign();
return op1.getTokenType() == op2.getTokenType();
}
}
private static WrapType getWrapType(final int wrap) {
switch (wrap) {
case CodeStyleSettings.WRAP_ALWAYS:
return WrapType.ALWAYS;
case CodeStyleSettings.WRAP_AS_NEEDED:
return WrapType.NORMAL;
case CodeStyleSettings.DO_NOT_WRAP:
return WrapType.NONE;
default:
return WrapType.CHOP_DOWN_IF_LONG;
}
}
private ASTNode processParenBlock(List<Block> result,
ASTNode child,
WrappingStrategy wrappingStrategy,
final boolean doAlign) {
myUseChildAttributes = true;
final IElementType from = JavaTokenType.LPARENTH;
final IElementType to = JavaTokenType.RPARENTH;
return processParenBlock(from, to, result, child, wrappingStrategy, doAlign);
}
private ASTNode processParenBlock(final IElementType from,
final IElementType to, final List<Block> result, ASTNode child,
final WrappingStrategy wrappingStrategy, final boolean doAlign
) {
final Indent externalIndent = Indent.getNoneIndent();
final Indent internalIndent = Indent.getContinuationIndent();
AlignmentStrategy alignmentStrategy = AlignmentStrategy.createDoNotAlingCommaStrategy(createAlignment(doAlign, null));
setChildIndent(internalIndent);
setChildAlignment(alignmentStrategy.getAlignment(null));
boolean isAfterIncomplete = false;
ASTNode prev = child;
int startOffset = child.getTextRange().getStartOffset();
while (child != null) {
isAfterIncomplete = isAfterIncomplete || child.getElementType() == TokenType.ERROR_ELEMENT ||
child.getElementType() == JavaElementType.EMPTY_EXPRESSION;
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
if (child.getElementType() == from) {
result.add(createJavaBlock(child, mySettings, externalIndent, null, null));
}
else if (child.getElementType() == to) {
result.add(createJavaBlock(child, mySettings,
isAfterIncomplete ? internalIndent : externalIndent,
null,
isAfterIncomplete ? alignmentStrategy.getAlignment(null) : null));
return child;
}
else {
final IElementType elementType = child.getElementType();
result.add(createJavaBlock(child, mySettings, internalIndent,
wrappingStrategy.getWrap(elementType),
alignmentStrategy.getAlignment(elementType),
startOffset));
if (to == null) {//process only one statement
return child;
}
}
isAfterIncomplete = false;
}
prev = child;
startOffset += child.getTextLength();
child = child.getTreeNext();
}
return prev;
}
@Nullable
private ASTNode processEnumBlock(List<Block> result,
ASTNode child,
ASTNode last) {
final WrappingStrategy wrappingStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(Wrap
.createWrap(getWrapType(mySettings.ENUM_CONSTANTS_WRAP), true));
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
result.add(createJavaBlock(child, mySettings, Indent.getNormalIndent(),
wrappingStrategy.getWrap(child.getElementType()), null));
if (child == last) return child;
}
child = child.getTreeNext();
}
return null;
}
private void setChildAlignment(final Alignment alignment) {
myChildAlignment = alignment;
}
private void setChildIndent(final Indent internalIndent) {
myChildIndent = internalIndent;
}
private static Alignment createAlignmentOrDefault(final Alignment defaultAlignment) {
return defaultAlignment == null ? Alignment.createAlignment() : defaultAlignment;
}
private int getBraceStyle() {
final PsiElement psiNode = SourceTreeToPsiMap.treeElementToPsi(myNode);
if (psiNode instanceof PsiClass) {
return mySettings.CLASS_BRACE_STYLE;
}
else if (psiNode instanceof PsiMethod) {
return mySettings.METHOD_BRACE_STYLE;
}
else if (psiNode instanceof PsiCodeBlock && psiNode.getParent() != null && psiNode.getParent() instanceof PsiMethod) {
return mySettings.METHOD_BRACE_STYLE;
}
else {
return mySettings.BRACE_STYLE;
}
}
protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent) {
if (isTopLevelClass() && mySettings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS) {
return Indent.getNoneIndent();
}
final int braceStyle = getBraceStyle();
return braceStyle == CodeStyleSettings.NEXT_LINE_SHIFTED ?
createNormalIndent(baseChildrenIndent - 1)
: createNormalIndent(baseChildrenIndent);
}
protected static Indent createNormalIndent(final int baseChildrenIndent) {
if (baseChildrenIndent == 1) {
return Indent.getNormalIndent();
}
else if (baseChildrenIndent <= 0) {
return Indent.getNoneIndent();
}
else {
LOG.assertTrue(false);
return Indent.getNormalIndent();
}
}
private boolean isTopLevelClass() {
return myNode.getElementType() == JavaElementType.CLASS &&
SourceTreeToPsiMap.treeElementToPsi(myNode.getTreeParent()) instanceof PsiFile;
}
protected Indent getCodeBlockExternalIndent() {
final int braceStyle = getBraceStyle();
if (braceStyle == CodeStyleSettings.END_OF_LINE || braceStyle == CodeStyleSettings.NEXT_LINE ||
braceStyle == CodeStyleSettings.NEXT_LINE_IF_WRAPPED) {
return Indent.getNoneIndent();
}
else {
return Indent.getNormalIndent();
}
}
protected abstract Wrap getReservedWrap();
protected abstract void setReservedWrap(final Wrap reservedWrap);
@Nullable
protected static ASTNode getTreeNode(final Block child2) {
if (child2 instanceof JavaBlock) {
return ((JavaBlock)child2).getFirstTreeNode();
}
else if (child2 instanceof LeafBlock) {
return ((LeafBlock)child2).getTreeNode();
}
else {
return null;
}
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
if (myUseChildAttributes) {
return new ChildAttributes(myChildIndent, myChildAlignment);
}
else if (isAfter(newChildIndex, new IElementType[]{JavaDocElementType.DOC_COMMENT})) {
return new ChildAttributes(Indent.getNoneIndent(), myChildAlignment);
}
else {
return super.getChildAttributes(newChildIndex);
}
}
@Nullable
protected Indent getChildIndent() {
return getChildIndent(myNode);
}
public CodeStyleSettings getSettings() {
return mySettings;
}
protected boolean isAfter(final int newChildIndex, final IElementType[] elementTypes) {
if (newChildIndex == 0) return false;
final Block previousBlock = getSubBlocks().get(newChildIndex - 1);
if (!(previousBlock instanceof AbstractBlock)) return false;
final IElementType previousElementType = ((AbstractBlock)previousBlock).getNode().getElementType();
for (IElementType elementType : elementTypes) {
if (previousElementType == elementType) return true;
}
return false;
}
protected Alignment getUsedAlignment(final int newChildIndex) {
final List<Block> subBlocks = getSubBlocks();
for (int i = 0; i < newChildIndex; i++) {
if (i >= subBlocks.size()) return null;
final Block block = subBlocks.get(i);
final Alignment alignment = block.getAlignment();
if (alignment != null) return alignment;
}
return null;
}
}
| source/com/intellij/psi/formatter/java/AbstractJavaBlock.java | package com.intellij.psi.formatter.java;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.formatter.common.AbstractBlock;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.parsing.ChameleonTransforming;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.impl.source.tree.java.ClassElement;
import com.intellij.psi.jsp.JspElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.AbstractJavaBlock");
protected final CodeStyleSettings mySettings;
private final Indent myIndent;
protected Indent myChildIndent;
protected Alignment myChildAlignment;
protected boolean myUseChildAttributes = false;
private boolean myIsAfterClassKeyword = false;
private Wrap myAnnotationWrap = null;
protected AbstractJavaBlock(final ASTNode node,
final Wrap wrap,
final Alignment alignment,
final Indent indent,
final CodeStyleSettings settings) {
super(node, wrap, alignment);
mySettings = settings;
myIndent = indent;
}
public static Block createJavaBlock(final ASTNode child,
final CodeStyleSettings settings,
final Indent indent,
Wrap wrap,
Alignment alignment) {
return createJavaBlock(child, settings, indent, wrap, alignment, -1);
}
public static Block createJavaBlock(final ASTNode child,
final CodeStyleSettings settings,
final Indent indent,
Wrap wrap,
Alignment alignment,
int startOffset
) {
Indent actualIndent = indent == null ? getDefaultSubtreeIndent(child) : indent;
final IElementType elementType = child.getElementType();
if (child.getPsi() instanceof PsiWhiteSpace) {
String text = child.getText();
int start = CharArrayUtil.shiftForward(text, 0, " \t\n");
int end = CharArrayUtil.shiftBackward(text, text.length() - 1, " \t\n") + 1;
LOG.assertTrue(start < end);
return new PartialWhitespaceBlock(child, new TextRange(start + child.getStartOffset(), end + child.getStartOffset()),
wrap, alignment, actualIndent, settings);
}
if (child.getPsi() instanceof PsiClass) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings);
}
if (isBlockType(elementType)) {
return new BlockContainingJavaBlock(child, wrap, alignment, actualIndent, settings);
}
if (isStatement(child, child.getTreeParent())) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings);
}
if (child instanceof LeafElement) {
final LeafBlock block = new LeafBlock(child, wrap, alignment, actualIndent);
block.setStartOffset(startOffset);
return block;
}
else if (isLikeExtendsList(elementType)) {
return new ExtendsListBlock(child, wrap, alignment, settings);
}
else if (elementType == JavaElementType.CODE_BLOCK) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings);
}
else if (elementType == JavaElementType.LABELED_STATEMENT) {
return new LabeledJavaBlock(child, wrap, alignment, actualIndent, settings);
}
else if (elementType == JavaDocElementType.DOC_COMMENT) {
return new DocCommentBlock(child, wrap, alignment, actualIndent, settings);
}
else {
final SimpleJavaBlock simpleJavaBlock = new SimpleJavaBlock(child, wrap, alignment, actualIndent, settings);
simpleJavaBlock.setStartOffset(startOffset);
return simpleJavaBlock;
}
}
private static boolean isLikeExtendsList(final IElementType elementType) {
return elementType == JavaElementType.EXTENDS_LIST
|| elementType == JavaElementType.IMPLEMENTS_LIST
|| elementType == JavaElementType.THROWS_LIST;
}
private static boolean isBlockType(final IElementType elementType) {
return elementType == JavaElementType.SWITCH_STATEMENT
|| elementType == JavaElementType.FOR_STATEMENT
|| elementType == JavaElementType.WHILE_STATEMENT
|| elementType == JavaElementType.DO_WHILE_STATEMENT
|| elementType == JavaElementType.TRY_STATEMENT
|| elementType == JavaElementType.CATCH_SECTION
|| elementType == JavaElementType.IF_STATEMENT
|| elementType == JavaElementType.METHOD
|| elementType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION
|| elementType == JavaElementType.CLASS_INITIALIZER
|| elementType == JavaElementType.SYNCHRONIZED_STATEMENT
|| elementType == JavaElementType.FOREACH_STATEMENT;
}
public static Block createJavaBlock(final ASTNode child, final CodeStyleSettings settings) {
return createJavaBlock(child, settings, getDefaultSubtreeIndent(child), null, null);
}
@Nullable
private static Indent getDefaultSubtreeIndent(final ASTNode child) {
final ASTNode parent = child.getTreeParent();
final IElementType childNodeType = child.getElementType();
if (childNodeType == JavaElementType.ANNOTATION) return Indent.getNoneIndent();
final ASTNode prevElement = getPrevElement(child);
if (prevElement != null && prevElement.getElementType() == JavaElementType.MODIFIER_LIST) {
return Indent.getNoneIndent();
}
if (childNodeType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (childNodeType == JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS) return Indent.getSpaceIndent(1);
if (child.getPsi() instanceof PsiFile) return Indent.getNoneIndent();
if (parent != null) {
final Indent defaultChildIndent = getChildIndent(parent);
if (defaultChildIndent != null) return defaultChildIndent;
}
return null;
}
@Nullable
private static Indent getChildIndent(final ASTNode parent) {
final IElementType parentType = parent.getElementType();
if (parentType == JavaElementType.MODIFIER_LIST) return Indent.getNoneIndent();
if (parentType == JspElementType.JSP_CODE_BLOCK) return Indent.getNormalIndent();
if (parentType == JspElementType.JSP_CLASS_LEVEL_DECLARATION_STATEMENT) return Indent.getNormalIndent();
if (parentType == ElementType.DUMMY_HOLDER) return Indent.getNoneIndent();
if (parentType == JavaElementType.CLASS) return Indent.getNoneIndent();
if (parentType == JavaElementType.IF_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.TRY_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.CATCH_SECTION) return Indent.getNoneIndent();
if (parentType == JavaElementType.FOR_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.FOREACH_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.BLOCK_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.DO_WHILE_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.WHILE_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.SWITCH_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.METHOD) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_COMMENT) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_INLINE_TAG) return Indent.getNoneIndent();
if (parentType == JavaElementType.IMPORT_LIST) return Indent.getNoneIndent();
if (SourceTreeToPsiMap.treeElementToPsi(parent) instanceof PsiFile) {
return Indent.getNoneIndent();
}
else {
return null;
}
}
public Spacing getSpacing(Block child1, Block child2) {
return JavaSpacePropertyProcessor.getSpacing(getTreeNode(child2), mySettings);
}
public ASTNode getFirstTreeNode() {
return myNode;
}
public Indent getIndent() {
return myIndent;
}
protected static boolean isStatement(final ASTNode child, final ASTNode parentNode) {
if (parentNode != null) {
final IElementType parentType = parentNode.getElementType();
if (parentType == JavaElementType.CODE_BLOCK) return false;
final int role = ((CompositeElement)parentNode).getChildRole(child);
if (parentType == JavaElementType.IF_STATEMENT) return role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH;
if (parentType == JavaElementType.FOR_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.DO_WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.FOREACH_STATEMENT) return role == ChildRole.LOOP_BODY;
}
return false;
}
@Nullable
protected Wrap createChildWrap() {
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.EXTENDS_LIST_WRAP), false);
}
else if (nodeType == JavaElementType.BINARY_EXPRESSION) {
Wrap actualWrap = myWrap != null ? myWrap : getReservedWrap();
if (actualWrap == null) {
return Wrap.createWrap(getWrapType(mySettings.BINARY_OPERATION_WRAP), false);
}
else {
if (!hasTheSamePriority(myNode.getTreeParent())) {
return Wrap.createChildWrap(actualWrap, getWrapType(mySettings.BINARY_OPERATION_WRAP), false);
}
else {
return actualWrap;
}
}
}
else if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
return Wrap.createWrap(getWrapType(mySettings.TERNARY_OPERATION_WRAP), false);
}
else if (nodeType == JavaElementType.ASSERT_STATEMENT) {
return Wrap.createWrap(getWrapType(mySettings.ASSERT_STATEMENT_WRAP), false);
}
else if (nodeType == JavaElementType.FOR_STATEMENT) {
return Wrap.createWrap(getWrapType(mySettings.FOR_STATEMENT_WRAP), false);
}
else if (nodeType == JavaElementType.THROWS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.THROWS_LIST_WRAP), true);
}
else if (nodeType == JavaElementType.CODE_BLOCK) {
return Wrap.createWrap(Wrap.NORMAL, false);
}
else if (isAssignment()) {
return Wrap.createWrap(getWrapType(mySettings.ASSIGNMENT_WRAP), true);
}
else {
return null;
}
}
private boolean isAssignment() {
final IElementType nodeType = myNode.getElementType();
return nodeType == JavaElementType.ASSIGNMENT_EXPRESSION || nodeType == JavaElementType.LOCAL_VARIABLE
|| nodeType == JavaElementType.FIELD;
}
@Nullable
protected Alignment createChildAlignment() {
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) {
if (myNode.getTreeParent() != null
&& myNode.getTreeParent().getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION
&& myAlignment != null) {
return myAlignment;
}
else {
return createAlignment(mySettings.ALIGN_MULTILINE_ASSIGNMENT, null);
}
}
else if (nodeType == JavaElementType.PARENTH_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION, null);
}
else if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_TERNARY_OPERATION, null);
}
else if (nodeType == JavaElementType.FOR_STATEMENT) {
return createAlignment(mySettings.ALIGN_MULTILINE_FOR, null);
}
else if (nodeType == JavaElementType.EXTENDS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null);
}
else if (nodeType == JavaElementType.IMPLEMENTS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null);
}
else if (nodeType == JavaElementType.THROWS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_THROWS_LIST, null);
}
else if (nodeType == JavaElementType.PARAMETER_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARAMETERS, null);
}
else if (nodeType == JavaElementType.BINARY_EXPRESSION) {
Alignment defaultAlignment = null;
if (shouldInheritAlignment()) {
defaultAlignment = myAlignment;
}
return createAlignment(mySettings.ALIGN_MULTILINE_BINARY_OPERATION, defaultAlignment);
}
else if (nodeType == JavaElementType.CLASS) {
return Alignment.createAlignment();
}
else if (nodeType == JavaElementType.METHOD) {
return Alignment.createAlignment();
}
else {
return null;
}
}
private boolean shouldInheritAlignment() {
if (myNode.getElementType() == JavaElementType.BINARY_EXPRESSION) {
final ASTNode treeParent = myNode.getTreeParent();
if (treeParent != null && treeParent.getElementType() == JavaElementType.BINARY_EXPRESSION) {
return hasTheSamePriority(treeParent);
}
}
return false;
}
protected ASTNode processChild(final ArrayList<Block> result,
ASTNode child,
Alignment defaultAlignment,
final Wrap defaultWrap,
final Indent childIndent) {
return processChild(result, child, defaultAlignment, defaultWrap, childIndent, -1);
}
protected ASTNode processChild(final ArrayList<Block> result,
ASTNode child,
Alignment defaultAlignment,
final Wrap defaultWrap,
final Indent childIndent,
int childOffset) {
final IElementType childType = child.getElementType();
if (childType == JavaTokenType.CLASS_KEYWORD || childType == JavaTokenType.INTERFACE_KEYWORD) {
myIsAfterClassKeyword = true;
}
if (childType == JavaElementType.METHOD_CALL_EXPRESSION) {
result.add(createMethodCallExpressiobBlock(child,
arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment)));
}
else {
final IElementType nodeType = myNode.getElementType();
if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
child = processParenBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE,
result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.EXPRESSION_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
if (mySettings.PREFER_PARAMETERS_WRAP) {
wrap.ignoreParentWraps();
}
child = processParenBlock(result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARAMETER_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
child = processParenBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.ANNOTATION_PARAMETER_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
child = processParenBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARENTH_EXPRESSION) {
child = processParenBlock(result, child,
WrappingStrategy.DO_NOT_WRAP,
mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION);
}
else if (childType == JavaElementType.ENUM_CONSTANT && myNode instanceof ClassElement) {
child = processEnumBlock(result, child, ((ClassElement)myNode).findEnumConstantListDelimiterPlace());
}
else if (mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE && isTernaryOperationSign(child)) {
child = processTernaryOperationRange(result, child, defaultAlignment, defaultWrap, childIndent);
}
else if (childType == JavaElementType.FIELD) {
child = processField(result, child, defaultAlignment, defaultWrap, childIndent);
}
else {
final Block block =
createJavaBlock(child, mySettings, childIndent, arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment), childOffset);
if (childType == JavaElementType.MODIFIER_LIST && containsAnnotations(child)) {
myAnnotationWrap = Wrap.createWrap(getWrapType(getAnnotationWrapType()), true);
}
if (block instanceof AbstractJavaBlock) {
final AbstractJavaBlock javaBlock = (AbstractJavaBlock)block;
if (nodeType == JavaElementType.METHOD_CALL_EXPRESSION && childType == JavaElementType.REFERENCE_EXPRESSION) {
javaBlock.setReservedWrap(getReservedWrap());
}
else if (nodeType == JavaElementType.REFERENCE_EXPRESSION &&
childType == JavaElementType.METHOD_CALL_EXPRESSION) {
javaBlock.setReservedWrap(getReservedWrap());
}
else if (nodeType == JavaElementType.BINARY_EXPRESSION) {
javaBlock.setReservedWrap(defaultWrap);
}
else if (childType == JavaElementType.MODIFIER_LIST) {
javaBlock.setReservedWrap(myAnnotationWrap);
if (!lastChildIsAnnotation(child)) {
myAnnotationWrap = null;
}
}
}
result.add(block);
}
}
return child;
}
private ASTNode processField(final ArrayList<Block> result, ASTNode child, final Alignment defaultAlignment, final Wrap defaultWrap,
final Indent childIndent) {
ASTNode lastFieldInGroup = findLastFieldInGroup(child);
if (lastFieldInGroup == child) {
result.add(createJavaBlock(child, getSettings(), childIndent, arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment)));
return child;
}
else {
final ArrayList<Block> localResult = new ArrayList<Block>();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
localResult.add(createJavaBlock(child, getSettings(), Indent.getContinuationWithoutFirstIndent(), arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment)));
}
if (child == lastFieldInGroup) break;
child = child.getTreeNext();
}
if (!localResult.isEmpty()) {
result.add(new SyntheticCodeBlock(localResult, null, getSettings(), childIndent, null));
}
return lastFieldInGroup;
}
}
@NotNull private static ASTNode findLastFieldInGroup(final ASTNode child) {
final PsiTypeElement typeElement = ((PsiVariable)child.getPsi()).getTypeElement();
if (typeElement == null) return child;
ASTNode lastChildNode = child.getLastChildNode();
if (lastChildNode == null) return child;
if (lastChildNode.getElementType() == JavaTokenType.SEMICOLON) return child;
ASTNode currentResult = child;
ASTNode currentNode = child.getTreeNext();
while (currentNode != null) {
if (currentNode.getElementType() == TokenType.WHITE_SPACE
|| currentNode.getElementType() == JavaTokenType.COMMA
|| StdTokenSets.COMMENT_BIT_SET.contains(currentNode.getElementType())) {
}
else if (currentNode.getElementType() == JavaElementType.FIELD) {
if (((PsiVariable)currentNode.getPsi()).getTypeElement() != typeElement) {
return currentResult;
}
else {
currentResult = currentNode;
}
}
else {
return currentResult;
}
currentNode = currentNode.getTreeNext();
}
return currentResult;
}
private ASTNode processTernaryOperationRange(final ArrayList<Block> result,
final ASTNode child,
final Alignment defaultAlignment,
final Wrap defaultWrap, final Indent childIndent) {
final ArrayList<Block> localResult = new ArrayList<Block>();
final Wrap wrap = arrangeChildWrap(child, defaultWrap);
final Alignment alignment = arrangeChildAlignment(child, defaultAlignment);
localResult.add(new LeafBlock(child, wrap, alignment, childIndent));
ASTNode current = child.getTreeNext();
while (current != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(current) && current.getTextLength() > 0) {
if (isTernaryOperationSign(current)) break;
current = processChild(localResult, current, defaultAlignment, defaultWrap, childIndent);
}
if (current != null) {
current = current.getTreeNext();
}
}
result.add(new SyntheticCodeBlock(localResult, alignment, getSettings(), null, wrap));
if (current == null) {
return null;
}
else {
return current.getTreePrev();
}
}
private boolean isTernaryOperationSign(final ASTNode child) {
if (myNode.getElementType() != JavaElementType.CONDITIONAL_EXPRESSION) return false;
final int role = ((CompositeElement)child.getTreeParent()).getChildRole(child);
return role == ChildRole.OPERATION_SIGN || role == ChildRole.COLON;
}
private Block createMethodCallExpressiobBlock(final ASTNode node, final Wrap blockWrap, final Alignment alignment) {
final ArrayList<ASTNode> nodes = new ArrayList<ASTNode>();
final ArrayList<Block> subBlocks = new ArrayList<Block>();
collectNodes(nodes, node);
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.METHOD_CALL_CHAIN_WRAP), false);
while (!nodes.isEmpty()) {
ArrayList<ASTNode> subNodes = readToNextDot(nodes);
subBlocks.add(createSynthBlock(subNodes, wrap));
}
return new SyntheticCodeBlock(subBlocks, alignment, mySettings, Indent.getContinuationWithoutFirstIndent(),
blockWrap);
}
private Block createSynthBlock(final ArrayList<ASTNode> subNodes, final Wrap wrap) {
final ArrayList<Block> subBlocks = new ArrayList<Block>();
final ASTNode firstNode = subNodes.get(0);
if (firstNode.getElementType() == JavaTokenType.DOT) {
subBlocks.add(createJavaBlock(firstNode, getSettings(), Indent.getNoneIndent(),
null,
null));
subNodes.remove(0);
if (!subNodes.isEmpty()) {
subBlocks.add(createSynthBlock(subNodes, wrap));
}
return new SyntheticCodeBlock(subBlocks, null, mySettings, Indent.getContinuationIndent(), wrap);
}
else {
return new SyntheticCodeBlock(createJavaBlocks(subNodes), null, mySettings,
Indent.getContinuationWithoutFirstIndent(), null);
}
}
private List<Block> createJavaBlocks(final ArrayList<ASTNode> subNodes) {
final ArrayList<Block> result = new ArrayList<Block>();
for (ASTNode node : subNodes) {
result.add(createJavaBlock(node, getSettings(), Indent.getContinuationWithoutFirstIndent(), null, null));
}
return result;
}
private static ArrayList<ASTNode> readToNextDot(final ArrayList<ASTNode> nodes) {
final ArrayList<ASTNode> result = new ArrayList<ASTNode>();
result.add(nodes.remove(0));
for (Iterator<ASTNode> iterator = nodes.iterator(); iterator.hasNext();) {
ASTNode node = iterator.next();
if (node.getElementType() == JavaTokenType.DOT) return result;
result.add(node);
iterator.remove();
}
return result;
}
private static void collectNodes(List<ASTNode> nodes, ASTNode node) {
ChameleonTransforming.transformChildren(node);
ASTNode child = node.getFirstChildNode();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
if (child.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION || child.getElementType() ==
JavaElementType
.REFERENCE_EXPRESSION) {
collectNodes(nodes, child);
}
else {
nodes.add(child);
}
}
child = child.getTreeNext();
}
}
private static boolean lastChildIsAnnotation(final ASTNode child) {
ASTNode current = child.getLastChildNode();
while (current != null && current.getElementType() == TokenType.WHITE_SPACE) {
current = current.getTreePrev();
}
return current != null && current.getElementType() == JavaElementType.ANNOTATION;
}
private static boolean containsAnnotations(final ASTNode child) {
return ((PsiModifierList)child.getPsi()).getAnnotations().length > 0;
}
private int getAnnotationWrapType() {
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.METHOD) {
return mySettings.METHOD_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.CLASS) {
return mySettings.CLASS_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.FIELD) {
return mySettings.FIELD_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.PARAMETER) {
return mySettings.PARAMETER_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.LOCAL_VARIABLE) {
return mySettings.VARIABLE_ANNOTATION_WRAP;
}
return CodeStyleSettings.DO_NOT_WRAP;
}
@Nullable
private Alignment arrangeChildAlignment(final ASTNode child, final Alignment defaultAlignment) {
int role = ((CompositeElement)child.getTreeParent()).getChildRole(child);
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.FOR_STATEMENT) {
if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) {
return defaultAlignment;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST || role == ChildRole.IMPLEMENTS_KEYWORD) {
return defaultAlignment;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.THROWS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return defaultAlignment;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.CLASS) {
if (role == ChildRole.CLASS_OR_INTERFACE_KEYWORD) return defaultAlignment;
if (myIsAfterClassKeyword) return null;
if (role == ChildRole.MODIFIER_LIST) return defaultAlignment;
if (role == ChildRole.DOC_COMMENT) return defaultAlignment;
return null;
}
else if (nodeType == JavaElementType.METHOD) {
if (role == ChildRole.MODIFIER_LIST) return defaultAlignment;
if (role == ChildRole.TYPE) return defaultAlignment;
if (role == ChildRole.NAME) return defaultAlignment;
return null;
}
else if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) {
if (role == ChildRole.LOPERAND) return defaultAlignment;
if (role == ChildRole.ROPERAND && child.getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION) {
return defaultAlignment;
}
else {
return null;
}
}
else {
return defaultAlignment;
}
}
/*
private boolean isAfterClassKeyword(final ASTNode child) {
ASTNode treePrev = child.getTreePrev();
while (treePrev != null) {
if (treePrev.getElementType() == ElementType.CLASS_KEYWORD ||
treePrev.getElementType() == ElementType.INTERFACE_KEYWORD) {
return true;
}
treePrev = treePrev.getTreePrev();
}
return false;
}
*/
private static Alignment createAlignment(final boolean alignOption, final Alignment defaultAlignment) {
return alignOption ? createAlignmentOrDefault(defaultAlignment) : defaultAlignment;
}
@Nullable
protected Wrap arrangeChildWrap(final ASTNode child, Wrap defaultWrap) {
if (myAnnotationWrap != null) {
try {
return myAnnotationWrap;
}
finally {
myAnnotationWrap = null;
}
}
final ASTNode parent = child.getTreeParent();
int role = ((CompositeElement)parent).getChildRole(child);
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.BINARY_EXPRESSION) {
if (role == ChildRole.OPERATION_SIGN && !mySettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) return null;
if (role == ChildRole.ROPERAND && mySettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) return null;
return defaultWrap;
}
final IElementType childType = child.getElementType();
if (childType == JavaElementType.EXTENDS_LIST || childType == JavaElementType.IMPLEMENTS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.EXTENDS_KEYWORD_WRAP), true);
}
else if (childType == JavaElementType.THROWS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.THROWS_KEYWORD_WRAP), true);
}
else if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return defaultWrap;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.THROWS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return defaultWrap;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
if (role == ChildRole.COLON && !mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
if (role == ChildRole.QUEST && !mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
if (role == ChildRole.THEN_EXPRESSION && mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
if (role == ChildRole.ELSE_EXPRESSION && mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
return defaultWrap;
}
else if (isAssignment()) {
if (role == ChildRole.INITIALIZER_EQ && mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
if (role == ChildRole.OPERATION_SIGN && mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
if (role == ChildRole.INITIALIZER && !mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
if (role == ChildRole.ROPERAND && !mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
return null;
}
else if (nodeType == JavaElementType.REFERENCE_EXPRESSION) {
if (role == ChildRole.DOT) {
return getReservedWrap();
}
else {
return defaultWrap;
}
}
else if (nodeType == JavaElementType.FOR_STATEMENT) {
if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) {
return defaultWrap;
}
if (role == ChildRole.LOOP_BODY) {
final boolean dontWrap = (childType == JavaElementType.CODE_BLOCK || childType == JavaElementType.BLOCK_STATEMENT) &&
mySettings.BRACE_STYLE == CodeStyleSettings.END_OF_LINE;
return Wrap.createWrap(dontWrap ? WrapType.NONE : WrapType.NORMAL, true);
}
else {
return null;
}
}
else if (nodeType == JavaElementType.METHOD) {
if (role == ChildRole.THROWS_LIST) {
return defaultWrap;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.MODIFIER_LIST) {
if (childType == JavaElementType.ANNOTATION) {
return getReservedWrap();
}
ASTNode prevElement = getPrevElement(child);
if (prevElement != null && prevElement.getElementType() == JavaElementType.ANNOTATION) {
return getReservedWrap();
}
else {
return null;
}
}
else if (nodeType == JavaElementType.ASSERT_STATEMENT) {
if (role == ChildRole.CONDITION) {
return defaultWrap;
}
if (role == ChildRole.ASSERT_DESCRIPTION && !mySettings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE) {
return defaultWrap;
}
if (role == ChildRole.COLON && mySettings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE) {
return defaultWrap;
}
return null;
}
else if (nodeType == JavaElementType.CODE_BLOCK) {
if (role == ChildRole.STATEMENT_IN_BLOCK) {
return defaultWrap;
}
else {
return null;
}
}
else if (nodeType == JavaElementType.IF_STATEMENT) {
if (role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH) {
if (childType == JavaElementType.BLOCK_STATEMENT) {
return null;
}
else {
return Wrap.createWrap(WrapType.NORMAL, true);
}
}
}
else if (nodeType == JavaElementType.FOREACH_STATEMENT || nodeType == JavaElementType.WHILE_STATEMENT) {
if (role == ChildRole.LOOP_BODY) {
if (childType == JavaElementType.BLOCK_STATEMENT) {
return null;
}
else {
return Wrap.createWrap(WrapType.NORMAL, true);
}
}
}
else if (nodeType == JavaElementType.DO_WHILE_STATEMENT) {
if (role == ChildRole.LOOP_BODY) {
return Wrap.createWrap(WrapType.NORMAL, true);
} else if (role == ChildRole.WHILE_KEYWORD) {
return Wrap.createWrap(WrapType.NORMAL, true);
}
}
return defaultWrap;
}
private static ASTNode getPrevElement(final ASTNode child) {
ASTNode result = child.getTreePrev();
while (result != null && result.getElementType() == TokenType.WHITE_SPACE) {
result = result.getTreePrev();
}
return result;
}
private boolean hasTheSamePriority(final ASTNode node) {
if (node == null) return false;
if (node.getElementType() != JavaElementType.BINARY_EXPRESSION) {
return false;
}
else {
final PsiBinaryExpression expr1 = (PsiBinaryExpression)SourceTreeToPsiMap.treeElementToPsi(myNode);
final PsiBinaryExpression expr2 = (PsiBinaryExpression)SourceTreeToPsiMap.treeElementToPsi(node);
final PsiJavaToken op1 = expr1.getOperationSign();
final PsiJavaToken op2 = expr2.getOperationSign();
return op1.getTokenType() == op2.getTokenType();
}
}
private static WrapType getWrapType(final int wrap) {
switch (wrap) {
case CodeStyleSettings.WRAP_ALWAYS:
return WrapType.ALWAYS;
case CodeStyleSettings.WRAP_AS_NEEDED:
return WrapType.NORMAL;
case CodeStyleSettings.DO_NOT_WRAP:
return WrapType.NONE;
default:
return WrapType.CHOP_DOWN_IF_LONG;
}
}
private ASTNode processParenBlock(List<Block> result,
ASTNode child,
WrappingStrategy wrappingStrategy,
final boolean doAlign) {
myUseChildAttributes = true;
final IElementType from = JavaTokenType.LPARENTH;
final IElementType to = JavaTokenType.RPARENTH;
return processParenBlock(from, to, result, child, wrappingStrategy, doAlign);
}
private ASTNode processParenBlock(final IElementType from,
final IElementType to, final List<Block> result, ASTNode child,
final WrappingStrategy wrappingStrategy, final boolean doAlign
) {
final Indent externalIndent = Indent.getNoneIndent();
final Indent internalIndent = Indent.getContinuationIndent();
AlignmentStrategy alignmentStrategy = AlignmentStrategy.createDoNotAlingCommaStrategy(createAlignment(doAlign, null));
setChildIndent(internalIndent);
setChildAlignment(alignmentStrategy.getAlignment(null));
boolean isAfterIncomplete = false;
ASTNode prev = child;
int startOffset = child.getTextRange().getStartOffset();
while (child != null) {
isAfterIncomplete = isAfterIncomplete || child.getElementType() == TokenType.ERROR_ELEMENT ||
child.getElementType() == JavaElementType.EMPTY_EXPRESSION;
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
if (child.getElementType() == from) {
result.add(createJavaBlock(child, mySettings, externalIndent, null, null));
}
else if (child.getElementType() == to) {
result.add(createJavaBlock(child, mySettings,
isAfterIncomplete ? internalIndent : externalIndent,
null,
isAfterIncomplete ? alignmentStrategy.getAlignment(null) : null));
return child;
}
else {
final IElementType elementType = child.getElementType();
result.add(createJavaBlock(child, mySettings, internalIndent,
wrappingStrategy.getWrap(elementType),
alignmentStrategy.getAlignment(elementType),
startOffset));
if (to == null) {//process only one statement
return child;
}
}
isAfterIncomplete = false;
}
prev = child;
startOffset += child.getTextLength();
child = child.getTreeNext();
}
return prev;
}
@Nullable
private ASTNode processEnumBlock(List<Block> result,
ASTNode child,
ASTNode last) {
final WrappingStrategy wrappingStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(Wrap
.createWrap(getWrapType(mySettings.ENUM_CONSTANTS_WRAP), true));
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
result.add(createJavaBlock(child, mySettings, Indent.getNormalIndent(),
wrappingStrategy.getWrap(child.getElementType()), null));
if (child == last) return child;
}
child = child.getTreeNext();
}
return null;
}
private void setChildAlignment(final Alignment alignment) {
myChildAlignment = alignment;
}
private void setChildIndent(final Indent internalIndent) {
myChildIndent = internalIndent;
}
private static Alignment createAlignmentOrDefault(final Alignment defaultAlignment) {
return defaultAlignment == null ? Alignment.createAlignment() : defaultAlignment;
}
private int getBraceStyle() {
final PsiElement psiNode = SourceTreeToPsiMap.treeElementToPsi(myNode);
if (psiNode instanceof PsiClass) {
return mySettings.CLASS_BRACE_STYLE;
}
else if (psiNode instanceof PsiMethod) {
return mySettings.METHOD_BRACE_STYLE;
}
else if (psiNode instanceof PsiCodeBlock && psiNode.getParent() != null && psiNode.getParent() instanceof PsiMethod) {
return mySettings.METHOD_BRACE_STYLE;
}
else {
return mySettings.BRACE_STYLE;
}
}
protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent) {
if (isTopLevelClass() && mySettings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS) {
return Indent.getNoneIndent();
}
final int braceStyle = getBraceStyle();
return braceStyle == CodeStyleSettings.NEXT_LINE_SHIFTED ?
createNormalIndent(baseChildrenIndent - 1)
: createNormalIndent(baseChildrenIndent);
}
protected static Indent createNormalIndent(final int baseChildrenIndent) {
if (baseChildrenIndent == 1) {
return Indent.getNormalIndent();
}
else if (baseChildrenIndent <= 0) {
return Indent.getNoneIndent();
}
else {
LOG.assertTrue(false);
return Indent.getNormalIndent();
}
}
private boolean isTopLevelClass() {
return myNode.getElementType() == JavaElementType.CLASS &&
SourceTreeToPsiMap.treeElementToPsi(myNode.getTreeParent()) instanceof PsiFile;
}
protected Indent getCodeBlockExternalIndent() {
final int braceStyle = getBraceStyle();
if (braceStyle == CodeStyleSettings.END_OF_LINE || braceStyle == CodeStyleSettings.NEXT_LINE ||
braceStyle == CodeStyleSettings.NEXT_LINE_IF_WRAPPED) {
return Indent.getNoneIndent();
}
else {
return Indent.getNormalIndent();
}
}
protected abstract Wrap getReservedWrap();
protected abstract void setReservedWrap(final Wrap reservedWrap);
@Nullable
protected static ASTNode getTreeNode(final Block child2) {
if (child2 instanceof JavaBlock) {
return ((JavaBlock)child2).getFirstTreeNode();
}
else if (child2 instanceof LeafBlock) {
return ((LeafBlock)child2).getTreeNode();
}
else {
return null;
}
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
if (myUseChildAttributes) {
return new ChildAttributes(myChildIndent, myChildAlignment);
}
else if (isAfter(newChildIndex, new IElementType[]{JavaDocElementType.DOC_COMMENT})) {
return new ChildAttributes(Indent.getNoneIndent(), myChildAlignment);
}
else {
return super.getChildAttributes(newChildIndex);
}
}
@Nullable
protected Indent getChildIndent() {
return getChildIndent(myNode);
}
public CodeStyleSettings getSettings() {
return mySettings;
}
protected boolean isAfter(final int newChildIndex, final IElementType[] elementTypes) {
if (newChildIndex == 0) return false;
final Block previousBlock = getSubBlocks().get(newChildIndex - 1);
if (!(previousBlock instanceof AbstractBlock)) return false;
final IElementType previousElementType = ((AbstractBlock)previousBlock).getNode().getElementType();
for (IElementType elementType : elementTypes) {
if (previousElementType == elementType) return true;
}
return false;
}
protected Alignment getUsedAlignment(final int newChildIndex) {
final List<Block> subBlocks = getSubBlocks();
for (int i = 0; i < newChildIndex; i++) {
if (i >= subBlocks.size()) return null;
final Block block = subBlocks.get(i);
final Alignment alignment = block.getAlignment();
if (alignment != null) return alignment;
}
return null;
}
}
| long annotations are not wrapped (IDEADEV-25323)
| source/com/intellij/psi/formatter/java/AbstractJavaBlock.java | long annotations are not wrapped (IDEADEV-25323) | <ide><path>ource/com/intellij/psi/formatter/java/AbstractJavaBlock.java
<ide> } else if (role == ChildRole.WHILE_KEYWORD) {
<ide> return Wrap.createWrap(WrapType.NORMAL, true);
<ide> }
<add> } else if (nodeType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER) {
<add> if (role == ChildRole.ANNOTATION_VALUE) {
<add> return Wrap.createWrap(WrapType.NORMAL, true);
<add> }
<ide> }
<ide>
<ide> return defaultWrap; |
|
Java | apache-2.0 | b7425124911b3293b46f3b48051ea681e66f140c | 0 | Terracotta-OSS/terracotta-platform,albinsuresh/terracotta-platform,Terracotta-OSS/terracotta-platform,chrisdennis/terracotta-platform,albinsuresh/terracotta-platform,chrisdennis/terracotta-platform | /*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terracotta.lease.connection;
import java.util.concurrent.TimeUnit;
public class TimeBudget {
private final long budgetExpiry;
private final TimeUnit timeUnit;
public TimeBudget(long timeout, TimeUnit timeUnit) {
this.timeUnit = timeUnit;
this.budgetExpiry = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeout, timeUnit);
}
public long remaining() {
return remaining(timeUnit);
}
public long remaining(TimeUnit timeUnit) {
long now = System.nanoTime();
long remaining = budgetExpiry - now;
return timeUnit.convert(remaining, TimeUnit.NANOSECONDS);
}
@Override
public String toString() {
return "TimeBudget{" +
"budgetExpiry=" + budgetExpiry +
", remaining=" + remaining() +
", timeUnit=" + timeUnit +
'}';
}
}
| lease/api/src/main/java/org/terracotta/lease/connection/TimeBudget.java | /*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terracotta.lease.connection;
import java.util.concurrent.TimeUnit;
public class TimeBudget {
private final long budgetExpiry;
public TimeBudget(long timeout, TimeUnit timeUnit) {
long now = System.nanoTime();
budgetExpiry = now + TimeUnit.NANOSECONDS.convert(timeout, timeUnit);
}
public long remaining(TimeUnit timeUnit) {
long now = System.nanoTime();
long remaining = budgetExpiry - now;
return timeUnit.convert(remaining, TimeUnit.NANOSECONDS);
}
}
| Added overloaded remaining() and toString() methods in TimeBudget class
| lease/api/src/main/java/org/terracotta/lease/connection/TimeBudget.java | Added overloaded remaining() and toString() methods in TimeBudget class | <ide><path>ease/api/src/main/java/org/terracotta/lease/connection/TimeBudget.java
<ide>
<ide> public class TimeBudget {
<ide> private final long budgetExpiry;
<add> private final TimeUnit timeUnit;
<ide>
<ide> public TimeBudget(long timeout, TimeUnit timeUnit) {
<del> long now = System.nanoTime();
<del> budgetExpiry = now + TimeUnit.NANOSECONDS.convert(timeout, timeUnit);
<add> this.timeUnit = timeUnit;
<add> this.budgetExpiry = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeout, timeUnit);
<add> }
<add>
<add> public long remaining() {
<add> return remaining(timeUnit);
<ide> }
<ide>
<ide> public long remaining(TimeUnit timeUnit) {
<ide> long remaining = budgetExpiry - now;
<ide> return timeUnit.convert(remaining, TimeUnit.NANOSECONDS);
<ide> }
<add>
<add> @Override
<add> public String toString() {
<add> return "TimeBudget{" +
<add> "budgetExpiry=" + budgetExpiry +
<add> ", remaining=" + remaining() +
<add> ", timeUnit=" + timeUnit +
<add> '}';
<add> }
<ide> } |
|
JavaScript | mit | 36bd972638acb2b2f74d7a1899b4f679e9cd4415 | 0 | zloirock/core-js,zloirock/core-js | var $ = require('../internals/export');
var uncurryThis = require('../internals/function-uncurry-this');
var $isCallable = require('../internals/is-callable');
var inspectSource = require('../internals/inspect-source');
var classRegExp = /^\s*class\b/;
var exec = uncurryThis(classRegExp.exec);
// `Function.isCallable` method
// https://github.com/caitp/TC39-Proposals/blob/trunk/tc39-reflect-isconstructor-iscallable.md
$({ target: 'Function', stat: true, sham: true }, {
isCallable: function isCallable(argument) {
// we can't properly detect `[[IsClassConstructor]]` internal slot without `Function#toString` check
return $isCallable(argument) && !exec(classRegExp, inspectSource(argument));
}
});
| packages/core-js/modules/esnext.function.is-callable.js | var $ = require('../internals/export');
var $isCallable = require('../internals/is-callable');
var inspectSource = require('../internals/inspect-source');
var classRegExp = /^\s*class\b/;
var exec = classRegExp.exec;
// `Function.isCallable` method
// https://github.com/caitp/TC39-Proposals/blob/trunk/tc39-reflect-isconstructor-iscallable.md
$({ target: 'Function', stat: true, sham: true }, {
isCallable: function isCallable(argument) {
// we can't properly detect `[[IsClassConstructor]]` internal slot without `Function#toString` check
return $isCallable(argument) && !exec.call(classRegExp, inspectSource(argument));
}
});
| refatoring
| packages/core-js/modules/esnext.function.is-callable.js | refatoring | <ide><path>ackages/core-js/modules/esnext.function.is-callable.js
<ide> var $ = require('../internals/export');
<add>var uncurryThis = require('../internals/function-uncurry-this');
<ide> var $isCallable = require('../internals/is-callable');
<ide> var inspectSource = require('../internals/inspect-source');
<ide>
<ide> var classRegExp = /^\s*class\b/;
<del>var exec = classRegExp.exec;
<add>var exec = uncurryThis(classRegExp.exec);
<ide>
<ide> // `Function.isCallable` method
<ide> // https://github.com/caitp/TC39-Proposals/blob/trunk/tc39-reflect-isconstructor-iscallable.md
<ide> $({ target: 'Function', stat: true, sham: true }, {
<ide> isCallable: function isCallable(argument) {
<ide> // we can't properly detect `[[IsClassConstructor]]` internal slot without `Function#toString` check
<del> return $isCallable(argument) && !exec.call(classRegExp, inspectSource(argument));
<add> return $isCallable(argument) && !exec(classRegExp, inspectSource(argument));
<ide> }
<ide> }); |
|
Java | apache-2.0 | 2ad69698241b6cc15a7121c1f46ee325a7e00d50 | 0 | zqian/sakai,rodriguezdevera/sakai,willkara/sakai,zqian/sakai,conder/sakai,joserabal/sakai,zqian/sakai,zqian/sakai,ouit0408/sakai,OpenCollabZA/sakai,joserabal/sakai,Fudan-University/sakai,willkara/sakai,frasese/sakai,willkara/sakai,OpenCollabZA/sakai,ouit0408/sakai,joserabal/sakai,frasese/sakai,OpenCollabZA/sakai,rodriguezdevera/sakai,joserabal/sakai,willkara/sakai,joserabal/sakai,duke-compsci290-spring2016/sakai,Fudan-University/sakai,ouit0408/sakai,willkara/sakai,ktakacs/sakai,joserabal/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,ouit0408/sakai,ouit0408/sakai,OpenCollabZA/sakai,Fudan-University/sakai,zqian/sakai,zqian/sakai,conder/sakai,OpenCollabZA/sakai,conder/sakai,duke-compsci290-spring2016/sakai,ktakacs/sakai,rodriguezdevera/sakai,joserabal/sakai,willkara/sakai,conder/sakai,Fudan-University/sakai,duke-compsci290-spring2016/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,zqian/sakai,joserabal/sakai,Fudan-University/sakai,rodriguezdevera/sakai,ouit0408/sakai,ktakacs/sakai,zqian/sakai,ktakacs/sakai,frasese/sakai,Fudan-University/sakai,OpenCollabZA/sakai,ktakacs/sakai,frasese/sakai,rodriguezdevera/sakai,Fudan-University/sakai,OpenCollabZA/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,ouit0408/sakai,willkara/sakai,ktakacs/sakai,conder/sakai,frasese/sakai,ouit0408/sakai,rodriguezdevera/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,conder/sakai,conder/sakai,conder/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,Fudan-University/sakai,ktakacs/sakai,frasese/sakai | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.vm;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.sakaiproject.thread_local.cover.ThreadLocalManager;
import org.sakaiproject.tool.api.ToolURL;
import org.sakaiproject.tool.api.ToolURLManager;
import org.sakaiproject.util.FormattedText;
/**
* <p>
* PortletActionURL provides a URL with settable and re-settable parameters based on a portlet window's ActionURL base URL.
* </p>
*/
public class ActionURL
{
/** The parameter for portlet window id (pid). */
public final static String PARAM_PID = "pid";
/** The parameter for site. */
public final static String PARAM_SITE = "site";
/** The parameter for page. */
public final static String PARAM_PAGE = "page";
/** The parameter for paneld. */
public final static String PARAM_PANEL = "panel";
/** The base url to the portlet. */
protected String m_base = null;
/** parameters. */
protected Map m_parameters = new Hashtable();
/** The portlet window id, if any. */
protected String m_pid = null;
/** The panel, if any. */
protected String m_panel = null;
/** The site, if any. */
protected String m_site = null;
/** The site pge, if any. */
protected String m_page = null;
/** Is this an Action URL */
protected boolean m_isAction = false;
/** Is this a Resource URL */
protected String m_resourcePath = null;
/** Pre-formatted query string, in lieu of <name, value> parameters */
protected String m_QueryString = "";
/** HttpServletRequest * */
protected HttpServletRequest m_request;
/**
* Construct with a base URL to the portlet, no parameters
*
* @param base
* The base URL
*/
public ActionURL(String base, HttpServletRequest request)
{
m_base = base;
m_request = request;
}
/**
* "Reset" the URL by clearing the parameters.
*
* @return this.
*/
public ActionURL reset()
{
m_parameters = new Hashtable();
m_isAction = false;
m_resourcePath = null;
m_QueryString = "";
return this;
}
/**
* Set or replace (or remove if value is null) a parameter
*
* @param name
* The parameter name.
* @param value
* The parameter value.
* @return this.
*/
public ActionURL setParameter(String name, String value)
{
if (value == null)
{
m_parameters.remove(name);
}
else
{
m_parameters.put(name, value);
}
return this;
}
/**
* Set this URL to be an 'action' URL, one that usually does a Form POST
*
* @return this
*/
public ActionURL setAction()
{
m_isAction = true;
return this;
}
/**
* Set or reset the pid.
*
* @param pid
* The portlet window id.
*/
public ActionURL setPid(String pid)
{
m_pid = pid;
return this;
}
/**
* Set or reset the site.
*
* @param site
* The site id.
*/
public ActionURL setSite(String site)
{
m_site = site;
return this;
}
/**
* Set or reset the page.
*
* @param page
* The page id.
*/
public ActionURL setPage(String page)
{
m_page = page;
return this;
}
/**
* Set or reset the panel.
*
* @param panel
* The panel id.
*/
public ActionURL setPanel(String panel)
{
m_panel = panel;
return this;
}
/**
* Reneder the URL with parameters
*
* @return The URL.
*/
public String toString()
{
String toolURL = getToolURL();
if (toolURL != null) return FormattedText.sanitizeHrefURL(toolURL);
String rv = m_base;
char c = '?';
if (m_parameters.size() > 0)
{
for (Iterator iEntries = m_parameters.entrySet().iterator(); iEntries.hasNext();)
{
Map.Entry entry = (Map.Entry) iEntries.next();
rv = rv + c + entry.getKey() + "=" + entry.getValue();
c = '&';
}
}
// Add pre-formatted query string as is
if ((m_QueryString != null) && (m_QueryString.length() > 0))
{
rv = rv + c + m_QueryString;
c = '&';
}
// add the pid if defined and not overridden
if ((m_pid != null) && (!m_parameters.containsKey(PARAM_PID)))
{
rv = rv + c + PARAM_PID + "=" + m_pid;
c = '&';
}
// add the site if defined and not overridden
if ((m_site != null) && (!m_parameters.containsKey(PARAM_SITE)))
{
rv = rv + c + PARAM_SITE + "=" + m_site;
c = '&';
}
// add the page if defined and not overridden
if ((m_page != null) && (!m_parameters.containsKey(PARAM_PAGE)))
{
rv = rv + c + PARAM_PAGE + "=" + m_page;
c = '&';
}
// add the panel if defined and not overridden
if ((m_panel != null) && (!m_parameters.containsKey(PARAM_PANEL)))
{
rv = rv + c + PARAM_PANEL + "=" + m_panel;
c = '&';
}
reset();
return FormattedText.sanitizeHrefURL(rv);
}
private String getToolURL()
{
ToolURLManager urlManager = getToolURLManager();
// ToolURLManager is not set, use default implementation
if (urlManager == null) return null;
ToolURL url = null;
String path = m_base;
if (m_isAction)
{
url = urlManager.createActionURL();
}
else if (m_resourcePath != null)
{
url = urlManager.createResourceURL();
path = m_resourcePath;
}
else
{
url = urlManager.createRenderURL();
}
if (url != null)
{
if ((this.m_QueryString != null) && (this.m_QueryString.length() > 0))
{
if (path.indexOf('?') == -1)
{
path = path + '?' + this.m_QueryString;
}
else
{
path = path + '&' + this.m_QueryString;
}
}
url.setPath(path);
if ((m_pid != null) && (!m_parameters.containsKey(PARAM_PID)))
{
m_parameters.put(PARAM_PID, m_pid);
}
// add the site if defined and not overridden
if ((m_site != null) && (!m_parameters.containsKey(PARAM_SITE)))
{
m_parameters.put(PARAM_SITE, m_site);
}
// add the page if defined and not overridden
if ((m_page != null) && (!m_parameters.containsKey(PARAM_PAGE)))
{
m_parameters.put(PARAM_PAGE, m_page);
}
// add the panel if defined and not overridden
if ((m_panel != null) && (!m_parameters.containsKey(PARAM_PANEL)))
{
m_parameters.put(PARAM_PANEL, m_panel);
}
url.setParameters(m_parameters);
reset();
return url.toString();
}
return null;
}
private ToolURLManager getToolURLManager()
{
HttpServletRequest request = m_request;
if (request == null)
{
request = (HttpServletRequest) ThreadLocalManager.get(ToolURL.HTTP_SERVLET_REQUEST);
}
if (request != null)
{
return (ToolURLManager) request.getAttribute(ToolURL.MANAGER);
}
return null;
}
/**
* {@inheritDoc}
*/
public boolean equals(Object obj)
{
boolean equals = false;
if ((obj != null) && (obj instanceof ActionURL))
{
equals = ((ActionURL) obj).toString().equals(toString());
}
return equals;
}
/**
* @param resource
* Whether the URL is a resource
*/
public ActionURL setResourcePath(String path)
{
m_resourcePath = path;
return this;
}
/**
* @param queryString
* The m_QueryString to set.
*/
public ActionURL setQueryString(String queryString)
{
m_QueryString = queryString;
return this;
}
}
| velocity/tool/src/java/org/sakaiproject/vm/ActionURL.java | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.vm;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.sakaiproject.thread_local.cover.ThreadLocalManager;
import org.sakaiproject.tool.api.ToolURL;
import org.sakaiproject.tool.api.ToolURLManager;
/**
* <p>
* PortletActionURL provides a URL with settable and re-settable parameters based on a portlet window's ActionURL base URL.
* </p>
*/
public class ActionURL
{
/** The parameter for portlet window id (pid). */
public final static String PARAM_PID = "pid";
/** The parameter for site. */
public final static String PARAM_SITE = "site";
/** The parameter for page. */
public final static String PARAM_PAGE = "page";
/** The parameter for paneld. */
public final static String PARAM_PANEL = "panel";
/** The base url to the portlet. */
protected String m_base = null;
/** parameters. */
protected Map m_parameters = new Hashtable();
/** The portlet window id, if any. */
protected String m_pid = null;
/** The panel, if any. */
protected String m_panel = null;
/** The site, if any. */
protected String m_site = null;
/** The site pge, if any. */
protected String m_page = null;
/** Is this an Action URL */
protected boolean m_isAction = false;
/** Is this a Resource URL */
protected String m_resourcePath = null;
/** Pre-formatted query string, in lieu of <name, value> parameters */
protected String m_QueryString = "";
/** HttpServletRequest * */
protected HttpServletRequest m_request;
/**
* Construct with a base URL to the portlet, no parameters
*
* @param base
* The base URL
*/
public ActionURL(String base, HttpServletRequest request)
{
m_base = base;
m_request = request;
}
/**
* "Reset" the URL by clearing the parameters.
*
* @return this.
*/
public ActionURL reset()
{
m_parameters = new Hashtable();
m_isAction = false;
m_resourcePath = null;
m_QueryString = "";
return this;
}
/**
* Set or replace (or remove if value is null) a parameter
*
* @param name
* The parameter name.
* @param value
* The parameter value.
* @return this.
*/
public ActionURL setParameter(String name, String value)
{
if (value == null)
{
m_parameters.remove(name);
}
else
{
m_parameters.put(name, value);
}
return this;
}
/**
* Set this URL to be an 'action' URL, one that usually does a Form POST
*
* @return this
*/
public ActionURL setAction()
{
m_isAction = true;
return this;
}
/**
* Set or reset the pid.
*
* @param pid
* The portlet window id.
*/
public ActionURL setPid(String pid)
{
m_pid = pid;
return this;
}
/**
* Set or reset the site.
*
* @param site
* The site id.
*/
public ActionURL setSite(String site)
{
m_site = site;
return this;
}
/**
* Set or reset the page.
*
* @param page
* The page id.
*/
public ActionURL setPage(String page)
{
m_page = page;
return this;
}
/**
* Set or reset the panel.
*
* @param panel
* The panel id.
*/
public ActionURL setPanel(String panel)
{
m_panel = panel;
return this;
}
/**
* Reneder the URL with parameters
*
* @return The URL.
*/
public String toString()
{
String toolURL = getToolURL();
if (toolURL != null) return toolURL;
String rv = m_base;
char c = '?';
if (m_parameters.size() > 0)
{
for (Iterator iEntries = m_parameters.entrySet().iterator(); iEntries.hasNext();)
{
Map.Entry entry = (Map.Entry) iEntries.next();
rv = rv + c + entry.getKey() + "=" + entry.getValue();
c = '&';
}
}
// Add pre-formatted query string as is
if ((m_QueryString != null) && (m_QueryString.length() > 0))
{
rv = rv + c + m_QueryString;
c = '&';
}
// add the pid if defined and not overridden
if ((m_pid != null) && (!m_parameters.containsKey(PARAM_PID)))
{
rv = rv + c + PARAM_PID + "=" + m_pid;
c = '&';
}
// add the site if defined and not overridden
if ((m_site != null) && (!m_parameters.containsKey(PARAM_SITE)))
{
rv = rv + c + PARAM_SITE + "=" + m_site;
c = '&';
}
// add the page if defined and not overridden
if ((m_page != null) && (!m_parameters.containsKey(PARAM_PAGE)))
{
rv = rv + c + PARAM_PAGE + "=" + m_page;
c = '&';
}
// add the panel if defined and not overridden
if ((m_panel != null) && (!m_parameters.containsKey(PARAM_PANEL)))
{
rv = rv + c + PARAM_PANEL + "=" + m_panel;
c = '&';
}
reset();
return rv;
}
private String getToolURL()
{
ToolURLManager urlManager = getToolURLManager();
// ToolURLManager is not set, use default implementation
if (urlManager == null) return null;
ToolURL url = null;
String path = m_base;
if (m_isAction)
{
url = urlManager.createActionURL();
}
else if (m_resourcePath != null)
{
url = urlManager.createResourceURL();
path = m_resourcePath;
}
else
{
url = urlManager.createRenderURL();
}
if (url != null)
{
if ((this.m_QueryString != null) && (this.m_QueryString.length() > 0))
{
if (path.indexOf('?') == -1)
{
path = path + '?' + this.m_QueryString;
}
else
{
path = path + '&' + this.m_QueryString;
}
}
url.setPath(path);
if ((m_pid != null) && (!m_parameters.containsKey(PARAM_PID)))
{
m_parameters.put(PARAM_PID, m_pid);
}
// add the site if defined and not overridden
if ((m_site != null) && (!m_parameters.containsKey(PARAM_SITE)))
{
m_parameters.put(PARAM_SITE, m_site);
}
// add the page if defined and not overridden
if ((m_page != null) && (!m_parameters.containsKey(PARAM_PAGE)))
{
m_parameters.put(PARAM_PAGE, m_page);
}
// add the panel if defined and not overridden
if ((m_panel != null) && (!m_parameters.containsKey(PARAM_PANEL)))
{
m_parameters.put(PARAM_PANEL, m_panel);
}
url.setParameters(m_parameters);
reset();
return url.toString();
}
return null;
}
private ToolURLManager getToolURLManager()
{
HttpServletRequest request = m_request;
if (request == null)
{
request = (HttpServletRequest) ThreadLocalManager.get(ToolURL.HTTP_SERVLET_REQUEST);
}
if (request != null)
{
return (ToolURLManager) request.getAttribute(ToolURL.MANAGER);
}
return null;
}
/**
* {@inheritDoc}
*/
public boolean equals(Object obj)
{
boolean equals = false;
if ((obj != null) && (obj instanceof ActionURL))
{
equals = ((ActionURL) obj).toString().equals(toString());
}
return equals;
}
/**
* @param resource
* Whether the URL is a resource
*/
public ActionURL setResourcePath(String path)
{
m_resourcePath = path;
return this;
}
/**
* @param queryString
* The m_QueryString to set.
*/
public ActionURL setQueryString(String queryString)
{
m_QueryString = queryString;
return this;
}
}
| SAK-30419
| velocity/tool/src/java/org/sakaiproject/vm/ActionURL.java | SAK-30419 | <ide><path>elocity/tool/src/java/org/sakaiproject/vm/ActionURL.java
<ide> import org.sakaiproject.thread_local.cover.ThreadLocalManager;
<ide> import org.sakaiproject.tool.api.ToolURL;
<ide> import org.sakaiproject.tool.api.ToolURLManager;
<add>import org.sakaiproject.util.FormattedText;
<ide>
<ide> /**
<ide> * <p>
<ide> public String toString()
<ide> {
<ide> String toolURL = getToolURL();
<del> if (toolURL != null) return toolURL;
<add> if (toolURL != null) return FormattedText.sanitizeHrefURL(toolURL);
<ide>
<ide> String rv = m_base;
<ide> char c = '?';
<ide> }
<ide>
<ide> reset();
<del> return rv;
<add> return FormattedText.sanitizeHrefURL(rv);
<ide> }
<ide>
<ide> private String getToolURL() |
|
Java | apache-2.0 | b1cab871f6b5730875be61babddb12128041e9a8 | 0 | cwenao/DSAA | /**
* Company
* Copyright (C) 2014-2017 All Rights Reserved.
*/
package com.cwenao.datastructure;
import com.cwenao.util.DrawGraphForSearch;
import com.cwenao.util.Vertexes;
import java.util.ArrayDeque;
import java.util.Queue;
/**
* @author cwenao
* @version $Id BreadthFirstSearchPath.java, v 0.1 2017-07-07 8:17 cwenao Exp $$
*/
public class BreadthFirstSearchPath {
private static final int maxVertexes = 9;
private static Vertexes[] vertexes;
private static int[][] adjacent;
public static void entrySearar (Integer start) {
Queue queue = new ArrayDeque();
queue.add(start);
while (!queue.isEmpty()) {
int x = (int) queue.poll();
vertexes[x].setVisited(true);
for(int i =0;i<maxVertexes;i++) {
if (adjacent[x][i] == 1 && vertexes[i].getVisited() == false) {
printVertexe(i);
vertexes[i].setVisited(true);
queue.offer(i);
}
}
}
}
private static void printVertexe(int i) {
System.out.println(vertexes[i].getVertex() + " ");
}
public static void printAdjacent(int[][] adjacent) {
for(int[] line:adjacent) {
for(int i:line) {
System.out.print(i + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
DrawGraphForSearch drawGraphForSearch = new DrawGraphForSearch(maxVertexes);
char[] ver = {'A','B','C','D','E','F','G','H','I'};
vertexes = drawGraphForSearch.getVertexes();
for(int i=0;i<vertexes.length;i++) {
Vertexes vertexesX = new Vertexes(ver[i]);
vertexes[i] = vertexesX;
}
drawGraphForSearch.addEdge(0,1);
drawGraphForSearch.addEdge(0,2);
drawGraphForSearch.addEdge(1,2);
drawGraphForSearch.addEdge(2,3);
drawGraphForSearch.addEdge(2,5);
drawGraphForSearch.addEdge(3,5);
drawGraphForSearch.addEdge(5,8);
drawGraphForSearch.setVertexes(vertexes);
adjacent = drawGraphForSearch.getAdjacent();
printAdjacent(adjacent);
entrySearar(0);
}
}
| data-structure/src/main/java/com/cwenao/datastructure/BreadthFirstSearchPath.java | /**
* Company
* Copyright (C) 2014-2017 All Rights Reserved.
*/
package com.cwenao.datastructure;
import com.cwenao.util.DrawGraphForSearch;
import com.cwenao.util.Vertexes;
import java.util.ArrayDeque;
import java.util.Queue;
/**
* @author cwenao
* @version $Id BreadthFirstSearchPath.java, v 0.1 2017-07-07 8:17 cwenao Exp $$
*/
public class BreadthFirstSearchPath {
private static final int maxVertexes = 5;
private static Vertexes[] vertexes;
private static int[][] adjacent;
public static void entrySearar (Integer start) {
Queue queue = new ArrayDeque();
queue.add(start);
while (!queue.isEmpty()) {
int x = (int) queue.poll();
printVertexe(x);
for(int i =1;i<maxVertexes;i++) {
if (adjacent[x][i] != 1 && vertexes[x].getVisited() == false) {
vertexes[x].setVisited(true);
queue.offer(i);
}
}
}
}
private static void printVertexe(int i) {
System.out.println(vertexes[i].getVertex() + " ");
}
public static void main(String[] args) {
DrawGraphForSearch drawGraphForSearch = new DrawGraphForSearch(maxVertexes);
char[] ver = {'A','B','C','D','E'}; //,'D','E','F','G','H','I'
vertexes = drawGraphForSearch.getVertexes();
for(int i=0;i<vertexes.length;i++) {
Vertexes vertexesX = new Vertexes(ver[i]);
vertexes[i] = vertexesX;
}
drawGraphForSearch.addEdge(0,1);
drawGraphForSearch.addEdge(0,2);
drawGraphForSearch.addEdge(2,3);
drawGraphForSearch.addEdge(3,5);
drawGraphForSearch.addEdge(5,8);
drawGraphForSearch.setVertexes(vertexes);
adjacent = drawGraphForSearch.getAdjacent();
entrySearar(0);
}
}
| update the breadthfirst
| data-structure/src/main/java/com/cwenao/datastructure/BreadthFirstSearchPath.java | update the breadthfirst | <ide><path>ata-structure/src/main/java/com/cwenao/datastructure/BreadthFirstSearchPath.java
<ide> */
<ide> public class BreadthFirstSearchPath {
<ide>
<del> private static final int maxVertexes = 5;
<add> private static final int maxVertexes = 9;
<ide> private static Vertexes[] vertexes;
<ide> private static int[][] adjacent;
<ide>
<ide>
<ide> while (!queue.isEmpty()) {
<ide> int x = (int) queue.poll();
<del> printVertexe(x);
<del> for(int i =1;i<maxVertexes;i++) {
<del> if (adjacent[x][i] != 1 && vertexes[x].getVisited() == false) {
<del> vertexes[x].setVisited(true);
<add> vertexes[x].setVisited(true);
<add>
<add> for(int i =0;i<maxVertexes;i++) {
<add> if (adjacent[x][i] == 1 && vertexes[i].getVisited() == false) {
<add> printVertexe(i);
<add> vertexes[i].setVisited(true);
<ide> queue.offer(i);
<ide> }
<ide> }
<add>
<ide> }
<ide> }
<ide>
<ide> private static void printVertexe(int i) {
<ide> System.out.println(vertexes[i].getVertex() + " ");
<ide> }
<add>
<add> public static void printAdjacent(int[][] adjacent) {
<add>
<add> for(int[] line:adjacent) {
<add> for(int i:line) {
<add> System.out.print(i + " ");
<add> }
<add> System.out.println();
<add> }
<add> }
<add>
<ide> public static void main(String[] args) {
<ide> DrawGraphForSearch drawGraphForSearch = new DrawGraphForSearch(maxVertexes);
<ide>
<del> char[] ver = {'A','B','C','D','E'}; //,'D','E','F','G','H','I'
<add> char[] ver = {'A','B','C','D','E','F','G','H','I'};
<ide>
<ide> vertexes = drawGraphForSearch.getVertexes();
<ide>
<ide> Vertexes vertexesX = new Vertexes(ver[i]);
<ide> vertexes[i] = vertexesX;
<ide> }
<add>
<ide> drawGraphForSearch.addEdge(0,1);
<ide> drawGraphForSearch.addEdge(0,2);
<add> drawGraphForSearch.addEdge(1,2);
<ide> drawGraphForSearch.addEdge(2,3);
<add> drawGraphForSearch.addEdge(2,5);
<ide> drawGraphForSearch.addEdge(3,5);
<ide> drawGraphForSearch.addEdge(5,8);
<ide>
<ide> drawGraphForSearch.setVertexes(vertexes);
<ide> adjacent = drawGraphForSearch.getAdjacent();
<add>
<add> printAdjacent(adjacent);
<add>
<ide> entrySearar(0);
<ide>
<ide> } |
|
JavaScript | apache-2.0 | d150f85045c2346fba71eba4c3020cb44828f452 | 0 | minbrowser/min,minbrowser/min,minbrowser/min | /*
Wraps APIs that are only available in the main process in IPC messages, so that the BrowserWindow can use them
*/
ipc.handle('test-invoke', function () {
return 1
})
ipc.handle('reloadWindow', function () {
mainWindow.webContents.reload()
})
ipc.handle('startFileDrag', function (e, path) {
app.getFileIcon(path, {}).then(function (icon) {
mainWindow.webContents.startDrag({
file: path,
icon: icon
})
})
})
ipc.handle('showFocusModeDialog1', function () {
dialog.showMessageBox({
type: 'info',
buttons: [l('closeDialog')],
message: l('isFocusMode'),
detail: l('focusModeExplanation1') + ' ' + l('focusModeExplanation2')
})
})
ipc.handle('showFocusModeDialog2', function () {
dialog.showMessageBox({
type: 'info',
buttons: [l('closeDialog')],
message: l('isFocusMode'),
detail: l('focusModeExplanation2')
})
})
ipc.handle('showOpenDialog', async function (e, options) {
const result = await dialog.showOpenDialog(mainWindow, options)
return result.filePaths
})
ipc.handle('showSaveDialog', async function (e, options) {
const result = await dialog.showSaveDialog(mainWindow, options)
return result.filePath
})
ipc.handle('addWordToSpellCheckerDictionary', function (e, word) {
session.fromPartition('persist:webcontent').addWordToSpellCheckerDictionary(word)
})
ipc.handle('downloadURL', function (e, url) {
mainWindow.webContents.downloadURL(url)
})
ipc.handle('clearStorageData', function () {
return session.fromPartition('persist:webcontent').clearStorageData()
/* It's important not to delete data from file:// from the default partition, since that would also remove internal browser data (such as bookmarks). However, HTTP data does need to be cleared, as there can be leftover data from loading external resources in the browser UI */
.then(function () {
return session.defaultSession.clearStorageData({ origin: 'http://' })
})
.then(function () {
return session.defaultSession.clearStorageData({ origin: 'https://' })
})
.then(function () {
return session.fromPartition('persist:webcontent').clearCache()
})
.then(function () {
return session.fromPartition('persist:webcontent').clearHostResolverCache()
})
.then(function () {
return session.fromPartition('persist:webcontent').clearAuthCache()
})
.then(function () {
return session.defaultSession.clearCache()
})
.then(function () {
return session.defaultSession.clearHostResolverCache()
})
.then(function () {
return session.defaultSession.clearAuthCache()
})
})
/* window actions */
ipc.handle('minimize', function (e) {
mainWindow.minimize()
// workaround for https://github.com/minbrowser/min/issues/1662
mainWindow.webContents.send('minimize')
})
ipc.handle('maximize', function (e) {
mainWindow.maximize()
// workaround for https://github.com/minbrowser/min/issues/1662
mainWindow.webContents.send('maximize')
})
ipc.handle('unmaximize', function (e) {
mainWindow.unmaximize()
// workaround for https://github.com/minbrowser/min/issues/1662
mainWindow.webContents.send('unmaximize')
})
ipc.handle('close', function (e) {
mainWindow.close()
})
ipc.handle('setFullScreen', function (e, fullScreen) {
mainWindow.setFullScreen(e, fullScreen)
})
| main/remoteActions.js | /*
Wraps APIs that are only available in the main process in IPC messages, so that the BrowserWindow can use them
*/
ipc.handle('test-invoke', function () {
return 1
})
ipc.handle('reloadWindow', function () {
mainWindow.webContents.reload()
})
ipc.handle('startFileDrag', function (e, path) {
app.getFileIcon(path, {}).then(function (icon) {
mainWindow.webContents.startDrag({
file: path,
icon: icon
})
})
})
ipc.handle('showFocusModeDialog1', function () {
dialog.showMessageBox({
type: 'info',
buttons: [l('closeDialog')],
message: l('isFocusMode'),
detail: l('focusModeExplanation1') + ' ' + l('focusModeExplanation2')
})
})
ipc.handle('showFocusModeDialog2', function () {
dialog.showMessageBox({
type: 'info',
buttons: [l('closeDialog')],
message: l('isFocusMode'),
detail: l('focusModeExplanation2')
})
})
ipc.handle('showOpenDialog', async function (e, options) {
const result = await dialog.showOpenDialog(mainWindow, options)
return result.filePaths
})
ipc.handle('showSaveDialog', async function (e, options) {
const result = await dialog.showSaveDialog(mainWindow, options)
return result.filePath
})
ipc.handle('addWordToSpellCheckerDictionary', function (e, word) {
session.fromPartition('persist:webcontent').addWordToSpellCheckerDictionary(word)
})
ipc.handle('downloadURL', function (e, url) {
mainWindow.webContents.downloadURL(url)
})
ipc.handle('clearStorageData', function () {
/* It's important not to delete data from file:// here, since that would also remove internal browser data (such as bookmarks) */
return session.fromPartition('persist:webcontent').clearStorageData({ origin: 'http://' })
.then(function () {
session.fromPartition('persist:webcontent').clearStorageData({ origin: 'https://' })
})
})
/* window actions */
ipc.handle('minimize', function (e) {
mainWindow.minimize()
// workaround for https://github.com/minbrowser/min/issues/1662
mainWindow.webContents.send('minimize')
})
ipc.handle('maximize', function (e) {
mainWindow.maximize()
// workaround for https://github.com/minbrowser/min/issues/1662
mainWindow.webContents.send('maximize')
})
ipc.handle('unmaximize', function (e) {
mainWindow.unmaximize()
// workaround for https://github.com/minbrowser/min/issues/1662
mainWindow.webContents.send('unmaximize')
})
ipc.handle('close', function (e) {
mainWindow.close()
})
ipc.handle('setFullScreen', function (e, fullScreen) {
mainWindow.setFullScreen(e, fullScreen)
})
| clear additional storage types in clearStorageData (#1779)
| main/remoteActions.js | clear additional storage types in clearStorageData (#1779) | <ide><path>ain/remoteActions.js
<ide> })
<ide>
<ide> ipc.handle('clearStorageData', function () {
<del> /* It's important not to delete data from file:// here, since that would also remove internal browser data (such as bookmarks) */
<del> return session.fromPartition('persist:webcontent').clearStorageData({ origin: 'http://' })
<add> return session.fromPartition('persist:webcontent').clearStorageData()
<add> /* It's important not to delete data from file:// from the default partition, since that would also remove internal browser data (such as bookmarks). However, HTTP data does need to be cleared, as there can be leftover data from loading external resources in the browser UI */
<ide> .then(function () {
<del> session.fromPartition('persist:webcontent').clearStorageData({ origin: 'https://' })
<add> return session.defaultSession.clearStorageData({ origin: 'http://' })
<add> })
<add> .then(function () {
<add> return session.defaultSession.clearStorageData({ origin: 'https://' })
<add> })
<add> .then(function () {
<add> return session.fromPartition('persist:webcontent').clearCache()
<add> })
<add> .then(function () {
<add> return session.fromPartition('persist:webcontent').clearHostResolverCache()
<add> })
<add> .then(function () {
<add> return session.fromPartition('persist:webcontent').clearAuthCache()
<add> })
<add> .then(function () {
<add> return session.defaultSession.clearCache()
<add> })
<add> .then(function () {
<add> return session.defaultSession.clearHostResolverCache()
<add> })
<add> .then(function () {
<add> return session.defaultSession.clearAuthCache()
<ide> })
<ide> })
<ide> |
|
JavaScript | mit | 7bbb6daf53dabda6ac982a6a3989eaeb88e2653a | 0 | jzitelli/cannon.js,mcanthony/cannon.js,mcanthony/cannon.js,schteppe/cannon.js,Tezirg/cannon.js,schteppe/cannon.js,beni55/cannon.js,Tezirg/cannon.js,jzitelli/cannon.js,beni55/cannon.js | var Vec3 = require('./Vec3');
var Quaternion = require('./Quaternion');
module.exports = Transform;
/**
* @class Transform
* @constructor
*/
function Transform() {
/**
* @property {Vec3} position
*/
this.position = new Vec3();
/**
* @property {Quaternion} quaternion
*/
this.quaternion = new Quaternion();
}
var tmpQuat = new Quaternion();
/**
* @static
* @method pointToLocaFrame
* @param {Vec3} position
* @param {Quaternion} quaternion
* @param {Vec3} worldPoint
* @param {Vec3} result
*/
Transform.pointToLocalFrame = function(position, quaternion, worldPoint, result){
var result = result || new Vec3();
worldPoint.vsub(position, result);
quaternion.conjugate(tmpQuat);
tmpQuat.vmult(result, result);
return result;
};
/**
* Get a global point in local transform coordinates.
* @param {Vec3} point
* @param {Vec3} result
* @return {Vec3} The "result" vector object
*/
Transform.prototype.pointToLocal = function(worldPoint, result){
return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
};
/**
* @static
* @method pointToWorldFrame
* @param {Vec3} position
* @param {Vec3} quaternion
* @param {Vec3} localPoint
* @param {Vec3} result
*/
Transform.pointToWorldFrame = function(position, quaternion, localPoint, result){
var result = result || new Vec3();
quaternion.vmult(localPoint, result);
result.vadd(position, result);
return result;
};
/**
* Get a local point in global transform coordinates.
* @param {Vec3} point
* @param {Vec3} result
* @return {Vec3} The "result" vector object
*/
Transform.prototype.pointToWorld = function(localPoint, result){
return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
};
Transform.prototype.vectorToWorldFrame = function(localVector, result){
var result = result || new Vec3();
this.quaternion.vmult(localVector, result);
return result;
};
Transform.vectorToLocalFrame = function(position, quaternion, worldVector, result){
var result = result || new Vec3();
quaternion.w *= -1;
quaternion.vmult(worldVector, result);
quaternion.w *= -1;
return result;
};
| src/math/Transform.js | var Vec3 = require('./Vec3');
var Quaternion = require('./Quaternion');
module.exports = Transform;
/**
* @class Transform
* @constructor
*/
function Transform() {
/**
* @property {Vec3} position
*/
this.position = new Vec3();
/**
* @property {Quaternion} quaternion
*/
this.quaternion = new Quaternion();
}
var tmpQuat = new Quaternion();
/**
* @static
* @method pointToLocaFrame
* @param {Vec3} position
* @param {Quaternion} quaternion
* @param {Vec3} worldPoint
* @param {Vec3} result
*/
Transform.pointToLocalFrame = function(position, quaternion, worldPoint, result){
var result = result || new Vec3();
worldPoint.vsub(position, result);
quaternion.conjugate(tmpQuat);
tmpQuat.vmult(result, result);
return result;
};
/**
* @static
* @method pointToWorldFrame
* @param {Vec3} position
* @param {Vec3} quaternion
* @param {Vec3} localPoint
* @param {Vec3} result
*/
Transform.pointToWorldFrame = function(position, quaternion, localPoint, result){
var result = result || new Vec3();
quaternion.vmult(localPoint, result);
result.vadd(position, result);
return result;
};
Transform.prototype.vectorToWorldFrame = function(localVector, result){
var result = result || new Vec3();
this.quaternion.vmult(localVector, result);
return result;
};
Transform.vectorToLocalFrame = function(position, quaternion, worldVector, result){
var result = result || new Vec3();
quaternion.w *= -1;
quaternion.vmult(worldVector, result);
quaternion.w *= -1;
return result;
};
| added Transform.prototype.pointToLocal and .pointToWorld
| src/math/Transform.js | added Transform.prototype.pointToLocal and .pointToWorld | <ide><path>rc/math/Transform.js
<ide> * @property {Vec3} position
<ide> */
<ide> this.position = new Vec3();
<del>
<add>
<ide> /**
<ide> * @property {Quaternion} quaternion
<ide> */
<ide> };
<ide>
<ide> /**
<add> * Get a global point in local transform coordinates.
<add> * @param {Vec3} point
<add> * @param {Vec3} result
<add> * @return {Vec3} The "result" vector object
<add> */
<add>Transform.prototype.pointToLocal = function(worldPoint, result){
<add> return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
<add>};
<add>
<add>/**
<ide> * @static
<ide> * @method pointToWorldFrame
<ide> * @param {Vec3} position
<ide> return result;
<ide> };
<ide>
<add>/**
<add> * Get a local point in global transform coordinates.
<add> * @param {Vec3} point
<add> * @param {Vec3} result
<add> * @return {Vec3} The "result" vector object
<add> */
<add>Transform.prototype.pointToWorld = function(localPoint, result){
<add> return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
<add>};
<add>
<add>
<ide> Transform.prototype.vectorToWorldFrame = function(localVector, result){
<ide> var result = result || new Vec3();
<ide> this.quaternion.vmult(localVector, result); |
|
Java | bsd-2-clause | 0ae7f0a5673f2d72b5ce09a8902c318b75e8c32e | 0 | clementval/claw-compiler,clementval/claw-compiler | /*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package cx2x.xcodeml.xelement;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
/**
* The XtypeTable represents the typeTable (3.1) element in XcodeML intermediate
* representation.
*
* Elements: ( FbasicType | FfunctionType | FstructType ) *
* - Optional:
* - FbasicType (XbasicType)
* - FfunctionType (XfctType)
* - FstructType (XstructType)
*
* @author clementval
*/
public class XtypeTable extends XbaseElement {
private static final int HASH_LENGTH = 12;
private static final String FCT_HASH_PREFIX = "F";
private Map<String, Xtype> _table;
/**
* Xelement standard ctor. Pass the base element to the base class and read
* inner information (elements and attributes).
* @param baseElement The root element of the Xelement
*/
public XtypeTable(Element baseElement){
super(baseElement);
_table = new LinkedHashMap<>();
readTable();
}
/**
* Read the type table.
*/
private void readTable(){
// TODO read all element in one loop.
// Read basic type
NodeList basicTypes = baseElement.getElementsByTagName(XelementName.BASIC_TYPE);
for (int i = 0; i < basicTypes.getLength(); i++) {
Node n = basicTypes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
XbasicType bt = new XbasicType(el);
_table.put(bt.getType(), bt);
}
}
// Read fct type
NodeList fctTypes = baseElement.getElementsByTagName(XelementName.FCT_TYPE);
for (int i = 0; i < fctTypes.getLength(); i++) {
Node n = fctTypes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
XfctType ft = new XfctType(el);
_table.put(ft.getType(), ft);
}
}
// Read struct type
NodeList structTypes =
baseElement.getElementsByTagName(XelementName.F_STRUCT_TYPE);
for (int i = 0; i < structTypes.getLength(); i++) {
Node n = structTypes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
// TODO create XstructType object and insert it in the table
}
}
}
/**
* Get number of elements in the type table.
* @return Number of elements in the table.
*/
public int count(){
return _table.size();
}
/**
* Add a new element in the type table.
* @param type The new type to be added.
*/
public void add(Xtype type){
baseElement.appendChild(type.cloneNode());
_table.put(type.getType(), type);
}
/**
* Get an element from the type table.
* @param key Key of the element to be returned.
* @return Xtype object if found in the table. Null otherwise.
*/
public Xtype get(String key) {
if(_table.containsKey(key)){
return _table.get(key);
}
return null;
}
/**
* Get a new unique function hash for the type table.
* @return A unique function hash as String value.
*/
public String generateFctTypeHash(){
String hash;
do {
hash = FCT_HASH_PREFIX + generateHash(HASH_LENGTH);
} while(_table.containsKey(hash));
return hash;
}
/**
* Generate a new unique type hash for the table.
* @param length Length of the hash string to be generated.
* @return The new unique hash.
*/
private String generateHash(int length){
Random r = new Random();
StringBuilder sb = new StringBuilder();
while(sb.length() < length){
sb.append(Integer.toHexString(r.nextInt()));
}
return sb.toString().substring(0, length);
}
}
| omni-cx2x/src/cx2x/xcodeml/xelement/XtypeTable.java | /*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package cx2x.xcodeml.xelement;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.Hashtable;
import java.util.Random;
/**
* The XtypeTable represents the typeTable (3.1) element in XcodeML intermediate
* representation.
*
* Elements: ( FbasicType | FfunctionType | FstructType ) *
* - Optional:
* - FbasicType (XbasicType)
* - FfunctionType (XfctType)
* - FstructType (XstructType)
*
* @author clementval
*/
public class XtypeTable extends XbaseElement {
private static final int HASH_LENGTH = 12;
private static final String FCT_HASH_PREFIX = "F";
private Hashtable<String, Xtype> _table;
/**
* Xelement standard ctor. Pass the base element to the base class and read
* inner information (elements and attributes).
* @param baseElement The root element of the Xelement
*/
public XtypeTable(Element baseElement){
super(baseElement);
_table = new Hashtable<>();
readTable();
}
/**
* Read the type table.
*/
private void readTable(){
// Read basic type
NodeList basicTypes = baseElement.getElementsByTagName(XelementName.BASIC_TYPE);
for (int i = 0; i < basicTypes.getLength(); i++) {
Node n = basicTypes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
XbasicType bt = new XbasicType(el);
_table.put(bt.getType(), bt);
}
}
// Read fct type
NodeList fctTypes = baseElement.getElementsByTagName(XelementName.FCT_TYPE);
for (int i = 0; i < fctTypes.getLength(); i++) {
Node n = fctTypes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
XfctType ft = new XfctType(el);
_table.put(ft.getType(), ft);
}
}
// Read struct type
NodeList structTypes =
baseElement.getElementsByTagName(XelementName.F_STRUCT_TYPE);
for (int i = 0; i < structTypes.getLength(); i++) {
Node n = structTypes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
// TODO create XstructType object and insert it in the table
}
}
}
/**
* Get number of elements in the type table.
* @return Number of elements in the table.
*/
public int count(){
return _table.size();
}
/**
* Add a new element in the type table.
* @param type The new type to be added.
*/
public void add(Xtype type){
baseElement.appendChild(type.cloneNode());
_table.put(type.getType(), type);
}
/**
* Get an element from the type table.
* @param key Key of the element to be returned.
* @return Xtype object if found in the table. Null otherwise.
*/
public Xtype get(String key) {
if(_table.containsKey(key)){
return _table.get(key);
}
return null;
}
/**
* Get a new unique function hash for the type table.
* @return A unique function hash as String value.
*/
public String generateFctTypeHash(){
String hash;
do {
hash = FCT_HASH_PREFIX + generateHash(HASH_LENGTH);
} while(_table.containsKey(hash));
return hash;
}
/**
* Generate a new unique type hash for the table.
* @param length Length of the hash string to be generated.
* @return The new unique hash.
*/
private String generateHash(int length){
Random r = new Random();
StringBuilder sb = new StringBuilder();
while(sb.length() < length){
sb.append(Integer.toHexString(r.nextInt()));
}
return sb.toString().substring(0, length);
}
}
| Change HashTable to LinkedHashMap
| omni-cx2x/src/cx2x/xcodeml/xelement/XtypeTable.java | Change HashTable to LinkedHashMap | <ide><path>mni-cx2x/src/cx2x/xcodeml/xelement/XtypeTable.java
<ide> import org.w3c.dom.Node;
<ide> import org.w3c.dom.NodeList;
<ide> import java.util.Hashtable;
<add>import java.util.LinkedHashMap;
<add>import java.util.Map;
<ide> import java.util.Random;
<ide>
<ide> /**
<ide> private static final int HASH_LENGTH = 12;
<ide> private static final String FCT_HASH_PREFIX = "F";
<ide>
<del> private Hashtable<String, Xtype> _table;
<add> private Map<String, Xtype> _table;
<ide>
<ide> /**
<ide> * Xelement standard ctor. Pass the base element to the base class and read
<ide> */
<ide> public XtypeTable(Element baseElement){
<ide> super(baseElement);
<del> _table = new Hashtable<>();
<add> _table = new LinkedHashMap<>();
<ide> readTable();
<ide> }
<ide>
<ide> * Read the type table.
<ide> */
<ide> private void readTable(){
<add> // TODO read all element in one loop.
<ide> // Read basic type
<ide> NodeList basicTypes = baseElement.getElementsByTagName(XelementName.BASIC_TYPE);
<ide> for (int i = 0; i < basicTypes.getLength(); i++) { |
|
Java | apache-2.0 | a15e1c9814c467742c06c194d6f3b44b5b0f1730 | 0 | oasisfeng/deagle | package com.oasisfeng.android.databinding.recyclerview;
import android.databinding.BindingAdapter;
import android.databinding.ObservableList;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
/**
* Binding adapters for RecyclerView.
*
* Created by Oasis on 2016/2/14.
*/
@SuppressWarnings("unused")
public class RecyclerViewBindingAdapter {
@BindingAdapter({"items", "item_binder", "item_layout_selector"})
public static <T> void setItemsAndBinder(final RecyclerView recycler_view, final ObservableList<T> items, final ItemBinder<T> binder, final LayoutSelector<T> layout_selector) {
recycler_view.setAdapter(new BindingRecyclerViewAdapter<>(items, binder, layout_selector));
}
@BindingAdapter({"items", "item_binder", "item_layout"})
public static <T> void setItemsAndBinder(final RecyclerView recycler_view, final ObservableList<T> items, final ItemBinder<T> binder, final @LayoutRes int item_layout) {
recycler_view.setAdapter(new BindingRecyclerViewAdapter<>(items, binder, new LayoutSelector<T>() {
@Override public int getLayoutRes(final T model) { return item_layout; }
}));
}
@BindingAdapter({"item_touch"})
public static void setItemTouchHelper(final RecyclerView view, final ItemTouchHelper helper) {
for (int i = 0;; i ++) try {
final RecyclerView.ItemDecoration decoration = view.getItemDecorationAt(i);
if (decoration == null) break; // Null is returned on RecyclerView library 27+
if (decoration == helper) return;
} catch (final IndexOutOfBoundsException ignored) { break; } // IndexOutOfBoundsException is thrown on RecyclerView library prior to 27.
helper.attachToRecyclerView(view);
}
}
| library/src/main/java/com/oasisfeng/android/databinding/recyclerview/RecyclerViewBindingAdapter.java | package com.oasisfeng.android.databinding.recyclerview;
import android.databinding.BindingAdapter;
import android.databinding.ObservableList;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
/**
* Binding adapters for RecyclerView.
*
* Created by Oasis on 2016/2/14.
*/
@SuppressWarnings("unused")
public class RecyclerViewBindingAdapter {
@BindingAdapter({"items", "item_binder", "item_layout_selector"})
public static <T> void setItemsAndBinder(final RecyclerView recycler_view, final ObservableList<T> items, final ItemBinder<T> binder, final LayoutSelector<T> layout_selector) {
recycler_view.setAdapter(new BindingRecyclerViewAdapter<>(items, binder, layout_selector));
}
@BindingAdapter({"items", "item_binder", "item_layout"})
public static <T> void setItemsAndBinder(final RecyclerView recycler_view, final ObservableList<T> items, final ItemBinder<T> binder, final @LayoutRes int item_layout) {
recycler_view.setAdapter(new BindingRecyclerViewAdapter<>(items, binder, new LayoutSelector<T>() {
@Override public int getLayoutRes(final T model) { return item_layout; }
}));
}
}
| ADD: New attribute "item_touch" for RecyclerView to bind ItemTouchHelper.
| library/src/main/java/com/oasisfeng/android/databinding/recyclerview/RecyclerViewBindingAdapter.java | ADD: New attribute "item_touch" for RecyclerView to bind ItemTouchHelper. | <ide><path>ibrary/src/main/java/com/oasisfeng/android/databinding/recyclerview/RecyclerViewBindingAdapter.java
<ide> import android.databinding.ObservableList;
<ide> import android.support.annotation.LayoutRes;
<ide> import android.support.v7.widget.RecyclerView;
<add>import android.support.v7.widget.helper.ItemTouchHelper;
<ide>
<ide> /**
<ide> * Binding adapters for RecyclerView.
<ide> @Override public int getLayoutRes(final T model) { return item_layout; }
<ide> }));
<ide> }
<add>
<add> @BindingAdapter({"item_touch"})
<add> public static void setItemTouchHelper(final RecyclerView view, final ItemTouchHelper helper) {
<add> for (int i = 0;; i ++) try {
<add> final RecyclerView.ItemDecoration decoration = view.getItemDecorationAt(i);
<add> if (decoration == null) break; // Null is returned on RecyclerView library 27+
<add> if (decoration == helper) return;
<add> } catch (final IndexOutOfBoundsException ignored) { break; } // IndexOutOfBoundsException is thrown on RecyclerView library prior to 27.
<add> helper.attachToRecyclerView(view);
<add> }
<ide> } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.