answer stringlengths 17 10.2M |
|---|
package com.jmrapp.terralegion.game.views.ui;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.jmrapp.terralegion.engine.camera.OrthoCamera;
import com.jmrapp.terralegion.engine.input.InputController;
import com.jmrapp.terralegion.engine.input.JoystickControl;
import com.jmrapp.terralegion.engine.utils.Settings;
import com.jmrapp.terralegion.engine.utils.Timer;
import com.jmrapp.terralegion.engine.views.drawables.Drawable;
import com.jmrapp.terralegion.engine.views.drawables.ResourceManager;
import com.jmrapp.terralegion.engine.views.drawables.ui.PictureButton;
import com.jmrapp.terralegion.engine.views.screens.ScreenManager;
import com.jmrapp.terralegion.game.item.ItemStack;
import com.jmrapp.terralegion.game.item.impl.BlockItem;
import com.jmrapp.terralegion.game.item.impl.CombatItem;
import com.jmrapp.terralegion.game.item.impl.ToolItem;
import com.jmrapp.terralegion.game.utils.Vector2Factory;
import com.jmrapp.terralegion.game.views.screen.GameScreen;
import com.jmrapp.terralegion.game.views.screen.InventoryScreen;
import com.jmrapp.terralegion.game.world.DayManager;
import com.jmrapp.terralegion.game.world.World;
import com.jmrapp.terralegion.game.world.block.BlockManager;
import com.jmrapp.terralegion.game.world.block.BlockType;
import com.jmrapp.terralegion.game.world.chunk.Chunk;
import com.jmrapp.terralegion.game.world.chunk.ChunkManager;
import com.jmrapp.terralegion.game.world.entity.LivingEntity;
public class GameHud {
private static final Drawable blankTile = ResourceManager.getInstance().getDrawable("blankTile");
private static final Texture heartTexture = ResourceManager.getInstance().getTexture("heart");
private JoystickControl moveControl, actionControl;
private Stage stage;
private SpriteBatch stageSb, sb;
private OrthoCamera camera;
private World world;
private Texture bg;
private InventoryBox[] inventoryBoxes = new InventoryBox[5];
private PictureButton inventoryBtn = new PictureButton(ResourceManager.getInstance().getDrawable("inventoryBtn"), 20 + (InventoryBox.bg.getWidth() + 7) * 5, Settings.getHeight() - InventoryBox.bg.getHeight() - 10);
private float lastBlockPlace;
private Vector2 highlightedBlockPosition = Vector2Factory.instance.getVector2();
private Rectangle collisionTestRect = new Rectangle();
private GameScreen gameScreen;
public GameHud(GameScreen gameScreen, World world) {
this.gameScreen = gameScreen;
this.world = world;
stageSb = new SpriteBatch();
sb = new SpriteBatch();
stage = new Stage(new StretchViewport(Settings.getWidth(), Settings.getHeight()), stageSb);
moveControl = new JoystickControl(ResourceManager.getInstance().getTexture("joystickBg"), ResourceManager.getInstance().getTexture("joystickKnob"), 10, 20, 20, 200, 200);
actionControl = new JoystickControl(ResourceManager.getInstance().getTexture("joystickBg"), ResourceManager.getInstance().getTexture("joystickKnob"), 10, 550, 20, 200, 200);
stage.addActor(moveControl.getTouchpad());
stage.addActor(actionControl.getTouchpad());
stage.act(Gdx.graphics.getDeltaTime());
camera = new OrthoCamera();
InputController.getInstance().addInputProcessor(stage);
bg = ResourceManager.getInstance().getTexture("bg");
for (int i = 0; i < inventoryBoxes.length; i++) {
inventoryBoxes[i] = new InventoryBox(world.getPlayer().getInventory().getItemStack(i, 0), 20 + (i * (InventoryBox.bg.getWidth() + 7)), Settings.getHeight() - InventoryBox.bg.getHeight() - 10);
}
inventoryBoxes[0].setSelected(true);
}
public void update(OrthoCamera gameCamera) {
camera.update();
stage.act(Gdx.graphics.getDeltaTime());
if (world.getPlayer().getInventory().wasChanged()) {
updateInventoryBoxes();
world.getPlayer().getInventory().resetChangedFlag();
}
if (moveControl.getTouchpad().isTouched()) {
if (moveControl.getTouchpad().getKnobPercentY() > .5f && world.getPlayer().canJump())
world.getPlayer().jump();
world.getPlayer().addVelocity(moveControl.getTouchpad().getKnobPercentX() * world.getPlayer().getSpeed(), 0);
} else if (actionControl.getTouchpad().isTouched()) {
ItemStack selectedItemStack = getSelectedItemStack();
if (selectedItemStack != null) {
if (selectedItemStack.getItem() instanceof ToolItem) {
if (selectedItemStack.getItem() instanceof CombatItem) {
LivingEntity entity = findLivingEntity((ToolItem) selectedItemStack.getItem()); //look for entities we can attack
if (entity != null) { //if we found an entity to attack, attack it
entity.damage(((CombatItem) selectedItemStack.getItem()).getDamage());
world.getPlayer().usedTool();
}
} else {
breakBlock((ToolItem) selectedItemStack.getItem());
}
} else if (selectedItemStack.getItem() instanceof BlockItem) {
placeBlock((BlockItem) selectedItemStack.getItem());
}
}
} else if (Gdx.input.isTouched(0)) {
float touchX = camera.unprojectXCoordinate(Gdx.input.getX(), Gdx.input.getY());
float touchY = camera.unprojectYCoordinate(Gdx.input.getX(), Gdx.input.getY());
for (InventoryBox box : inventoryBoxes) {
if (box.isPressed(touchX, touchY)) {
if (!box.isSelected()) {
unsetSelectedInventoryBox();
box.setSelected(true);
}
}
}
if (inventoryBtn.isPressed(touchX, touchY)) {
ScreenManager.setScreen(new InventoryScreen(gameScreen, world, world.getPlayer().getInventory()));
}
touchX = gameCamera.unprojectXCoordinate(Gdx.input.getX(), Gdx.input.getY());
touchY = gameCamera.unprojectYCoordinate(Gdx.input.getX(), Gdx.input.getY());
ItemStack selectedItemStack = getSelectedItemStack();
Vector2 origin = Vector2Factory.instance.getVector2(world.getPlayer().getX(), world.getPlayer().getY());
Vector2 position = Vector2Factory.instance.getVector2(touchX, touchY);
if (selectedItemStack != null) {
if (selectedItemStack.getItem() instanceof ToolItem) {
ToolItem tool = (ToolItem) selectedItemStack.getItem();
if (position.dst(origin) <= tool.getReach()) {
BlockType type = world.getChunkManager().getBlockFromPos(touchX, touchY);
if (tool.canDamageBlock(type)) {
highlightedBlockPosition.set(((int)touchX / ChunkManager.TILE_SIZE) * ChunkManager.TILE_SIZE, ((int)touchY / ChunkManager.TILE_SIZE) * ChunkManager.TILE_SIZE);
if (world.getPlayer().canUseTool(tool))
if (world.getChunkManager().damageBlock(touchX, touchY, tool.getPower()))
world.getPlayer().usedTool();
}
}
} else if (selectedItemStack.getItem() instanceof BlockItem) {
if (position.dst(origin) <= 100) {
BlockType type = world.getChunkManager().getBlockFromPos(touchX, touchY);
if (type == BlockType.AIR) {
highlightedBlockPosition.set(((int)touchX / ChunkManager.TILE_SIZE) * ChunkManager.TILE_SIZE, ((int)touchY / ChunkManager.TILE_SIZE) * ChunkManager.TILE_SIZE);
if (Timer.getGameTimeElapsed() - lastBlockPlace > .75f) {
if (world.getChunkManager().getBlockFromPos(touchX, touchY) == BlockType.AIR) {
collisionTestRect.set(highlightedBlockPosition.x, highlightedBlockPosition.y, ChunkManager.TILE_SIZE, ChunkManager.TILE_SIZE);
if (!world.getPlayer().getBounds().overlaps(collisionTestRect) || !BlockManager.getBlock(((BlockItem) selectedItemStack.getItem()).getBlockType()).collides()) {
world.getChunkManager().setBlock(((BlockItem) selectedItemStack.getItem()).getBlockType(), touchX, touchY, true);
world.getPlayer().getInventory().removeItemStack(selectedItemStack.getItem(), 1);
}
}
}
}
}
}
}
Vector2Factory.instance.destroy(origin);
Vector2Factory.instance.destroy(position);
} else {
highlightedBlockPosition.set(-100, -100);
}
}
public void render(OrthoCamera gameCamera) {
if (highlightedBlockPosition.x != -100 && highlightedBlockPosition.y != -100) { //means we are highlighting a block and trying to break it
sb.setProjectionMatrix(gameCamera.combined);
sb.begin();
blankTile.render(sb, highlightedBlockPosition.x, highlightedBlockPosition.y);
sb.end();
}
sb.setProjectionMatrix(camera.combined);
sb.begin();
ResourceManager.getInstance().getFont("font").draw(sb, "FPS: " + Gdx.graphics.getFramesPerSecond(), Settings.getWidth() - 150, Settings.getHeight() - 60);
Chunk chunk = world.getChunkManager().getLoadedChunks()[1][1];
if (chunk != null) {
ResourceManager.getInstance().getFont("font").draw(sb, "Chunk: " + chunk.getStartX() + ", " + chunk.getStartY(), Settings.getWidth() - 150, Settings.getHeight() - 80);
}
int hearts = (int) world.getPlayer().getHealth() / 20;
for (int i = 0; i < hearts; i++) {
sb.draw(heartTexture, Settings.getWidth() - 75 - (i * (heartTexture.getWidth() + 5)), Settings.getHeight() - heartTexture.getHeight() - 15);
}
for (InventoryBox box : inventoryBoxes)
box.render(sb);
inventoryBtn.render(sb);
sb.end();
stage.draw();
}
public void renderBackground() {
sb.setProjectionMatrix(camera.combined);
sb.begin();
float value = DayManager.getInstance().getWorldLightValue();
sb.setColor(value, value, value, 1);
sb.draw(bg, 0, 0);
sb.setColor(Color.WHITE);
sb.end();
}
private LivingEntity findLivingEntity(ToolItem item) {
if (world.getPlayer().canUseTool(item)) {
Vector2 direction = Vector2Factory.instance.getVector2(actionControl.getTouchpad().getKnobPercentX(), actionControl.getTouchpad().getKnobPercentY()).nor(); //Get vector direction of the know
Chunk chunk = world.getChunkManager().getChunkFromPos(world.getPlayer().getX(), world.getPlayer().getY());
//The entities found array is sorted by distance to player from least to greatest
for (LivingEntity entity : chunk.findLivingEntitiesInRange(world.getPlayer().getX(), world.getPlayer().getY(), item.getReach())) {
if (direction.x < 0) {
if (entity.getX() < world.getPlayer().getX()) {
return entity;
}
} else if (direction.x >= 0) {
if (entity.getX() >= world.getPlayer().getX()) {
return entity;
}
}
}
}
return null;
}
private void breakBlock(ToolItem tool) {
Vector2 direction = Vector2Factory.instance.getVector2(actionControl.getTouchpad().getKnobPercentX(), actionControl.getTouchpad().getKnobPercentY()).nor(); //Get vector direction of the know
Vector2 foundBlockPos = world.getChunkManager().findBlock(tool, world.getPlayer().getX() + ChunkManager.TILE_SIZE / 2, world.getPlayer().getY() + ChunkManager.TILE_SIZE / 2, direction, tool.getReach()); //Find a block
if (direction.x != 0 && direction.y != 0) {
if (foundBlockPos != null) {
float px = ChunkManager.tileToPixelPosition((int) foundBlockPos.x);
float py = ChunkManager.tileToPixelPosition((int) foundBlockPos.y);
highlightedBlockPosition.set(px, py);
}
if (world.getPlayer().canUseTool(tool)) {
if (foundBlockPos != null) { //if block found within reach
if (world.getChunkManager().damageBlock((int) foundBlockPos.x, (int) foundBlockPos.y, tool.getPower())) { //Damage the block
world.getPlayer().usedTool();
}
}
}
}
Vector2Factory.instance.destroy(foundBlockPos);
Vector2Factory.instance.destroy(direction);
}
private void placeBlock(BlockItem block) {
Vector2 direction = Vector2Factory.instance.getVector2(actionControl.getTouchpad().getKnobPercentX(), actionControl.getTouchpad().getKnobPercentY()).nor(); //Get vector direction of the know
Vector2 foundBlockPos = world.getChunkManager().findFarthestAirBlock(world.getPlayer().getX() + ChunkManager.TILE_SIZE / 2, world.getPlayer().getY() + ChunkManager.TILE_SIZE / 2, direction, 100); //Find an air block
if (direction.x != 0 && direction.y != 0) {
if (foundBlockPos != null) { //if we found an air block
float px = ChunkManager.tileToPixelPosition((int) foundBlockPos.x);
float py = ChunkManager.tileToPixelPosition((int) foundBlockPos.y);
highlightedBlockPosition.set(px, py);
}
if (foundBlockPos != null) { //if block found within reach
if (Timer.getGameTimeElapsed() - lastBlockPlace > .75f) {
collisionTestRect.set(highlightedBlockPosition.x, highlightedBlockPosition.y, ChunkManager.TILE_SIZE, ChunkManager.TILE_SIZE);
if (!world.getPlayer().getBounds().overlaps(collisionTestRect)) {
world.getChunkManager().setBlock(block.getBlockType(), (int) foundBlockPos.x, (int) foundBlockPos.y, true);
world.getPlayer().getInventory().removeItemStack(block, 1);
lastBlockPlace = Timer.getGameTimeElapsed();
}
}
}
}
Vector2Factory.instance.destroy(foundBlockPos);
Vector2Factory.instance.destroy(direction);
}
public void updateInventoryBoxes() {
for (int i = 0; i < inventoryBoxes.length; i++) {
inventoryBoxes[i].setItemStack(world.getPlayer().getInventory().getItemStack(i, 0));
}
}
private void unsetSelectedInventoryBox() {
for (InventoryBox b : inventoryBoxes) {
if (b.isSelected()) {
b.setSelected(false);
break;
}
}
}
public ItemStack getSelectedItemStack() {
for (InventoryBox box : inventoryBoxes) {
if (box.isSelected()) {
return box.getItemStack();
}
}
return null;
}
public void resume() {
InputController.getInstance().addInputProcessor(stage);
}
public void dispose() {
InputController.getInstance().removeInputProcessor(stage);
}
public void resize(int width, int height) {
camera.resize();
}
} |
package org.cache2k.impl.threading;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author Jens Wilke; created: 2014-06-03
*/
public class Futures {
/**
* A container for futures which waits for all futures to finish.
* Futures to wait for can be added with {@link #add(java.util.concurrent.Future)}
* or the constructor. Waiting for all futures to finish is done
* via {@link #get()}.
*
* <p/>The get method call will throw Exceptions from the added futures.
*/
public static class WaitForAllFuture<V> implements Future<V> {
List<Future<V>> futureList = new LinkedList<>();
public WaitForAllFuture(Future<V> _top) {
add(_top);
}
@SafeVarargs
public WaitForAllFuture(final Future<V>... _top) {
for (Future<V> f : _top) { add(f); }
}
/**
* Add a new future to the list for Futures we should wait for.
*/
public synchronized void add(Future<V> f) {
if (f == null) { return; }
futureList.add(f);
}
/**
* Send cancel to all futures that are not yet cancelled. Returns
* true if every future is in cancelled state.
*/
@Override
public synchronized boolean cancel(boolean mayInterruptIfRunning) {
if (futureList.size() == 0) {
return false;
}
boolean _flag = true;
for (Future<V> f : futureList) {
if (!f.isCancelled()) {
f.cancel(mayInterruptIfRunning);
_flag &= f.isCancelled();
}
}
return _flag;
}
/**
* Unsupported, it is not possible to implement useful semantics.
*/
@Override
public boolean isCancelled() {
throw new UnsupportedOperationException();
}
/**
* True, if every future is done or no future is contained.
*
* <p/>The list of futures is not touched, since an exception
* may be thrown via get.
*/
@Override
public synchronized boolean isDone() {
boolean _flag = true;
for (Future<V> f : futureList) {
_flag &= f.isDone();
}
return _flag;
}
/**
* Wait until everything is finished. It may happen that a new future during
* this method waits for finishing another one. If this happens, we wait
* for that task also.
*
* <p/>All get methods of the futures are executed to probe for possible
* exceptions. Futures completed without exceptions, will be removed
* for the list.
*
* <p/>Implementation is a bit tricky. We need to call a potential stalling
* get outside the synchronized block, since new futures may come in in parallel.
*/
@Override
public V get() throws InterruptedException, ExecutionException {
for (;;) {
Future<V> _needsGet = null;
synchronized (this) {
Iterator<Future<V>> it = futureList.iterator();
while (it.hasNext()){
Future<V> f = it.next();
if (!f.isDone()) {
_needsGet = f;
break;
}
f.get();
it.remove();
}
}
if (_needsGet != null) {
_needsGet.get();
continue;
}
return null;
}
}
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
long _maxTime = System.currentTimeMillis() + unit.toMillis(timeout);
if (_maxTime < 0) {
return get();
}
for (;;) {
Future<V> _needsGet = null;
synchronized (this) {
Iterator<Future<V>> it = futureList.iterator();
while (it.hasNext()){
Future<V> f = it.next();
if (!f.isDone()) {
_needsGet = f;
break;
}
f.get();
it.remove();
}
}
if (_needsGet != null) {
long now = System.currentTimeMillis();
long _waitTime = _maxTime - now;
if (_waitTime <= 0) {
throw new TimeoutException();
}
_needsGet.get(_maxTime - now, TimeUnit.MILLISECONDS);
continue;
}
return null;
}
}
}
public static class FinishedFuture<V> implements Future<V> {
V result;
public FinishedFuture() {
}
public FinishedFuture(V result) {
this.result = result;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public V get() {
return result;
}
@Override
public V get(long timeout, TimeUnit unit) {
return result;
}
}
public static class ExceptionFuture<V> implements Future<V> {
private Throwable exception;
public ExceptionFuture(Throwable exception) {
this.exception = exception;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public V get() throws ExecutionException {
throw new ExecutionException(exception);
}
@Override
public V get(long timeout, TimeUnit unit) throws ExecutionException {
throw new ExecutionException(exception);
}
}
public static abstract class BusyWaitFuture<V> implements Future<V> {
private int spinMillis = 123;
private V result = null;
protected BusyWaitFuture() { }
protected BusyWaitFuture(V _defaultResult) {
this.result = _defaultResult;
}
protected BusyWaitFuture(int spinMillis, V _defaultResult) {
this.spinMillis = spinMillis;
this.result = _defaultResult;
}
protected V getResult() { return result; }
@Override
public boolean cancel(boolean mayInterruptIfRunning) { return false; }
@Override
public boolean isCancelled() { return false; }
@Override
public abstract boolean isDone();
/** Just busy wait for running fetches. We have no notification for this. */
@Override
public V get() throws InterruptedException, ExecutionException {
while (!isDone()) { Thread.sleep(spinMillis); }
return getResult();
}
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
long _maxMillis = unit.toMillis(timeout) + System.currentTimeMillis();
if (_maxMillis < 0) { return get(); }
while (!isDone() && System.currentTimeMillis() < _maxMillis) { Thread.sleep(spinMillis); }
if (!isDone()) { throw new TimeoutException(); }
return getResult();
}
}
} |
package org.mskcc.cbio.portal.util;
import org.mskcc.cbio.cgds.dao.DaoException;
import org.mskcc.cbio.portal.servlet.QueryBuilder;
import org.mskcc.cbio.portal.servlet.ServletXssUtil;
import org.owasp.validator.html.PolicyException;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.Enumeration;
/**
* URL Utility Class.
*/
public class UrlUtil {
/**
* Gets Current URL.
*
* @param request HttpServletRequest.
* @return Current URL
*/
public static String getCurrentUrl (HttpServletRequest request) {
Enumeration paramEnum = request.getParameterNames();
StringBuffer buf = new StringBuffer(request.getAttribute
(QueryBuilder.ATTRIBUTE_URL_BEFORE_FORWARDING) + "?");
while (paramEnum.hasMoreElements()) {
String paramName = (String) paramEnum.nextElement();
String values[] = request.getParameterValues(paramName);
if (values != null && values.length >0) {
for (int i=0; i<values.length; i++) {
String currentValue = values[i];
if (paramName.equals(QueryBuilder.GENE_LIST)
|| paramName.equals(QueryBuilder.CASE_IDS)
&& currentValue != null) {
currentValue = URLEncoder.encode(currentValue);
}
buf.append (paramName + "=" + currentValue + "&");
}
}
}
return buf.toString();
}
/**
* Gets current URL by replacing the case_ids parameter by
* the case_ids_key parameter.
*
* @param request HttpServletRequest.
* @return current URL with case_ids replaced by case_ids_key
* @throws DaoException
*/
public static String getUrlWithCaseIdsKey(HttpServletRequest request)
throws DaoException
{
Enumeration paramEnum = request.getParameterNames();
StringBuffer buf = new StringBuffer(request.getAttribute
(QueryBuilder.ATTRIBUTE_URL_BEFORE_FORWARDING) + "?");
ServletXssUtil xssUtil = null;
try {
xssUtil = ServletXssUtil.getInstance();
} catch (PolicyException e) {
//logger.error("Could not instantiate XSS Util: " + e.toString());
}
while (paramEnum.hasMoreElements())
{
String paramName = (String) paramEnum.nextElement();
String values[] = request.getParameterValues(paramName);
if (values != null && values.length >0)
{
for (int i=0; i<values.length; i++)
{
String currentValue = values[i];
if (paramName.equals(QueryBuilder.GENE_LIST)
&& currentValue != null)
{
currentValue = URLEncoder.encode(currentValue);
}
else if (paramName.equals(QueryBuilder.CASE_IDS)
&& currentValue != null)
{
paramName = QueryBuilder.CASE_IDS_KEY;
// first try to get case_ids_key attribute from the request
if (request.getAttribute(QueryBuilder.CASE_IDS_KEY) != null)
{
currentValue = (String)request.getAttribute(QueryBuilder.CASE_IDS_KEY);
}
// if no request attribute found, then use the utility function
else
{
currentValue = CaseSetUtil.shortenCaseIds(currentValue);
}
}
if (xssUtil != null)
{
currentValue = xssUtil.getCleanerInput(currentValue);
}
buf.append(paramName + "=" + currentValue + "&");
}
}
}
return buf.toString();
}
} |
package org.mwg.core.task;
import org.mwg.DeferCounter;
import org.mwg.core.utility.GenericIterable;
import org.mwg.task.Task;
import org.mwg.task.TaskAction;
import org.mwg.task.TaskContext;
//TODO implement a real multi-thread version
class ActionForeachPar implements TaskAction {
private final Task _subTask;
ActionForeachPar(final Task p_subTask) {
_subTask = p_subTask;
}
@Override
public void eval(final TaskContext context) {
final Object previousResult = context.result();
final GenericIterable genericIterable = new GenericIterable(previousResult);
int plainEstimation = genericIterable.estimate();
if (plainEstimation == -1) {
plainEstimation = 16;
}
Object[] results = new Object[plainEstimation];
int index = 0;
Object loop = genericIterable.next();
while (loop != null) {
final DeferCounter waiter = context.graph().newCounter(1);
_subTask.executeWith(context.graph(), context, loop, waiter.wrap());
if (index >= results.length) {
Object[] doubled_res = new Object[results.length * 2];
System.arraycopy(results, 0, doubled_res, 0, results.length);
results = doubled_res;
}
results[index] = waiter.waitResult();
index++;
context.cleanObj(loop);
loop = genericIterable.next();
}
if (index != results.length) {
Object[] shrinked_res = new Object[index];
System.arraycopy(results, 0, shrinked_res, 0, index);
results = shrinked_res;
}
context.cleanObj(previousResult);
context.setUnsafeResult(results);
}
} |
// Triple Play - utilities for use in PlayN-based games
package tripleplay.ui.bgs;
import pythagoras.f.IDimension;
import playn.core.Image;
import playn.core.ImmediateLayer;
import playn.core.PlayN;
import playn.core.Surface;
import tripleplay.ui.Background;
/**
* A background constructed by scaling the parts of a source image to fit the target width and
* height. First the source image is divided into a 3x3 grid. Of the resulting 9 parts, the corners
* are drawn without scaling to the destination, the top and bottom center pieces are copied with
* horizontal scaling, the left and right center pieces are copied with vertical scaling, and the
* center piece is copied with both horizontal and vertical scaling.
*
* <p>By using {@link #xaxis} and {@link #yaxis}, the partitioning of the image can be
* controlled directly. For example, if the horizontal middle of an image is a single pixel:
* <pre>{@code
* Scale9Background bkg = ...;
* bkg.xaxis.resize(1, 1);
* }</pre></p>
*/
public class Scale9Background extends Background
{
/** A horizontal or vertical axis, broken up into 3 chunks. */
public static class Axis3
{
/** Creates a new axis equally splitting the given length. */
public Axis3 (float length) {
float d = length / 3;
_lengths = new float[] {d, length - 2 * d, d};
_offsets = new float[] {0, _lengths[0], _lengths[0] + _lengths[1]};
}
/** Creates a new axis with the given total length and 0th and 2nd lengths copied from a
* source axis. */
public Axis3 (float length, Axis3 src) {
_lengths = new float[] {src.size(0), length - src.size(0) - src.size(2), src.size(2)};
_offsets = new float[] {0, _lengths[0], _lengths[0] + _lengths[1]};
}
/** Returns the coordinate of the given chunk, 0 - 2. */
public float coord (int idx) {
return _offsets[idx];
}
/** Returns the size of the given chunk, 0 - 2. */
public float size (int idx) {
return _lengths[idx];
}
/** Sets the size and location of the given chunk, 0 - 2. */
public Axis3 set (int idx, float coord, float size) {
_offsets[idx] = coord;
_lengths[idx] = size;
return this;
}
/** Sets the size of the given chunk, shifting neighbors. */
public Axis3 resize (int idx, float size) {
float excess = _lengths[idx] - size;
_lengths[idx] = size;
switch (idx) {
case 0:
_offsets[1] -= excess;
_lengths[1] += excess;
break;
case 1:
float half = excess * .5f;
_lengths[0] += half;
_lengths[2] += half;
_offsets[1] += half;
_offsets[2] -= half;
break;
case 2:
_offsets[2] -= excess;
_lengths[1] += excess;
break;
}
return this;
}
/** The positions of the 3 chunks. */
protected final float[] _offsets;
/** The lengths of the 3 chunks. */
protected final float[] _lengths;
}
/** The axes of our source image. */
public final Axis3 xaxis, yaxis;
/** Creates a new background using the given image. The subdivision of the image into a 3x3
* grid is automatic.
*
* <p>NOTE: the image must be preloaded since we need to determine the stretching factor.
* If this cannot be arranged using the application resource strategy, callers may consider
* setting the background style from the images callback.</p>
*/
public Scale9Background (Image image) {
if (!image.isReady()) {
// complain about this, we don't support asynch images
PlayN.log().warn("Scale9 image not preloaded: " + image);
}
_image = image;
xaxis = new Axis3(image.width());
yaxis = new Axis3(image.height());
}
/**
* Will ensure that the Axis3 passed in does not exceed the length given. An equal chunk will
* be removed from the outer chunks if it is too long. The given Axis3 is modified and returned.
*/
public static Axis3 clamp (Axis3 axis, float length) {
float left = axis.size(0);
float middle = axis.size(1);
float right = axis.size(2);
if (left + middle + right > length && middle > 0 && left + right < length) {
// the special case where for some reason the total is too wide, but the middle is non
// zero, and it can absorb the extra all on its own.
axis.set(1, left, length - left - right);
axis.set(2, length - right, right);
} else if (left + right > length) {
// eat equal chunks out of each end so that we don't end up overlapping
float remove = (left + right - length) / 2;
axis.set(0, 0, left - remove);
axis.set(1, left - remove, 0);
axis.set(2, left - remove, right - remove);
}
return axis;
}
@Override
protected Instance instantiate (final IDimension size) {
return new LayerInstance(size, new ImmediateLayer.Renderer() {
// The axes of our destination surface.
Axis3 dx = clamp(new Axis3(size.width(), xaxis), size.width());
Axis3 dy = clamp(new Axis3(size.height(), yaxis), size.height());
public void render (Surface surf) {
surf.save();
if (alpha != null) surf.setAlpha(alpha);
// issue the 9 draw calls
for (int yy = 0; yy < 3; ++yy) for (int xx = 0; xx < 3; ++xx) {
drawPart(surf, xx, yy);
}
if (alpha != null) surf.setAlpha(1); // alpha is not part of save/restore
surf.restore();
}
protected void drawPart (Surface surf, int x, int y) {
if (dx.size(x) ==0 || dy.size(y) == 0) return;
surf.drawImage(_image,
dx.coord(x), dy.coord(y), dx.size(x), dy.size(y),
xaxis.coord(x), yaxis.coord(y), xaxis.size(x), yaxis.size(y));
}
});
}
protected Image _image;
} |
package org.javarosa.core.util;
import java.util.Vector;
/**
*
* Only use for J2ME Compatible Vectors
*
* A SizeBoundVector that enforces that all member items be unique. You must
* implement the .equals() method of class E
*
* @author wspride
*
*/
public class SizeBoundUniqueVector<E> extends SizeBoundVector<E> {
public SizeBoundUniqueVector(int sizeLimit) {
super(sizeLimit);
}
/* (non-Javadoc)
* @see java.util.Vector#addElement(java.lang.Object)
*/
public synchronized void addElement(E obj) {
if(this.size() == limit) {
additional++;
return;
}
else if(this.contains(obj)){
return;
}
else {
super.addElement(obj);
}
}
public synchronized boolean addElementForResult(E obj) {
if(this.size() == limit) {
additional++;
return true;
}
else if(this.contains(obj)){
return false;
}
else {
super.addElement(obj);
return true;
}
}
} |
package org.klomp.snark;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.klomp.snark.bencode.BDecoder;
import org.klomp.snark.bencode.BEValue;
import org.klomp.snark.bencode.InvalidBEncodingException;
/**
* The data structure for the tracker response.
* Handles both traditional and compact formats.
* Compact format 1 - a list of hashes - early format for testing
* Compact format 2 - One big string of concatenated hashes - official format
*/
public class TrackerInfo
{
private final String failure_reason;
private final int interval;
private final Set<Peer> peers;
private int complete;
private int incomplete;
public TrackerInfo(InputStream in, byte[] my_id, MetaInfo metainfo)
throws IOException
{
this(new BDecoder(in), my_id, metainfo);
}
public TrackerInfo(BDecoder be, byte[] my_id, MetaInfo metainfo)
throws IOException
{
this(be.bdecodeMap().getMap(), my_id, metainfo);
}
public TrackerInfo(Map m, byte[] my_id, MetaInfo metainfo)
throws IOException
{
BEValue reason = (BEValue)m.get("failure reason");
if (reason != null)
{
failure_reason = reason.getString();
interval = -1;
peers = null;
}
else
{
failure_reason = null;
BEValue beInterval = (BEValue)m.get("interval");
if (beInterval == null)
throw new InvalidBEncodingException("No interval given");
else
interval = beInterval.getInt();
BEValue bePeers = (BEValue)m.get("peers");
if (bePeers == null) {
peers = Collections.EMPTY_SET;
} else {
Set<Peer> p;
try {
// One big string (the official compact format)
p = getPeers(bePeers.getBytes(), my_id, metainfo);
} catch (InvalidBEncodingException ibe) {
// List of Dictionaries or List of Strings
p = getPeers(bePeers.getList(), my_id, metainfo);
}
peers = p;
}
BEValue bev = (BEValue)m.get("complete");
if (bev != null) try {
complete = bev.getInt();
if (complete < 0)
complete = 0;
} catch (InvalidBEncodingException ibe) {}
bev = (BEValue)m.get("incomplete");
if (bev != null) try {
incomplete = bev.getInt();
if (incomplete < 0)
incomplete = 0;
} catch (InvalidBEncodingException ibe) {}
}
}
/** List of Dictionaries or List of Strings */
private static Set<Peer> getPeers(List<BEValue> l, byte[] my_id, MetaInfo metainfo)
throws IOException
{
Set<Peer> peers = new HashSet(l.size());
for (BEValue bev : l) {
PeerID peerID;
try {
// Case 1 - non-compact - A list of dictionaries (maps)
peerID = new PeerID(bev.getMap());
} catch (InvalidBEncodingException ibe) {
try {
// Case 2 - compact - A list of 32-byte binary strings (hashes)
// This was just for testing and is not the official format
peerID = new PeerID(bev.getBytes());
} catch (InvalidBEncodingException ibe2) {
// don't let one bad entry spoil the whole list
//Snark.debug("Discarding peer from list: " + ibe, Snark.ERROR);
continue;
}
}
peers.add(new Peer(peerID, my_id, metainfo));
}
return peers;
}
private static final int HASH_LENGTH = 32;
/**
* One big string of concatenated 32-byte hashes
* @since 0.8.1
*/
private static Set<Peer> getPeers(byte[] l, byte[] my_id, MetaInfo metainfo)
throws IOException
{
int count = l.length / HASH_LENGTH;
Set<Peer> peers = new HashSet(count);
for (int i = 0; i < count; i++) {
PeerID peerID;
byte[] hash = new byte[HASH_LENGTH];
System.arraycopy(l, i * HASH_LENGTH, hash, 0, HASH_LENGTH);
try {
peerID = new PeerID(hash);
} catch (InvalidBEncodingException ibe) {
// won't happen
continue;
}
peers.add(new Peer(peerID, my_id, metainfo));
}
return peers;
}
public Set<Peer> getPeers()
{
return peers;
}
public int getPeerCount()
{
int pc = peers == null ? 0 : peers.size();
return Math.max(pc, complete + incomplete - 1);
}
public String getFailureReason()
{
return failure_reason;
}
public int getInterval()
{
return interval;
}
@Override
public String toString()
{
if (failure_reason != null)
return "TrackerInfo[FAILED: " + failure_reason + "]";
else
return "TrackerInfo[interval=" + interval
+ (complete > 0 ? (", complete=" + complete) : "" )
+ (incomplete > 0 ? (", incomplete=" + incomplete) : "" )
+ ", peers=" + peers + "]";
}
} |
package org.basex.query.expr;
import static org.basex.query.QueryText.*;
import org.basex.query.*;
import org.basex.query.iter.*;
import org.basex.query.util.list.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.type.*;
import org.basex.query.value.type.SeqType.Occ;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;
public final class List extends Arr {
/** Limit for the size of sequences that are materialized at compile time. */
private static final int MAX_MAT_SIZE = 1 << 20;
/**
* Constructor.
* @param info input info
* @param exprs expressions
*/
public List(final InputInfo info, final Expr... exprs) {
super(info, exprs);
}
@Override
public void checkUp() throws QueryException {
checkAllUp(exprs);
}
@Override
public Expr compile(final QueryContext qc, final VarScope scp) throws QueryException {
final int es = exprs.length;
for(int e = 0; e < es; e++) exprs[e] = exprs[e].compile(qc, scp);
return optimize(qc, scp);
}
@Override
public Expr optimize(final QueryContext qc, final VarScope scp) throws QueryException {
// remove empty sequences
final ExprList el = new ExprList(exprs.length);
for(final Expr e : exprs) {
if(!e.isEmpty()) el.add(e);
}
if(el.size() != exprs.length) {
qc.compInfo(OPTREMOVE, this, Empty.SEQ);
exprs = el.finish();
}
// compute number of results
size = 0;
boolean ne = false;
for(final Expr e : exprs) {
final long c = e.size();
ne |= c > 0 || e.seqType().occ.min == 1;
if(c == -1) {
size = -1;
break;
} else if(size >= 0) {
size += c;
}
}
if(size >= 0) {
if(allAreValues() && size <= MAX_MAT_SIZE) {
Type all = null;
final Value[] vs = new Value[exprs.length];
int c = 0;
for(final Expr e : exprs) {
final Value v = e.value(qc);
if(c == 0) all = v.type;
else if(all != v.type) all = null;
vs[c++] = v;
}
final Value val;
final int s = (int) size;
if(all == AtomType.STR) val = StrSeq.get(vs, s);
else if(all == AtomType.BLN) val = BlnSeq.get(vs, s);
else if(all == AtomType.FLT) val = FltSeq.get(vs, s);
else if(all == AtomType.DBL) val = DblSeq.get(vs, s);
else if(all == AtomType.DEC) val = DecSeq.get(vs, s);
else if(all == AtomType.BYT) val = BytSeq.get(vs, s);
else if(all != null && all.instanceOf(AtomType.ITR)) {
val = IntSeq.get(vs, s, all);
} else {
final ValueBuilder vb = new ValueBuilder();
for(int i = 0; i < c; i++) vb.add(vs[i]);
val = vb.value();
}
return optPre(val, qc);
}
}
if(size == 0) {
seqType = SeqType.EMP;
} else {
final Occ o = size == 1 ? Occ.ONE : size < 0 && !ne ? Occ.ZERO_MORE : Occ.ONE_MORE;
SeqType st = null;
for(final Expr e : exprs) {
final SeqType et = e.seqType();
if(et.occ != Occ.ZERO) st = st == null ? et : st.union(et);
}
seqType = SeqType.get(st == null ? AtomType.ITEM : st.type, o);
}
return this;
}
@Override
public Iter iter(final QueryContext qc) {
return new Iter() {
Iter ir;
int e;
@Override
public Item next() throws QueryException {
while(true) {
if(ir == null) {
if(e == exprs.length) return null;
ir = qc.iter(exprs[e++]);
}
final Item it = ir.next();
if(it != null) return it;
ir = null;
}
}
};
}
@Override
public Value value(final QueryContext qc) throws QueryException {
// most common case
if(exprs.length == 2) return ValueBuilder.concat(qc.value(exprs[0]), qc.value(exprs[1]));
final ValueBuilder vb = new ValueBuilder();
for(final Expr e : exprs) vb.add(qc.value(e));
return vb.value();
}
@Override
public Expr copy(final QueryContext qc, final VarScope scp, final IntObjMap<Var> vs) {
return copyType(new List(info, copyAll(qc, scp, vs, exprs)));
}
@Override
public boolean isVacuous() {
for(final Expr e : exprs) if(!e.isVacuous()) return false;
return true;
}
@Override
public String toString() {
return toString(SEP);
}
} |
package org.bridje.core.vfs;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* An utility class for virtual path management.
*
* The path elements are separated by the / character.
*/
public class Path implements Iterable<Path>
{
private final String[] pathElements;
/**
* Creates a Path object from String
*
* @param path The String object representing the path
*/
public Path(String path)
{
this(createElements(path));
}
private Path(String[] pathElements)
{
if (pathElements == null || pathElements.length == 0)
{
throw new IllegalArgumentException("The specified path is not valid .");
}
this.pathElements = pathElements;
}
/**
* Gets the first element of the path, this is if the path represented by
* this object is "usr/local" this method will return "usr".
*
* @return An String object that represents the first element of the path.
*/
public String getFirstElement()
{
return pathElements[0];
}
/**
* Gets the first element of the path.
*
* This is if the path represented by this object is "usr/local/somefile"
* this method will return "somefile".
*
* @return An String object that represents the first element of the path.
*/
public String getName()
{
return pathElements[pathElements.length - 1];
}
/**
* Creates a new Path object that represents the path to the parent object
* of the current path.
*
* This is if the path represented by this object is "usr/local/somefile"
* this method will return a path object representing "usr/local"
*
* @return The Path object parent of this object, or null if this is the
* last path.
*/
public Path getParent()
{
if (isLast())
{
return null;
}
String[] copyOfRange = Arrays.copyOfRange(pathElements, 0, pathElements.length - 1);
return new Path(copyOfRange);
}
/**
* Creates a new Path object that does not constaint the first element of
* the current path.
*
* This is if the path represented by this object is "usr/local/somefile"
* this method will return a path object representing "/local/somefile"
*
* @return The Path object without the first element of the current path, or
* null if this is the las path.
*/
public Path getNext()
{
if (isLast())
{
return null;
}
String[] copyOfRange = Arrays.copyOfRange(pathElements, 1, pathElements.length);
return new Path(copyOfRange);
}
/**
* Determines if this path has any element left.
*
* If the path represented by this object is a multiple element path like
* "usr/local" the this method will return true.
*
* @return true if this path is a multi element path like "usr/local", false
* if this path is a single element path like "usr".
*/
public boolean hasNext()
{
return !isLast();
}
/**
* Determines if the first element of the path is the dot (.) character
* witch represents the current folder.
*
* @return true if the first element of the path is the dot (.) character
* false otherwise.
*/
public boolean isSelf()
{
return ".".equalsIgnoreCase(pathElements[0]);
}
/**
* Determines if the first element of the path is the (..) identifier witch
* represents the parent folder.
*
* @return true if the first element of the path is the (..) identifier
* false otherwise.
*/
public boolean isParent()
{
return "..".equalsIgnoreCase(pathElements[0]);
}
/**
* Determines if this path has is the last path.
*
* If the path represented by this object is a single element path like
* "usr" the this method will return true.
*
* @return true if this path is a single element path like "usr", false if
* this path is a multiple element path like "usr/local".
*/
public boolean isLast()
{
return (pathElements.length == 1);
}
/**
* This methos creates a new path object that does not contains the (.) and
* (..) identifiers.
*
* If the path represented by this element is "usr/./local/../etc" this
* element will return "usr/etc".
*
* @return A new Path object representing the canonical path of this object.
*/
public Path getCanonicalPath()
{
List<String> str = new LinkedList<>();
for (String pe : pathElements)
{
if (pe.equalsIgnoreCase(".."))
{
if (str.isEmpty())
{
return null;
}
else
{
str.remove(str.size() - 1);
}
}
else if (!pe.equalsIgnoreCase("."))
{
str.add(pe);
}
}
if (str.isEmpty())
{
return null;
}
String[] els = new String[str.size()];
return new Path(str.toArray(els));
}
/**
* Gets a string representation of the current path.
*
* @return The String object representing the current path.
*/
@Override
public String toString()
{
return toString("/");
}
/**
* Gets a string representation of the current path, separated by the
* pathSep parameter.
*
* @param pathSep The path separator to be used.
* @return The String object representing the current path.
*/
public String toString(String pathSep)
{
return String.join(pathSep, pathElements);
}
public Path join(Path path)
{
String[] newElements = new String[pathElements.length + path.pathElements.length];
System.arraycopy(pathElements, 0, newElements, 0, pathElements.length);
System.arraycopy(path.pathElements, 0, newElements, pathElements.length, path.pathElements.length);
return new Path(newElements);
}
public Path join(String path)
{
return join(new Path(path));
}
@Override
public Iterator<Path> iterator()
{
return new Iterator<Path>()
{
private int currentIndex = 0;
@Override
public boolean hasNext()
{
return (currentIndex < pathElements.length);
}
@Override
public Path next()
{
String[] copyOfRange = Arrays.copyOfRange(pathElements, 0, currentIndex + 1);
currentIndex++;
return new Path(copyOfRange);
}
};
}
private static String[] createElements(String path)
{
if (path == null || path.trim().isEmpty())
{
throw new IllegalArgumentException("The specified path is not valid.");
}
String newPath = path;
String toReplace = "\\";
while (newPath.contains(toReplace))
{
newPath = newPath.replace(toReplace, "/");
}
if (path.startsWith("/"))
{
newPath = newPath.substring(1);
}
if (newPath.endsWith("/"))
{
newPath = newPath.substring(0, newPath.length() - 1);
}
if (newPath.trim().isEmpty())
{
throw new IllegalArgumentException("The specified path is not valid .");
}
String[] arr = newPath.trim().split("/");
return arr;
}
@Override
public int hashCode()
{
return toString().hashCode();
}
@Override
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Path other = (Path) obj;
return toString().equals(other.toString());
}
} |
package ucar.unidata.io.s3;
import static com.google.common.truth.Truth.assertThat;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import software.amazon.awssdk.regions.Region;
import ucar.ma2.Array;
import ucar.ma2.InvalidRangeException;
import ucar.ma2.Section;
import ucar.nc2.Dimension;
import ucar.nc2.NetcdfFile;
import ucar.nc2.NetcdfFiles;
import ucar.nc2.Variable;
import ucar.nc2.constants.CF;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.dataset.NetcdfDatasets;
import ucar.unidata.util.test.category.NeedsExternalResource;
@Category(NeedsExternalResource.class)
public class TestS3Read {
@Test
public void testFullS3ReadNetcdfFile() throws IOException {
String region = Region.US_EAST_1.toString();
String bucket = "noaa-goes16";
String key =
"ABI-L1b-RadC/2019/363/21/OR_ABI-L1b-RadC-M6C16_G16_s20193632101189_e20193632103574_c20193632104070.nc";
String s3uri = "s3://" + bucket + "/" + key;
System.setProperty("aws.region", region);
try (NetcdfFile ncfile = NetcdfFiles.open(s3uri)) {
Dimension x = ncfile.findDimension("x");
Dimension y = ncfile.findDimension("y");
assertThat(x).isNotNull();
assertThat(y).isNotNull();
Variable radiance = ncfile.findVariable("Rad");
Assert.assertNotNull(radiance);
// read full array
Array array = radiance.read();
assertThat(array.getRank()).isEqualTo(2);
// check shape of array is the same as the shape of the variable
int[] variableShape = radiance.getShape();
int[] arrayShape = array.getShape();
assertThat(arrayShape).isEqualTo(arrayShape);
} finally {
System.clearProperty("aws.region");
}
}
@Test
public void testPartialS3NetcdfFile() throws IOException, InvalidRangeException {
String region = Region.US_EAST_1.toString();
String bucket = "noaa-goes16";
String key =
"ABI-L1b-RadC/2019/363/21/OR_ABI-L1b-RadC-M6C16_G16_s20193632101189_e20193632103574_c20193632104070.nc";
String s3uri = "s3://" + bucket + "/" + key;
System.setProperty("aws.region", region);
try (NetcdfFile ncfile = NetcdfFiles.open(s3uri)) {
Variable radiance = ncfile.findVariable("Rad");
Assert.assertNotNull(radiance);
// read part of the array
Section section = new Section("(100:200:2,10:20:1)");
Array array = radiance.read(section);
assertThat(array.getRank()).isEqualTo(2);
// check shape of array is the same as the shape of the section
assertThat(array.getShape()).isEqualTo(section.getShape());
} finally {
System.clearProperty("aws.region");
}
}
@Test
public void testFullS3ReadNetcdfDatasets() throws IOException {
String region = Region.US_EAST_1.toString();
String bucket = "noaa-goes16";
String key =
"ABI-L1b-RadC/2019/363/21/OR_ABI-L1b-RadC-M6C16_G16_s20193632101189_e20193632103574_c20193632104070.nc";
String s3uri = "s3://" + bucket + "/" + key;
System.setProperty("aws.region", region);
try (NetcdfDataset ds = NetcdfDatasets.openDataset(s3uri)) {
String partialConventionValue = "CF-1.";
// read conventions string
String conventions = ds.getRootGroup().attributes().findAttValueIgnoreCase(CF.CONVENTIONS, "");
// check that the file was read the CF convention builder
assertThat(conventions).startsWith(partialConventionValue);
assertThat(ds.getConventionUsed()).startsWith(partialConventionValue);
} finally {
System.clearProperty("aws.region");
}
}
} |
package ru.job4j.chess;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class QueenTest {
/**
* Test where check passed cells.
*/
@Test
public void whenQueentMoveRightThenReturnArray() {
Figure queen = new Queen(new Cell(0, 2));
Cell dist = new Cell(1, 2);
Cell[] result = queen.way(dist);
assertThat(result[0].getxCoord(), is(1));
assertThat(result[0].getyCoord(), is(2));
}
/**
* Test where figure can't move to chosen cell.
* @throws ImpossibleMoveException - exception when move impossible
*/
@Test(expected = ImpossibleMoveException.class)
public void whenQueenMoveWrongThenException() throws ImpossibleMoveException {
Figure queen = new Queen(new Cell(0, 2));
Cell dist = new Cell(1, 4);
Cell[] result = queen.way(dist);
}
} |
package ru.job4j.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Training.
*/
public class SQLStorage {
/**
* Main.
* @param args args.
*/
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/test";
String user = "postgres";
String password = "password";
String sql1 = "SELECT "
+ "cr.name AS \"car\", "
+ "en.name AS \"engine\", "
+ "tr.name AS \"transmission\", "
+ "gr.name AS \"gearbox\" "
+ "FROM cars AS cr\n"
+ "INNER JOIN engines AS en ON cr.engine_id = en.id\n"
+ "INNER JOIN transmissions AS tr ON cr.transmission_id = tr.id\n"
+ "INNER JOIN gearboxes AS gr ON cr.gearbox_id = gr.id";
String sql = "SELECT en.name AS \"Unused parts\" FROM engines AS en\n"
+ "LEFT OUTER JOIN cars AS cr ON en.id = cr.engine_id\n"
+ "WHERE cr.id IS NULL\n"
+ "UNION\n"
+ "SELECT tr.name FROM transmissions AS tr\n"
+ "LEFT OUTER JOIN cars AS cr ON tr.id = cr.transmission_id\n"
+ "WHERE cr.id IS NULL\n"
+ "UNION\n"
+ "SELECT gr.name FROM gearboxes AS gr\n"
+ "LEFT OUTER JOIN cars AS cr ON gr.id = cr.gearbox_id\n"
+ "WHERE cr.id IS NULL";
try (Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(sql1);
while (resultSet.next()) {
// System.out.println(String.format("%s ", resultSet.getString("Unused parts")));
System.out.println(String.format("%s | %s | %s | %s ",
resultSet.getString("car"),
resultSet.getString("engine"),
resultSet.getString("transmission"),
resultSet.getString("gearbox")));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
package org.neo4j.kernel.ha;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
import org.neo4j.helpers.Pair;
import org.neo4j.kernel.impl.ha.Master;
import org.neo4j.kernel.impl.ha.SlaveContext;
/**
* Sits on the master side, receiving serialized requests from slaves (via
* {@link MasterClient}). Delegates actual work to {@link MasterImpl}.
*/
public class MasterServer extends CommunicationProtocol implements ChannelPipelineFactory
{
private final static int DEAD_CONNECTIONS_CHECK_INTERVAL = 10;
private final ChannelFactory channelFactory;
private final ServerBootstrap bootstrap;
private final Master realMaster;
private final ChannelGroup channelGroup;
private final ScheduledExecutorService deadConnectionsPoller;
private final Map<Integer, Collection<Channel>> channelsPerClient =
new HashMap<Integer, Collection<Channel>>();
public MasterServer( Master realMaster, final int port )
{
this.realMaster = realMaster;
ExecutorService executor = Executors.newCachedThreadPool();
channelFactory = new NioServerSocketChannelFactory(
executor, executor );
bootstrap = new ServerBootstrap( channelFactory );
bootstrap.setPipelineFactory( this );
channelGroup = new DefaultChannelGroup();
executor.execute( new Runnable()
{
public void run()
{
Channel channel = bootstrap.bind( new InetSocketAddress( port ) );
// Add the "server" channel
channelGroup.add( channel );
System.out.println( "Master server bound to " + port );
}
} );
deadConnectionsPoller = new ScheduledThreadPoolExecutor( 1 );
deadConnectionsPoller.scheduleWithFixedDelay( new Runnable()
{
public void run()
{
checkForDeadConnections();
}
}, DEAD_CONNECTIONS_CHECK_INTERVAL, DEAD_CONNECTIONS_CHECK_INTERVAL, TimeUnit.SECONDS );
}
public ChannelPipeline getPipeline() throws Exception
{
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast( "frameDecoder", new LengthFieldBasedFrameDecoder( MAX_FRAME_LENGTH,
0, 4, 0, 4 ) );
pipeline.addLast( "frameEncoder", new LengthFieldPrepender( 4 ) );
pipeline.addLast( "serverHandler", new ServerHandler() );
return pipeline;
}
private class ServerHandler extends SimpleChannelHandler
{
@Override
public void messageReceived( ChannelHandlerContext ctx, MessageEvent e ) throws Exception
{
try
{
ChannelBuffer message = (ChannelBuffer) e.getMessage();
Pair<ChannelBuffer, SlaveContext> result = handleRequest( realMaster, message );
rememberChannel( e.getChannel(), result.other() );
e.getChannel().write( result.first() );
}
catch ( Exception e1 )
{
e1.printStackTrace();
throw e1;
}
}
@Override
public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e ) throws Exception
{
// TODO
}
}
public void shutdown()
{
// Close all open connections
deadConnectionsPoller.shutdown();
channelGroup.close().awaitUninterruptibly();
channelFactory.releaseExternalResources();
}
private void rememberChannel( Channel channel, SlaveContext other )
{
channelGroup.add( channel );
if ( other == null )
{
return;
}
int id = other.machineId();
synchronized ( channelsPerClient )
{
Collection<Channel> channels = channelsPerClient.get( id );
if ( channels == null )
{
channels = new HashSet<Channel>();
channelsPerClient.put( id, channels );
System.out.println( "new client connected " + id + ", " + channel );
}
channels.add( channel );
}
}
private void checkForDeadConnections()
{
synchronized ( channelsPerClient )
{
for ( Map.Entry<Integer, Collection<Channel>> entry : channelsPerClient.entrySet() )
{
if ( !entry.getValue().isEmpty() && !pruneDeadChannels( entry.getValue() ) )
{
System.out.println( "Rolling back dead transaction from client " +
entry.getKey() + " since it went down" );
realMaster.rollbackOngoingTransactions( new SlaveContext( entry.getKey(),
new Pair[0] ) );
}
}
}
}
private boolean pruneDeadChannels( Collection<Channel> channels )
{
boolean anyoneAlive = false;
for ( Channel channel : channels.toArray( new Channel[channels.size()] ) )
{
if ( channel.isConnected() )
{
anyoneAlive = true;
}
else
{
channels.remove( channel );
}
}
return anyoneAlive;
}
} |
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// 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 DAVID J. PEARCE 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 wyjc.util;
import java.io.*;
import java.util.*;
import wybs.lang.*;
import wybs.lang.SyntaxError.InternalFailure;
import wybs.util.*;
import wyc.builder.Whiley2WyilBuilder;
import wyc.lang.WhileyFile;
import wyil.Pipeline;
import wyil.lang.WyilFile;
import wyjc.Wyil2JavaBuilder;
import wyjvm.lang.ClassFile;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.MatchingTask;
public class AntTask extends wyc.util.AntTask {
public static class Registry extends wyc.util.AntTask.Registry {
public void associate(Path.Entry e) {
String suffix = e.suffix();
if(suffix.equals("class")) {
e.associate(ClassFile.ContentType, null);
} else {
super.associate(e);
}
}
public String suffix(Content.Type<?> t) {
if(t == ClassFile.ContentType) {
return "class";
} else {
return super.suffix(t);
}
}
}
/**
* The purpose of the class file filter is simply to ensure only binary
* files are loaded in a given directory root. It is not strictly necessary
* for correct operation, although hopefully it offers some performance
* benefits.
*/
public static final FileFilter classFileFilter = new FileFilter() {
public boolean accept(File f) {
String name = f.getName();
return name.endsWith(".class") || f.isDirectory();
}
};
/**
* The class directory is the filesystem directory where all generated jvm
* class files are stored.
*/
protected DirectoryRoot classDir;
/**
* Identifies which wyil files generated from whiley source files which
* should be considered for compilation. By default, all files reachable
* from <code>whileyDestDir</code> are considered.
*/
protected Content.Filter<WyilFile> wyilIncludes = Content.filter("**", WyilFile.ContentType);
/**
* Identifies which wyil files generated from whiley source files should not
* be considered for compilation. This overrides any identified by
* <code>wyilBinaryIncludes</code> . By default, no files files reachable from
* <code>wyilDestDir</code> are excluded.
*/
protected Content.Filter<WyilFile> wyilExcludes = null;
public AntTask() {
super(new Registry());
}
public void setClassdir(File classdir) throws IOException {
this.classDir = new DirectoryRoot(classdir, wyilFileFilter, registry);
}
@Override
public void setIncludes(String includes) {
super.setIncludes(includes);
String[] split = includes.split(",");
Content.Filter<WyilFile> wyilFilter = null;
for (String s : split) {
if (s.endsWith(".whiley")) {
// in this case, we are explicitly includes some whiley source
// files. This implicitly means the corresponding wyil files are
// included.
String name = s.substring(0, s.length() - 7);
Content.Filter<WyilFile> nf = Content.filter(name,
WyilFile.ContentType);
wyilFilter = wyilFilter == null ? nf : Content.or(nf,
wyilFilter);
} else if (s.endsWith(".wyil")) {
String name = s.substring(0, s.length() - 5);
Content.Filter<WyilFile> nf = Content.filter(name,
WyilFile.ContentType);
wyilFilter = wyilFilter == null ? nf : Content.or(nf,
wyilFilter);
}
}
if(wyilFilter != null) {
this.wyilIncludes = wyilFilter;
}
}
@Override
public void setExcludes(String excludes) {
super.setExcludes(excludes);
String[] split = excludes.split(",");
Content.Filter<WyilFile> wyilFilter = null;
for (String s : split) {
if (s.endsWith(".whiley")) {
String name = s.substring(0, s.length() - 7);
Content.Filter<WyilFile> nf = Content.filter(name,
WyilFile.ContentType);
wyilFilter = wyilFilter == null ? nf : Content.or(
nf, wyilFilter);
} else if (s.endsWith(".wyil")) {
String name = s.substring(0, s.length() - 5);
Content.Filter<WyilFile> nf = Content.filter(name,
WyilFile.ContentType);
wyilFilter = wyilFilter == null ? nf : Content.or(
nf, wyilFilter);
}
}
this.wyilExcludes = wyilFilter;
}
@Override
protected void addBuildRules(SimpleProject project) {
// Add default build rule for converting whiley files into wyil files.
super.addBuildRules(project);
// Now, add build rule for converting wyil files into class files using
// the Wyil2JavaBuilder.
Wyil2JavaBuilder jbuilder = new Wyil2JavaBuilder();
if (verbose) {
jbuilder.setLogger(new Logger.Default(System.err));
}
StandardBuildRule rule = new StandardBuildRule(jbuilder);
rule.add(wyilDir, wyilIncludes, wyilExcludes, classDir,
WyilFile.ContentType, ClassFile.ContentType);
project.add(rule);
}
@Override
protected List<Path.Entry<?>> getSourceFileDelta() throws IOException {
// First, determine all whiley source files which are out-of-date with
// respect to their wyil files.
List<Path.Entry<?>> sources = super.getSourceFileDelta();
// Second, look for any wyil files which are out-of-date with their
// respective class file.
for (Path.Entry<WyilFile> source : wyilDir.get(wyilIncludes)) {
Path.Entry<ClassFile> binary = classDir.get(source.id(),
ClassFile.ContentType);
// first, check whether wyil file out-of-date with source file
if (binary == null
|| binary.lastModified() < source.lastModified()) {
sources.add(source);
}
}
// done
return sources;
}
@Override
public void execute() throws BuildException {
if (whileyDir == null && wyilDir == null) {
throw new BuildException("whileydir or wyildir must be specified");
}
if(!compile()) {
throw new BuildException("compilation errors");
}
}
} |
package nars.inference;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import nars.core.EventEmitter.Observer;
import nars.core.Events.ConceptBeliefRemove;
import nars.core.Events.TaskDerive;
import nars.core.Memory;
import nars.core.Parameters;
import nars.entity.Concept;
import nars.entity.Sentence;
import nars.entity.Stamp;
import nars.entity.Task;
import nars.entity.TruthValue;
import nars.inference.GraphExecutive.ParticlePlan;
import nars.io.Symbols;
import nars.io.Texts;
import nars.io.buffer.PriorityBuffer;
import nars.language.Conjunction;
import nars.language.Implication;
import nars.language.Interval;
import nars.language.Term;
import static nars.language.Terms.equalSubTermsInRespectToImageAndProduct;
import nars.language.Variables;
import nars.operator.Operation;
import nars.operator.Operator;
/**
* Operation execution and planning support.
* Strengthens and accelerates goal-reaching activity
*/
public class Executive implements Observer {
public final GraphExecutive graph;
public final Memory memory;
///** memory for faster execution of &/ statements (experiment) */
//public final Deque<TaskConceptContent> next = new ArrayDeque<>();
PriorityBuffer<TaskExecution> tasks;
private Set<TaskExecution> tasksToRemove = new HashSet();
public int shortTermMemorySize=10; //how many events its able to track for the temporal feedback system
//100 should be enough for all practical examples for now, we may make it adaptive later,
//which means adjusting according to the longest (&/,a1...an) =/> .. statement
public ArrayList<Task> lastEvents=new ArrayList<>();
/** number of tasks that are active in the sorted priority buffer for execution */
int numActiveTasks = 1;
/** max number of tasks that a plan can generate. chooses the N best */
int maxPlannedTasks = 1;
/** global plan search parameters */
float searchDepth = 128;
int particles = 64;
/** inline search parameters */
float inlineSearchDepth = searchDepth;
int inlineParticles = 24;
float maxExecutionsPerDuration = 1f;
/** how much to multiply all cause relevancies per cycle */
double causeRelevancyFactor = 0.999;
/** how much to add value to each cause involved in a successful plan */
//TODO move this to a parameter class visible to both Executive and GraphExecutive
public static double relevancyOfSuccessfulPlan = 0.10;
/** time of last execution */
long lastExecution = -1;
/** motivation set on an executing task to prevent other tasks from interrupting it, unless they are relatively urgent.
* a larger value means it is more difficult for a new task to interrupt one which has
* already begun executing.
*/
float motivationToFinishCurrentExecution = 1.5f;
public Executive(Memory mem) {
this.memory = mem;
this.graph = new GraphExecutive(mem,this);
this.tasks = new PriorityBuffer<TaskExecution>(new Comparator<TaskExecution>() {
@Override
public final int compare(final TaskExecution a, final TaskExecution b) {
float ap = a.getDesire();
float bp = b.getDesire();
if (bp != ap) {
return Float.compare(ap, bp);
} else {
float ad = a.getPriority();
float bd = b.getPriority();
if (ad!=bd)
return Float.compare(ad, bd);
else {
float add = a.getDurability();
float bdd = b.getDurability();
return Float.compare(add, bdd);
}
}
}
}, numActiveTasks) {
@Override protected void reject(final TaskExecution t) {
removeTask(t);
}
};
memory.event.set(this, true, TaskDerive.class, ConceptBeliefRemove.class);
}
HashSet<Task> current_tasks=new HashSet<>();
@Override
public void event(Class event, Object[] args) {
if (event == TaskDerive.class) {
Task derivedTask=(Task) args[0];
if(derivedTask.sentence.content instanceof Implication &&
(((Implication) derivedTask.sentence.content).getTemporalOrder()==TemporalRules.ORDER_FORWARD ||
((Implication) derivedTask.sentence.content).getTemporalOrder()==TemporalRules.ORDER_CONCURRENT)) {
if(!current_tasks.contains(derivedTask) && !Variables.containVarIndep(derivedTask.getContent().name())) {
current_tasks.add(derivedTask);
}
}
}
else if (event == ConceptBeliefRemove.class) {
Task removedTask=(Task) args[2]; //task is 3nd
if(current_tasks.contains(removedTask)) {
current_tasks.remove(removedTask);
}
}
}
public class TaskExecution {
/** may be null for input tasks */
public final Concept c;
public final Task t;
public int sequence;
public long delayUntil = -1;
private float motivationFactor = 1;
private TruthValue desire;
public TaskExecution(final Concept concept, Task t) {
this.c = concept;
this.desire = t.getDesire();
//Check if task is
if(Parameters.TEMPORAL_PARTICLE_PLANNER) {
Term term = t.getContent();
if (term instanceof Implication) {
Implication it = (Implication)term;
if ((it.getTemporalOrder() == TemporalRules.ORDER_FORWARD) || (it.getTemporalOrder() == TemporalRules.ORDER_CONCURRENT)) {
if (it.getSubject() instanceof Conjunction) {
t = inlineConjunction(t, (Conjunction)it.getSubject());
}
}
}
else if (term instanceof Conjunction) {
t = inlineConjunction(t, (Conjunction)term);
}
}
this.t = t;
}
//TODO support multiple inline replacements
protected Task inlineConjunction(Task t, final Conjunction c) {
ArrayDeque<Term> inlined = new ArrayDeque();
boolean modified = false;
if (c.operator() == Symbols.NativeOperator.SEQUENCE) {
Term prev = null;
for (Term e : c.term) {
if (!isPlanTerm(e)) {
if (graph.isPlannable(e)) {
TreeSet<ParticlePlan> plans = graph.particlePlan(e, inlineSearchDepth, inlineParticles);
if (plans.size() > 0) {
//use the first
ParticlePlan pp = plans.first();
//if terms precede this one, remove a common prefix
//scan from the end of the sequence backward until a term matches the previous, and splice it there
//TODO more rigorous prefix compraison. compare sublist prefix
List<Term> seq = pp.sequence;
// if (prev!=null) {
// int previousTermIndex = pp.sequence.lastIndexOf(prev);
// if (previousTermIndex!=-1) {
// if (previousTermIndex == seq.size()-1)
// seq = Collections.EMPTY_LIST;
// else {
// seq = seq.subList(previousTermIndex+1, seq.size());
//System.out.println("inline: " + seq + " -> " + e + " in " + c);
//TODO adjust the truth value according to the ratio of term length, so that a small inlined sequence affects less than a larger one
desire = TruthFunctions.deduction(desire, pp.truth);
//System.out.println(t.sentence.truth + " <- " + pp.truth + " -> " + desire);
inlined.addAll(seq);
modified = true;
}
else {
//no plan available, this wont be able to execute
end();
}
}
else {
//this won't be able to execute here
end();
}
}
else {
//executable term, add
inlined.add(e);
}
prev = e;
}
}
//remove suffix intervals
if (inlined.size() > 0) {
while (inlined.peekLast() instanceof Interval) {
inlined.removeLast();
modified = true;
}
}
if (inlined.isEmpty())
end();
if (modified) {
Conjunction nc = c.cloneReplacingTerms(inlined.toArray(new Term[inlined.size()]));
t = t.clone(t.sentence.clone(nc) );
}
return t;
}
@Override public boolean equals(final Object obj) {
if (obj instanceof TaskExecution) {
return ((TaskExecution)obj).t.equals(t);
}
return false;
}
public final float getDesire() {
return desire.getExpectation() * motivationFactor;
}
public final float getPriority() { return t.getPriority(); }
public final float getDurability() { return t.getDurability(); }
//public final float getMotivation() { return getDesire() * getPriority() * motivationFactor; }
public final void setMotivationFactor(final float f) { this.motivationFactor = f; }
@Override public int hashCode() { return t.hashCode(); }
@Override
public String toString() {
return "!" + Texts.n2Slow(getDesire()) + "|" + sequence + "! " + t.toString();
}
public void end() {
setMotivationFactor(0);
if (t!=null)
t.end();
}
}
protected TaskExecution getExecution(final Task parent) {
for (final TaskExecution t : tasks) {
if (t.t.parentTask!=null)
if (t.t.parentTask.equals(parent))
return t;
}
return null;
}
public boolean addTask(final Concept c, final Task t) {
TaskExecution existingExecutable = getExecution(t.parentTask);
boolean valid = true;
if (existingExecutable!=null) {
//TODO compare motivation (desire * priority) instead?
//if the new task for the existin goal has a lower priority, ignore it
if (existingExecutable.getDesire() > t.getDesire().getExpectation()) {
//System.out.println("ignored lower priority task: " + t + " for parent " + t.parentTask);
valid = false;
}
//do not allow interrupting a lower priority, but already executing task
//TODO allow interruption if priority difference is above some threshold
if (existingExecutable.sequence > 0) {
//System.out.println("ignored late task: " + t + " for parent " + t.parentTask);
valid = false;
}
}
if (valid) {
if(!occured && this.expected_task!=null && ended) {
//expected_task.expect(false); //ok this one didnt get his expectation
}
occured=false; //only bad to not happened not interrupted ones
ended=false;
final TaskExecution te = new TaskExecution(c, t);
if (tasks.add(te)) {
//added successfully
memory.emit(TaskExecution.class, te);
return true;
}
}
//t.end();
return false;
}
protected void removeTask(final TaskExecution t) {
if (tasksToRemove.add(t)) {
// if (memory.getRecorder().isActive())
// memory.getRecorder().output("Executive", "Task Remove: " + t.toString());
t.end();
}
}
protected void updateTasks() {
List<TaskExecution> t = new ArrayList(tasks);
t.removeAll(tasksToRemove);
tasks.clear();
for (TaskExecution x : t) {
if (x.getDesire() > 0) { // && (x.getPriority() > 0)) {
tasks.add(x);
//this is incompatible with the other usages of motivationFactor, so do not use this:
// if ((x.delayUntil!=-1) && (x.delayUntil <= memory.getTime())) {
// //restore motivation so task can resume processing
// x.motivationFactor = 1.0f;
}
}
tasksToRemove.clear();
}
// public void manageExecution() {
// if (next.isEmpty()) {
// return;
// TaskConceptContent n = next.pollFirst();
// if (n.task==null) {
// //we have to wait
// return;
// if (!(n.content instanceof Operation)) {
// throw new RuntimeException("manageExecution: Term content is not Operation: " + n.content);
// System.out.println("manageExecution: " + n.task);
// //ok it is time for action:
// execute((Operation)n.content, n.concept, n.task, true);
protected void execute(final Operation op, final Task task) {
Operator oper = op.getOperator();
//if (NAR.DEBUG)
//System.out.println("exe: " + task.getExplanation().trim());
op.setTask(task);
oper.call(op, memory);
//task.end(true);
}
public void decisionPlanning(final NAL nal, final Task t, final Concept concept) {
if (Parameters.TEMPORAL_PARTICLE_PLANNER) {
if (!isDesired(t, concept)) return;
boolean plannable = graph.isPlannable(t.getContent());
if (plannable) {
graph.plan(nal, concept, t, t.getContent(), particles, searchDepth, '!', maxPlannedTasks);
}
}
}
/** Entry point for all potentially executable tasks */
public void decisionMaking(final Task t, final Concept concept) {
if (isDesired(t, concept)) {
Term content = concept.term;
if (content instanceof Operation) {
addTask(concept, t);
}
else if (isSequenceConjunction(content)) {
addTask(concept, t);
}
}
else {
//t.end();
}
}
/** whether a concept's desire exceeds decision threshold */
public boolean isDesired(final Task t, final Concept c) {
float desire = c.getDesire().getExpectation();
float priority = t.budget.getPriority(); //t.budget.summary();
//return true; //always plan //(desire * priority) >= memory.param.decisionThreshold.get();
double dt = memory.param.decisionThreshold.get();
return ((desire >= dt) || (priority >= dt));
}
/** called during each memory cycle */
public void cycle() {
long now = memory.time();
//only execute something no less than every duration time
if (now - lastExecution < (memory.param.duration.get()/maxExecutionsPerDuration) )
return;
lastExecution = now;
graph.implication.multiplyRelevancy(causeRelevancyFactor);
updateTasks();
updateSensors();
if (tasks.isEmpty())
return;
if (memory.emitting(TaskExecution.class)) {
if (tasks.size() > 1) {
for (TaskExecution tcc : tasks)
memory.emit(Executive.class, memory.time(), tcc);
}
else {
memory.emit(Executive.class, memory.time(), tasks.get(0));
}
}
TaskExecution topExecution = tasks.getFirst();
Task top = topExecution.t;
Term term = top.getContent();
if (term instanceof Operation) {
execute((Operation)term, top); //directly execute
removeTask(topExecution);
return;
}
else if (Parameters.TEMPORAL_PARTICLE_PLANNER && term instanceof Conjunction) {
Conjunction c = (Conjunction)term;
if (c.operator() == Symbols.NativeOperator.SEQUENCE) {
executeConjunctionSequence(topExecution, c);
return;
}
}
else if (Parameters.TEMPORAL_PARTICLE_PLANNER && term instanceof Implication) {
Implication it = (Implication)term;
if ((it.getTemporalOrder() == TemporalRules.ORDER_FORWARD) || (it.getTemporalOrder() == TemporalRules.ORDER_CONCURRENT)) {
if (it.getSubject() instanceof Conjunction) {
Conjunction c = (Conjunction)it.getSubject();
if (c.operator() == Symbols.NativeOperator.SEQUENCE) {
executeConjunctionSequence(topExecution, c);
return;
}
}
else if (it.getSubject() instanceof Operation) {
execute((Operation)it.getSubject(), top); //directly execute
removeTask(topExecution);
return;
}
}
throw new RuntimeException("Unrecognized executable term: " + it.getSubject() + "[" + it.getSubject().getClass() + "] from " + top);
}
else {
//throw new RuntimeException("Unknown Task type: "+ top);
}
// //Example prediction
// if (memory.getCurrentBelief()!=null) {
// Term currentTerm = memory.getCurrentBelief().content;
// if (implication.containsVertex(currentTerm)) {
// particlePredict(currentTerm, 12, particles);
}
public static boolean isPlanTerm(final Term t) {
return ((t instanceof Interval) || (t instanceof Operation));
}
public static boolean isExecutableTerm(final Term t) {
return (t instanceof Operation) || isSequenceConjunction(t);
//task.sentence.content instanceof Operation || (task.sentence.content instanceof Conjunction && task.sentence.content.getTemporalOrder()==TemporalRules.ORDER_FORWARD)))
}
public static boolean isSequenceConjunction(final Term c) {
if (c instanceof Conjunction) {
Conjunction cc = ((Conjunction)c);
return ( cc.operator() == Symbols.NativeOperator.SEQUENCE );
//return (cc.getTemporalOrder()==TemporalRules.ORDER_FORWARD) || (cc.getTemporalOrder()==TemporalRules.ORDER_CONCURRENT);
}
return false;
}
public Task expected_task=null;
public Term expected_event=null;
boolean ended=false;
private void executeConjunctionSequence(final TaskExecution task, final Conjunction c) {
int s = task.sequence;
Term currentTerm = c.term[s];
long now = memory.time();
if (task.delayUntil > now) {
//not ready to execute next term
return;
}
if (currentTerm instanceof Operation) {
Concept conc=memory.concept(currentTerm);
execute((Operation)currentTerm, task.t);
task.delayUntil = now + memory.param.duration.get();
s++;
}
else if (currentTerm instanceof Interval) {
Interval ui = (Interval)currentTerm;
task.delayUntil = memory.time() + Interval.magnitudeToTime(ui.magnitude, memory.param.duration);
s++;
}
else {
System.err.println("Non-executable term in sequence: " + currentTerm + " in " + c + " from task " + task.t);
//removeTask(task); //was never executed, dont remove
}
if (s == c.term.length) {
ended=true;
//completed task
if(task.t.sentence.content instanceof Implication) {
expected_task=task.t;
expected_event=((Implication)task.t.sentence.content).getPredicate();
}
removeTask(task);
task.sequence=0;
}
else {
ended=false;
//still incomplete
task.sequence = s;
task.setMotivationFactor(motivationToFinishCurrentExecution);
}
}
//check all predictive statements, match them with last events
public void temporalPredictionsAdapt() {
for(Task c : current_tasks) { //a =/> b or (&/ a1...an) =/> b
boolean concurrent_conjunction=false;
Term[] args=new Term[1];
Implication imp=(Implication) c.getContent();
boolean concurrent_implication=imp.getTemporalOrder()==TemporalRules.ORDER_CONCURRENT;
args[0]=imp.getSubject();
if(imp.getSubject() instanceof Conjunction) {
Conjunction conj=(Conjunction) imp.getSubject();
if(conj.temporalOrder==TemporalRules.ORDER_FORWARD || conj.temporalOrder==TemporalRules.ORDER_CONCURRENT) {
concurrent_conjunction=conj.temporalOrder==TemporalRules.ORDER_CONCURRENT;
args=conj.term; //in case of &/ this are the terms
}
}
int i=0;
boolean matched=true;
int off=0;
long expected_time=lastEvents.get(0).sentence.getOccurenceTime();
for(i=0;i<args.length;i++) {
//handling of intervals:
if(args[i] instanceof Interval) {
if(!concurrent_conjunction) {
expected_time+=((Interval)args[i]).getTime(memory);
}
off++;
continue;
}
if(i-off>=lastEvents.size()) {
break;
}
//handling of other events, seeing if they match and are right in time
if(!args[i].equals(lastEvents.get(i-off).sentence.content)) { //it didnt match, instead sth different unexpected happened
matched=false; //whether intermediate events should be tolerated or not was a important question when considering this,
break; //if it should be allowed, the sequential match does not matter only if the events come like predicted.
} else { //however I decided that sequence matters also for now, because then the more accurate hypothesis wins.
if(lastEvents.get(i-off).sentence.truth.getExpectation()<=0.5) { //it matched according to sequence, but is its expectation bigger than 0.5? todo: decide how truth values of the expected events
//it didn't happen
matched=false;
break;
}
long occurence=lastEvents.get(i-off).sentence.getOccurenceTime();
boolean right_in_time=Math.abs(occurence-expected_time) < ((double)memory.param.duration.get())/Parameters.TEMPORAL_PREDICTION_FEEDBACK_ACCURACY_DIV;
if(!right_in_time) { //it matched so far, but is the timing right or did it happen when not relevant anymore?
matched=false;
break;
}
}
if(!concurrent_conjunction) {
expected_time+=memory.param.duration.get();
}
}
if(concurrent_conjunction && !concurrent_implication) { //implication is not concurrent
expected_time+=memory.param.duration.get(); //so here we have to add duration
}
else
if(!concurrent_conjunction && concurrent_implication) {
expected_time-=memory.param.duration.get();
} //else if both are concurrent, time has never been added so correct
//else if both are not concurrent, time was always added so also correct
//ok it matched, is the consequence also right?
if(matched && lastEvents.size()>args.length-off) {
long occurence=lastEvents.get(args.length-off).sentence.getOccurenceTime();
boolean right_in_time=Math.abs(occurence-expected_time)<((double)memory.param.duration.get())/Parameters.TEMPORAL_PREDICTION_FEEDBACK_ACCURACY_DIV;
if(right_in_time && imp.getPredicate().equals(lastEvents.get(args.length-off).sentence.content)) { //it matched and same consequence, so positive evidence
c.sentence.truth=TruthFunctions.revision(c.sentence.truth, new TruthValue(1.0f,Parameters.DEFAULT_JUDGMENT_CONFIDENCE));
} else { //it matched and other consequence, so negative evidence
c.sentence.truth=TruthFunctions.revision(c.sentence.truth, new TruthValue(0.0f,Parameters.DEFAULT_JUDGMENT_CONFIDENCE));
} //todo use derived task with revision instead
}
}
}
public Task stmLast=null;
boolean occured=false;
public boolean inductionOnSucceedingEvents(final Task newEvent, NAL nal) {
if (newEvent == null || newEvent.sentence.stamp.getOccurrenceTime()==Stamp.ETERNAL || !isInputOrTriggeredOperation(newEvent,nal.mem))
return false;
if (stmLast!=null) {
if(equalSubTermsInRespectToImageAndProduct(newEvent.sentence.content,stmLast.sentence.content)) {
return false;
}
nal.setTheNewStamp(newEvent.sentence.stamp, stmLast.sentence.stamp, memory.time());
nal.setCurrentTask(newEvent);
Sentence currentBelief = stmLast.sentence;
nal.setCurrentBelief(currentBelief);
if(newEvent.getPriority()>Parameters.TEMPORAL_INDUCTION_MIN_PRIORITY) {
TemporalRules.temporalInduction(newEvent.sentence, currentBelief, nal);
}
}
//for this heuristic, only use input events & task effects of operations
if(newEvent.getPriority()>Parameters.TEMPORAL_INDUCTION_MIN_PRIORITY) {
if(Parameters.TEMPORAL_PARTICLE_PLANNER && this.expected_event!=null && this.expected_task!=null) {
if(newEvent.sentence.content.equals(this.expected_event)) {
//this.expected_task.expect(true);
occured=true;
} //else {
//// this.expected_task.expect(false);
// this.expected_event=null;
// this.expected_task=null; //done i think//todo, refine, it could come in a specific time, also +4 on end of a (&/ plan has to be used
}
stmLast=newEvent;
lastEvents.add(newEvent);
temporalPredictionsAdapt();
while(lastEvents.size()>shortTermMemorySize) {
lastEvents.remove(0);
}
}
return true;
}
//is input or by the system triggered operation
public boolean isInputOrTriggeredOperation(final Task newEvent, Memory mem) {
if(!((newEvent.isInput() || Parameters.INTERNAL_EXPERIENCE_FULL) || (newEvent.getCause()!=null))) {
return false;
}
/*Term newcontent=newEvent.sentence.content;
if(newcontent instanceof Operation) {
Term pred=((Operation)newcontent).getPredicate();
if(pred.equals(mem.getOperator("^want")) || pred.equals(mem.getOperator("^believe"))) {
return false;
}
}*/
return true;
}
/*
public boolean isActionable(final Task newEvent, Memory mem) {
if(!((newEvent.isInput()))) {
return false;
}
Term newcontent=newEvent.sentence.content;
if(newcontent instanceof Operation) {
Term pred=((Operation)newcontent).getPredicate();
if(pred.equals(mem.getOperator("^want")) || pred.equals(mem.getOperator("^believe"))) {
return false;
}
}
return true;
}*/
// public static class TaskConceptContent {
// public final Task task;
// public final Concept concept;
// public final Term content;
// public static TaskConceptContent NULL = new TaskConceptContent();
// /** null placeholder */
// protected TaskConceptContent() {
// this.task = null;
// this.concept = null;
// this.content = null;
// public TaskConceptContent(Task task, Concept concept, Term content) {
// this.task = task;
// this.concept = concept;
// this.content = content;
protected void updateSensors() {
memory.logic.PLAN_GRAPH_EDGE.commit(graph.implication.edgeSet().size());
memory.logic.PLAN_GRAPH_VERTEX.commit(graph.implication.vertexSet().size());
memory.logic.PLAN_TASK_EXECUTABLE.commit(tasks.size());
}
} |
package com.lucidera.farrago;
import com.lucidera.farrago.fennel.*;
import com.lucidera.lcs.*;
import com.lucidera.opt.*;
import com.lucidera.runtime.*;
import com.lucidera.type.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.db.*;
import net.sf.farrago.defimpl.*;
import net.sf.farrago.fem.config.*;
import net.sf.farrago.fem.med.*;
import net.sf.farrago.fem.sql2003.*;
import net.sf.farrago.namespace.util.*;
import net.sf.farrago.query.*;
import net.sf.farrago.session.*;
import net.sf.farrago.util.*;
import org.eigenbase.oj.rel.*;
import org.eigenbase.rel.*;
import org.eigenbase.rel.metadata.*;
import org.eigenbase.rel.rules.*;
import org.eigenbase.relopt.*;
import org.eigenbase.relopt.hep.*;
import org.eigenbase.reltype.*;
import org.eigenbase.resgen.*;
import org.eigenbase.resource.*;
import org.eigenbase.sql.*;
import org.eigenbase.sql.parser.*;
/**
* Customizes Farrago session personality with LucidDB behavior.
*
* @author John V. Sichi
* @version $Id$
*/
public class LucidDbSessionPersonality
extends FarragoDefaultSessionPersonality
{
public static final String LOG_DIR = FarragoSessionVariables.LOG_DIR;
public static final String [] LOG_DIR_DEFAULT =
{ "log", "testlog", "trace" };
public static final String ETL_PROCESS_ID = "etlProcessId";
public static final String ETL_PROCESS_ID_DEFAULT = null;
public static final String ETL_ACTION_ID = "etlActionId";
public static final String ETL_ACTION_ID_DEFAULT = null;
public static final String ERROR_MAX = "errorMax";
public static final String ERROR_MAX_DEFAULT = "0";
public static final String ERROR_LOG_MAX = "errorLogMax";
public static final String ERROR_LOG_MAX_DEFAULT = null;
public static final String LAST_UPSERT_ROWS_INSERTED =
"lastUpsertRowsInserted";
public static final String LAST_UPSERT_ROWS_INSERTED_DEFAULT = null;
/**
* If true, this session's default personality is LucidDb, as opposed to one
* that was switched from some other personality to LucidDb
*/
private boolean defaultLucidDb;
/**
* If true, enable index only scan rules
*/
private boolean enableIndexOnlyScans;
protected LucidDbSessionPersonality(
FarragoDbSession session,
FarragoSessionPersonality defaultPersonality,
boolean enableIndexOnlyScans)
{
super(session);
paramValidator.registerDirectoryParam(LOG_DIR, false);
paramValidator.registerStringParam(ETL_PROCESS_ID, true);
paramValidator.registerStringParam(ETL_ACTION_ID, true);
paramValidator.registerIntParam(
ERROR_MAX,
true,
0,
Integer.MAX_VALUE);
paramValidator.registerIntParam(
ERROR_LOG_MAX,
true,
0,
Integer.MAX_VALUE);
paramValidator.registerLongParam(
LAST_UPSERT_ROWS_INSERTED,
true,
0,
Long.MAX_VALUE);
defaultLucidDb = (defaultPersonality == null);
this.enableIndexOnlyScans = enableIndexOnlyScans;
}
// implement FarragoSessionPersonality
public String getDefaultLocalDataServerName(
FarragoSessionStmtValidator stmtValidator)
{
return "SYS_COLUMN_STORE_DATA_SERVER";
}
// implement FarragoSessionPersonality
public SqlOperatorTable getSqlOperatorTable(
FarragoSessionPreparingStmt preparingStmt)
{
return LucidDbOperatorTable.ldbInstance();
}
public boolean supportsFeature(ResourceDefinition feature)
{
// TODO jvs 20-Nov-2005: better infrastructure once there
// are enough feature overrides to justify it
EigenbaseResource featureResource = EigenbaseResource.instance();
// LucidDB doesn't yet support transactions.
if (feature == featureResource.SQLFeature_E151) {
return false;
}
// LucidDB doesn't support UPDATE
if (feature == featureResource.SQLFeature_E101_03) {
return false;
}
// but LucidDB does support MERGE (unlike vanilla Farrago)
if (feature == featureResource.SQLFeature_F312) {
return true;
}
return super.supportsFeature(feature);
}
// implement FarragoSessionPersonality
public FarragoSessionPlanner newPlanner(
FarragoSessionPreparingStmt stmt,
boolean init)
{
return newHepPlanner(stmt);
}
// implement FarragoSessionPersonality
public void registerRelMetadataProviders(ChainedRelMetadataProvider chain)
{
chain.addProvider(new LoptMetadataProvider(database.getSystemRepos()));
}
private FarragoSessionPlanner newHepPlanner(
final FarragoSessionPreparingStmt stmt)
{
final boolean fennelEnabled = stmt.getRepos().isFennelEnabled();
final CalcVirtualMachine calcVM =
stmt.getRepos().getCurrentConfig().getCalcVirtualMachine();
Collection<RelOptRule> medPluginRules = new LinkedHashSet<RelOptRule>();
HepProgram program =
createHepProgram(
fennelEnabled,
calcVM,
medPluginRules);
FarragoSessionPlanner planner =
new LucidDbPlanner(
program,
stmt,
medPluginRules);
// TODO jvs 9-Apr-2006: Get rid of !fennelEnabled configuration
// altogether once there are packaged Windows binary builds available.
planner.addRelTraitDef(CallingConventionTraitDef.instance);
RelOptUtil.registerAbstractRels(planner);
FarragoStandardPlannerRules.addDefaultRules(
planner,
fennelEnabled,
calcVM);
planner.addRule(new CoerceInputsRule(LcsTableMergeRel.class, false));
planner.removeRule(SwapJoinRule.instance);
return planner;
}
private HepProgram createHepProgram(
boolean fennelEnabled,
CalcVirtualMachine calcVM,
Collection<RelOptRule> medPluginRules)
{
HepProgramBuilder builder = new HepProgramBuilder();
// The very first step is to implement index joins on catalog
// tables. The reason we do this here is so that we don't
// disturb the carefully hand-coded joins in the catalog views.
// TODO: loosen up once we make sure OptimizeJoinRule does
// as well or better than the hand-coding.
builder.addRuleByDescription("MedMdrJoinRule");
// Eliminate AGG(DISTINCT x) now, because this transformation
// may introduce new joins which need to be optimized further on.
builder.addRuleInstance(RemoveDistinctAggregateRule.instance);
// Eliminate reducible constant expression. TODO jvs 26-May-2006: do
// this again later wherever more such expressions may be reintroduced.
builder.addRuleClass(FarragoReduceExpressionsRule.class);
// Now, pull join conditions out of joins, leaving behind Cartesian
// products. Why? Because PushFilterRule doesn't start from
// join conditions, only filters. It will push them right back
// into and possibly through the join.
builder.addRuleInstance(ExtractJoinFilterRule.instance);
// Need to fire delete and merge rules before any projection rules
// since they modify the projection
builder.addRuleInstance(new LcsTableDeleteRule());
builder.addRuleInstance(new LcsTableMergeRule());
// Convert ProjectRels underneath an insert into RenameRels before
// applying any merge projection rules. Otherwise, we end up losing
// column information used in error reporting during inserts.
if (fennelEnabled) {
builder.addRuleInstance(new FennelInsertRenameRule());
}
// Execute rules that are needed to do proper join optimization: 1) Push
// down filters so they're closest to the RelNode they apply to. This
// also needs to be done before the pull project rules because filters
// need to be pushed into joins in order for the pull up project rules
// to properly determine whether projects can be pulled up. 2) Pull up
// projects above joins to maximize the number of join factors. 3) Push
// the projects back down so row scans are projected and also so we can
// determine which fields are projected above each join. 4) Push down
// filters a second time to push filters past any projects that were
// pushed down. 5) Convert the join inputs into MultiJoinRels and also
// pull projects back up, but only the ones above joins so we preserve
// projects on top of row scans but maximize the number of join factors.
// 6) Optimize join ordering.
// Push down filters
applyPushDownFilterRules(builder);
// Pull up projects
builder.addGroupBegin();
builder.addRuleInstance(RemoveTrivialProjectRule.instance);
builder.addRuleInstance(
PullUpProjectsAboveJoinRule.instanceTwoProjectChildren);
builder.addRuleInstance(
PullUpProjectsAboveJoinRule.instanceLeftProjectChild);
builder.addRuleInstance(
PullUpProjectsAboveJoinRule.instanceRightProjectChild);
// push filter past project to move the project up in the tree
builder.addRuleInstance(new PushFilterPastProjectRule());
// merge any projects we pull up
builder.addRuleInstance(new MergeProjectRule(true));
builder.addGroupEnd();
// Push the projects back down
applyPushDownProjectRules(builder);
// Push filters down again after pulling and pushing projects
applyPushDownFilterRules(builder);
// Merge any projects that are now on top of one another as a result
// of pushing filters. This ensures that the subprogram below fires
// the 3 rules described in lockstep fashion on only the nodes related
// to joins.
builder.addRuleInstance(new MergeProjectRule(true));
// Convert 2-way joins to n-way joins. Do the conversion bottom-up
// so once a join is converted to a MultiJoinRel, you're ensured that
// all of its children have been converted to MultiJoinRels. At the
// same time, pull up projects that are on top of MultiJoinRels so the
// projects are above their parent joins. Since we're pulling up
// projects, we need to also merge any projects we generate as a
// result of the pullup.
// These three rules are applied within a subprogram so they can be
// applied one after the other in lockstep fashion.
HepProgramBuilder subprogramBuilder = new HepProgramBuilder();
subprogramBuilder.addMatchOrder(HepMatchOrder.BOTTOM_UP);
subprogramBuilder.addMatchLimit(1);
subprogramBuilder.addRuleInstance(new ConvertMultiJoinRule());
subprogramBuilder.addRuleInstance(
PullUpProjectsOnTopOfMultiJoinRule.instanceTwoProjectChildren);
subprogramBuilder.addRuleInstance(
PullUpProjectsOnTopOfMultiJoinRule.instanceLeftProjectChild);
subprogramBuilder.addRuleInstance(
PullUpProjectsOnTopOfMultiJoinRule.instanceRightProjectChild);
subprogramBuilder.addRuleInstance(new MergeProjectRule(true));
builder.addSubprogram(subprogramBuilder.createProgram());
// Push projection information in the remaining projections that sit
// on top of MultiJoinRels into the MultiJoinRels. These aren't
// handled by PullUpProjectsOnTopOfMultiJoinRule because these
// projects are not beneath joins.
builder.addRuleInstance(new PushProjectIntoMultiJoinRule());
// Optimize join order; this will spit back out all 2-way joins and
// semijoins. Note that the match order is bottom-up, so we
// can optimize lower-level joins before their ancestors. That allows
// ancestors to have better cost info to work with (well, eventually).
builder.addMatchOrder(HepMatchOrder.BOTTOM_UP);
builder.addRuleInstance(new LoptOptimizeJoinRule());
builder.addMatchOrder(HepMatchOrder.ARBITRARY);
// Push semijoins down to tables. (The join part is a NOP for now,
// but once we start taking more kinds of join factors, it won't be.)
builder.addGroupBegin();
builder.addRuleInstance(new PushSemiJoinPastFilterRule());
builder.addRuleInstance(new PushSemiJoinPastProjectRule());
builder.addRuleInstance(new PushSemiJoinPastJoinRule());
builder.addGroupEnd();
// Do another round of filtering pushing, in the event that
// LoptOptimizeJoinRule has added filters on top of join nodes.
// Do this after pushing semijoins, in case those interfere with
// filter pushdowns.
applyPushDownFilterRules(builder);
// Convert semijoins to physical index access.
// Do this immediately after LopOptimizeJoinRule and the PushSemiJoin
// rules.
builder.addRuleClass(LcsIndexSemiJoinRule.class);
// Convert filters to bitmap index searches and boolean operators.
// Do this after LcsIndexSemiJoinRule
builder.addRuleClass(LcsIndexAccessRule.class);
// TODO zfong 10/27/06 - This rule is currently a no-op because we
// won't generate a semijoin if it can't be converted to physical
// RelNodes. But it's currently left in place in case of bugs.
// In the future, change it to a rule that converts the leftover
// SemiJoinRel to a pattern that can be processed by LhxSemiJoinRule so
// we instead use hash semijoins to process the semijoin rather than
// removing the semijoin, which could result in an incorrect query
// result.
builder.addRuleInstance(new RemoveSemiJoinRule());
// Now that we've finished join ordering optimization, have converted
// filters where possible, and have converted semijoins, push projects
// back down.
applyPushDownProjectRules(builder);
// Apply physical projection to row scans, eliminating access
// to clustered indexes we don't need.
builder.addRuleInstance(new LcsTableProjectionRule());
// Consider index only access. Multiple rules are required
// for various patterns. Apply these rules after we've pushed down
// all projections.
if (enableIndexOnlyScans) {
builder.addRuleInstance(LcsIndexOnlyAccessRule.instanceSearch);
builder.addRuleInstance(LcsIndexOnlyAccessRule.instanceMerge);
}
// Eliminate UNION DISTINCT and trivial UNION.
// REVIEW: some of this may need to happen earlier as well.
builder.addRuleInstance(new UnionToDistinctRule());
builder.addRuleInstance(new UnionEliminatorRule());
// Eliminate redundant SELECT DISTINCT.
builder.addRuleInstance(new RemoveDistinctRule());
// We're getting close to physical implementation. First, insert
// type coercions for expressions which require it.
builder.addRuleClass(CoerceInputsRule.class);
// Run any SQL/MED plugin rules. For FTRS, this includes index joins.
// LCS rules are included here too; the ones we've already executed
// explicitly should be nops now, but some, like LcsTableAppendRule and
// LcsIndexBuilderRule, we actually need to run. (Note that
// LcsTableAppendRule relies on CoerceInputsRule above.)
builder.addRuleCollection(medPluginRules);
// Use hash semi join if possible.
builder.addRuleInstance(new LhxSemiJoinRule());
// Use hash join wherever possible.
builder.addRuleInstance(new LhxJoinRule());
// Use hash join to implement set op: Intersect.
builder.addRuleInstance(new LhxIntersectRule());
// Use hash join to implement set op: Except(minus).
builder.addRuleInstance(new LhxMinusRule());
// Use nested loop join if hash join can't be used
if (fennelEnabled) {
builder.addRuleInstance(new FennelNestedLoopJoinRule());
}
// Extract join conditions again so that FennelCartesianJoinRule can do
// its job. Need to do this before converting filters to calcs, but
// after other join strategies such as hash join have been attempted,
// because they rely on the join condition being part of the join.
builder.addRuleInstance(ExtractJoinFilterRule.instance);
// Change "is not distinct from" condition to a case expression
// which can be evaluated by CalcRel.
builder.addRuleInstance(RemoveIsNotDistinctFromRule.instance);
// Replace AVG with SUM/COUNT (need to do this BEFORE calc conversion
// and decimal reduction).
builder.addRuleInstance(ReduceAggregatesRule.instance);
// Bitmap aggregation is favored
if (enableIndexOnlyScans) {
builder.addRuleInstance(LcsIndexAggRule.instanceRenameRowScan);
builder.addRuleInstance(LcsIndexAggRule.instanceRenameNormalizer);
}
// Prefer hash aggregation over the standard Fennel aggregation.
// Apply aggregation rules before the calc rules below so we can
// call metadata queries on logical RelNodes.
builder.addRuleInstance(new LhxAggRule());
// Handle trivial renames now so that they don't get
// implemented as calculators.
if (fennelEnabled) {
builder.addRuleInstance(new FennelRenameRule());
}
// Convert remaining filters and projects to logical calculators,
// merging adjacent ones.
builder.addGroupBegin();
builder.addRuleInstance(FilterToCalcRule.instance);
builder.addRuleInstance(ProjectToCalcRule.instance);
builder.addRuleInstance(MergeCalcRule.instance);
builder.addGroupEnd();
// First, try to use ReshapeRel for calcs before firing the other
// physical calc conversion rules. Fire this rule before
// ReduceDecimalsRule so we avoid decimal reinterprets that can
// be handled by Reshape
if (fennelEnabled) {
builder.addRuleInstance(new FennelReshapeRule());
}
// Replace the DECIMAL datatype with primitive ints.
builder.addRuleInstance(new ReduceDecimalsRule());
// The rest of these are all physical implementation rules
// which are safe to apply simultaneously.
builder.addGroupBegin();
// Implement calls to UDX's.
builder.addRuleInstance(FarragoJavaUdxRule.instance);
if (fennelEnabled) {
builder.addRuleInstance(new FennelSortRule());
builder.addRuleInstance(new FennelRenameRule());
builder.addRuleInstance(new FennelCartesianJoinRule());
builder.addRuleInstance(new FennelAggRule());
builder.addRuleInstance(new FennelValuesRule());
// Requires CoerceInputsRule.
builder.addRuleInstance(FennelUnionRule.instance);
} else {
builder.addRuleInstance(
new IterRules.HomogeneousUnionToIteratorRule());
}
// If FennelCartesianJoinRule swapped its join inputs and added a
// new CalcRel on top of the new cartesian join, we may need to
// merge the calc with other calcs
builder.addRuleInstance(MergeCalcRule.instance);
if (calcVM.equals(CalcVirtualMachineEnum.CALCVM_FENNEL)) {
// use Fennel for calculating expressions
assert (fennelEnabled);
builder.addRuleByDescription("FennelCalcRule");
builder.addRuleInstance(new FennelOneRowRule());
} else if (calcVM.equals(CalcVirtualMachineEnum.CALCVM_JAVA)) {
// use Java code generation for calculating expressions
builder.addRuleInstance(IterRules.IterCalcRule.instance);
builder.addRuleInstance(new IterRules.OneRowToIteratorRule());
}
// Finish main physical implementation group.
builder.addGroupEnd();
// If automatic calculator selection is enabled (the default),
// figure out what to do with CalcRels.
if (calcVM.equals(CalcVirtualMachineEnum.CALCVM_AUTO)) {
// First, attempt to choose calculators such that converters are
// minimized
builder.addConverters(false);
// Split remaining expressions into Fennel part and Java part
builder.addRuleByDescription("FarragoAutoCalcRule");
// Convert expressions, giving preference to Java
builder.addRuleInstance(new IterRules.OneRowToIteratorRule());
builder.addRuleInstance(IterRules.IterCalcRule.instance);
builder.addRuleByDescription("FennelCalcRule");
}
// Finally, add generic converters as necessary.
builder.addConverters(true);
// After calculator relations are resolved, decorate Java calc rels
builder.addRuleInstance(LoptIterCalcRule.lcsAppendInstance);
builder.addRuleInstance(LoptIterCalcRule.tableAccessInstance);
builder.addRuleInstance(LoptIterCalcRule.lcsMergeInstance);
builder.addRuleInstance(LoptIterCalcRule.lcsDeleteInstance);
builder.addRuleInstance(LoptIterCalcRule.jdbcQueryInstance);
builder.addRuleInstance(LoptIterCalcRule.javaUdxInstance);
builder.addRuleInstance(LoptIterCalcRule.hashJoinInstance);
builder.addRuleInstance(LoptIterCalcRule.defaultInstance);
return builder.createProgram();
}
/**
* Applies rules that push filters past various RelNodes.
*
* @param builder HEP program builder
*/
private void applyPushDownFilterRules(HepProgramBuilder builder)
{
builder.addGroupBegin();
builder.addRuleInstance(new PushFilterPastSetOpRule());
builder.addRuleInstance(new PushFilterPastProjectRule());
builder.addRuleInstance(
new PushFilterPastJoinRule(
new RelOptRuleOperand(
FilterRel.class,
new RelOptRuleOperand[] {
new RelOptRuleOperand(JoinRel.class, null)
}),
"with filter above join"));
builder.addRuleInstance(
new PushFilterPastJoinRule(
new RelOptRuleOperand(JoinRel.class, null),
"without filter above join"));
// merge filters
builder.addRuleInstance(new MergeFilterRule());
builder.addGroupEnd();
}
/**
* Applies rules that push projects past various RelNodes.
*
* @param builder HEP program builder
*/
private void applyPushDownProjectRules(HepProgramBuilder builder)
{
builder.addGroupBegin();
builder.addRuleInstance(RemoveTrivialProjectRule.instance);
builder.addRuleInstance(
new PushProjectPastSetOpRule(
LucidDbOperatorTable.ldbInstance().getSpecialOperators()));
builder.addRuleInstance(
new PushProjectPastJoinRule(
LucidDbOperatorTable.ldbInstance().getSpecialOperators()));
// Rules to push projects past filters. There are two rule
// patterns because the second is needed to handle the case where
// the projection has been trivially removed but we still need to
// pull special columns referenced in filters into a new projection.
builder.addRuleInstance(
new PushProjectPastFilterRule(
new RelOptRuleOperand(
ProjectRel.class,
new RelOptRuleOperand[] {
new RelOptRuleOperand(FilterRel.class, null)
}),
LucidDbOperatorTable.ldbInstance().getSpecialOperators(),
"with project"));
builder.addRuleInstance(
new PushProjectPastFilterRule(
new RelOptRuleOperand(FilterRel.class, null),
LucidDbOperatorTable.ldbInstance().getSpecialOperators(),
"without project"));
builder.addRuleInstance(new MergeProjectRule(true));
builder.addGroupEnd();
}
// override FarragoDefaultSessionPersonality
public void loadDefaultSessionVariables(
FarragoSessionVariables variables)
{
super.loadDefaultSessionVariables(variables);
// try to pick a good default variable for log directory. this would
// not be used in practice, but could be helpful during development.
String homeDirPath = FarragoProperties.instance().homeDir.get();
File homeDir = new File(homeDirPath);
assert (homeDir.exists() && homeDir.isDirectory());
String logDirPath = homeDirPath;
for (String subDirPath : LOG_DIR_DEFAULT) {
File logDir = new File(homeDir, subDirPath);
if (logDir.exists()) {
logDirPath = logDir.getPath();
break;
}
}
variables.setDefault(LOG_DIR, logDirPath);
variables.setDefault(ETL_PROCESS_ID, ETL_PROCESS_ID_DEFAULT);
variables.setDefault(ETL_ACTION_ID, ETL_ACTION_ID_DEFAULT);
variables.setDefault(ERROR_MAX, ERROR_MAX_DEFAULT);
variables.setDefault(ERROR_LOG_MAX, ERROR_LOG_MAX_DEFAULT);
variables.setDefault(
LAST_UPSERT_ROWS_INSERTED,
LAST_UPSERT_ROWS_INSERTED_DEFAULT);
}
// implement FarragoSessionPersonality
public FarragoSessionVariables createInheritedSessionVariables(
FarragoSessionVariables variables)
{
// for reentrant sessions, don't inherit the "errorMax" setting because
// it may cause misbehavior in internal SQL for something like ANALYZE
// or constant reduction
FarragoSessionVariables clone =
super.createInheritedSessionVariables(variables);
clone.set(
LucidDbSessionPersonality.ERROR_MAX,
LucidDbSessionPersonality.ERROR_MAX_DEFAULT);
return clone;
}
// override FarragoDefaultSessionPersonality
public FarragoSessionRuntimeContext newRuntimeContext(
FarragoSessionRuntimeParams params)
{
return new LucidDbRuntimeContext(params);
}
// override FarragoDefaultSessionPersonality
public FarragoSessionPreparingStmt newPreparingStmt(
FarragoSessionStmtContext stmtContext,
FarragoSessionStmtValidator stmtValidator)
{
String sql = (stmtContext == null) ? "?" : stmtContext.getSql();
LucidDbPreparingStmt stmt =
new LucidDbPreparingStmt(stmtValidator, sql);
initPreparingStmt(stmt);
return stmt;
}
// implement FarragoSessionPersonality
public RelDataTypeFactory newTypeFactory(
FarragoRepos repos)
{
return new LucidDbTypeFactory(repos);
}
// implement FarragoSessionPersonality
public void getRowCounts(
ResultSet resultSet,
List<Long> rowCounts,
TableModificationRel.Operation tableModOp)
throws SQLException
{
boolean found = resultSet.next();
assert (found);
boolean nextRowCount = addRowCount(resultSet, rowCounts);
if ((tableModOp == TableModificationRel.Operation.INSERT)
|| (tableModOp == TableModificationRel.Operation.MERGE))
{
// inserts may have a violation rowcount whereas merges may have
// both a violation count and a deletion count
if (nextRowCount) {
nextRowCount = addRowCount(resultSet, rowCounts);
}
}
if (tableModOp == TableModificationRel.Operation.MERGE) {
if (nextRowCount) {
nextRowCount = addRowCount(resultSet, rowCounts);
}
}
assert (!nextRowCount);
}
// implement FarragoSessionPersonality
public long updateRowCounts(
FarragoSession session,
List<String> tableName,
List<Long> rowCounts,
TableModificationRel.Operation tableModOp)
{
FarragoSessionStmtValidator stmtValidator = session.newStmtValidator();
FarragoRepos repos = session.getRepos();
long affectedRowCount = 0;
FarragoReposTxnContext txn = repos.newTxnContext();
try {
txn.beginWriteTxn();
// get the current rowcounts
assert (tableName.size() == 3);
SqlIdentifier qualifiedName =
new SqlIdentifier(
tableName.toArray(new String[tableName.size()]),
new SqlParserPos(0, 0));
FemAbstractColumnSet columnSet =
stmtValidator.findSchemaObject(
qualifiedName,
FemAbstractColumnSet.class);
long currRowCount = columnSet.getRowCount();
long currDeletedRowCount = columnSet.getDeletedRowCount();
// categorize the rowcounts returned by the statement
long insertedRowCount = 0;
long deletedRowCount = 0;
long violationRowCount = 0;
int numRowCounts = rowCounts.size();
if (tableModOp == TableModificationRel.Operation.DELETE) {
deletedRowCount = rowCounts.get(0);
} else if (tableModOp == TableModificationRel.Operation.INSERT) {
insertedRowCount = rowCounts.get(0);
if (numRowCounts == 2) {
violationRowCount = rowCounts.get(1);
}
} else if (tableModOp == TableModificationRel.Operation.MERGE) {
insertedRowCount = rowCounts.get(0);
if (FarragoCatalogUtil.hasUniqueKey(columnSet)) {
violationRowCount = rowCounts.get(1);
if (numRowCounts == 3) {
deletedRowCount = rowCounts.get(2);
}
} else {
if (numRowCounts == 2) {
deletedRowCount = rowCounts.get(1);
}
}
} else {
assert (false);
}
// update the rowcounts based on the operation
if (tableModOp == TableModificationRel.Operation.INSERT) {
affectedRowCount = insertedRowCount - violationRowCount;
currRowCount += affectedRowCount;
} else if (tableModOp == TableModificationRel.Operation.DELETE) {
affectedRowCount = deletedRowCount;
currRowCount -= deletedRowCount;
currDeletedRowCount += deletedRowCount;
} else if (tableModOp == TableModificationRel.Operation.MERGE) {
affectedRowCount = insertedRowCount - violationRowCount;
long newRowCount = affectedRowCount - deletedRowCount;
currRowCount += newRowCount;
currDeletedRowCount += deletedRowCount;
session.getSessionVariables().setLong(
LAST_UPSERT_ROWS_INSERTED,
newRowCount);
} else {
assert (false);
}
// update the catalog; don't let the rowcount go below zero; it
// may go below zero if a crash occurred in the middle of a prior
// update
if (currRowCount < 0) {
currRowCount = 0;
}
columnSet.setRowCount(currRowCount);
assert (currDeletedRowCount >= 0);
columnSet.setDeletedRowCount(currDeletedRowCount);
txn.commit();
} finally {
txn.rollback();
stmtValidator.closeAllocation();
}
return affectedRowCount;
}
// implement FarragoSessionPersonality
public void resetRowCounts(FemAbstractColumnSet table)
{
FarragoCatalogUtil.resetRowCounts(table);
}
// implement FarragoStreamFactoryProvider
public void registerStreamFactories(long hStreamGraph)
{
// REVIEW jvs 22-Mar-2007: We override FarragoDefaultSessionPersonality
// here to prevent dependency on DisruptiveTechJni unless explicitly
// requested via calc system parameter.
final CalcVirtualMachine calcVM =
database.getSystemRepos().getCurrentConfig()
.getCalcVirtualMachine();
if (calcVM.equals(CalcVirtualMachineEnum.CALCVM_JAVA)) {
LucidEraJni.registerStreamFactory(hStreamGraph);
} else {
super.registerStreamFactories(hStreamGraph);
}
}
// implement FarragoSessionPersonality
public void updateIndexRoot(
FemLocalIndex index,
FarragoDataWrapperCache wrapperCache,
FarragoSessionIndexMap baseIndexMap,
Long newRoot)
{
if (defaultLucidDb) {
baseIndexMap.versionIndexRoot(wrapperCache, index, newRoot);
} else {
super.updateIndexRoot(index, wrapperCache, baseIndexMap, newRoot);
}
}
// TODO jvs 9-Apr-2006: Move this to com.lucidera.opt once
// naming convention has been decided there.
private static class LucidDbPlanner
extends HepPlanner
implements FarragoSessionPlanner
{
private final FarragoSessionPreparingStmt stmt;
private final Collection<RelOptRule> medPluginRules;
private boolean inPluginRegistration;
LucidDbPlanner(
HepProgram program,
FarragoSessionPreparingStmt stmt,
Collection<RelOptRule> medPluginRules)
{
super(program);
this.stmt = stmt;
this.medPluginRules = medPluginRules;
}
// implement FarragoSessionPlanner
public FarragoSessionPreparingStmt getPreparingStmt()
{
return stmt;
}
// implement FarragoSessionPlanner
public void beginMedPluginRegistration(String serverClassName)
{
inPluginRegistration = true;
}
// implement FarragoSessionPlanner
public void endMedPluginRegistration()
{
inPluginRegistration = false;
}
// implement RelOptPlanner
public JavaRelImplementor getJavaRelImplementor(RelNode rel)
{
return stmt.getRelImplementor(
rel.getCluster().getRexBuilder());
}
// implement RelOptPlanner
public boolean addRule(RelOptRule rule)
{
if (inPluginRegistration) {
medPluginRules.add(rule);
}
return super.addRule(rule);
}
}
}
// End LucidDbSessionPersonality.java |
package edu.umd.cs.findbugs.ba.type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ATHROW;
import org.apache.bcel.generic.CodeExceptionGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.ExceptionThrower;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.DeepSubtypeAnalysis;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisFeatures;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.Dataflow;
import edu.umd.cs.findbugs.ba.DataflowAnalysis;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.DataflowTestDriver;
import edu.umd.cs.findbugs.ba.DepthFirstSearch;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.EdgeTypes;
import edu.umd.cs.findbugs.ba.FrameDataflowAnalysis;
import edu.umd.cs.findbugs.ba.Hierarchy;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.MissingClassException;
import edu.umd.cs.findbugs.ba.ObjectTypeFactory;
import edu.umd.cs.findbugs.ba.RepositoryLookupFailureCallback;
import edu.umd.cs.findbugs.ba.SignatureConverter;
import edu.umd.cs.findbugs.ba.vna.ValueNumber;
import edu.umd.cs.findbugs.ba.vna.ValueNumberDataflow;
import edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;
/**
* A forward dataflow analysis to determine the types of all values
* in the Java stack frame at all points in a Java method.
* The values include local variables and values on the Java operand stack.
* <p/>
* <p> As a side effect, the analysis computes the exception
* set throwable on each exception edge in the CFG.
* This information can be used to prune infeasible exception
* edges, and mark exception edges which propagate only
* implicit exceptions.
*
* @author David Hovemeyer
* @see Dataflow
* @see DataflowAnalysis
* @see TypeFrame
*/
public class TypeAnalysis extends FrameDataflowAnalysis<Type, TypeFrame>
implements EdgeTypes {
public static final boolean DEBUG = SystemProperties.getBoolean("ta.debug");
/**
* Force computation of accurate exceptions.
*/
public static final boolean FORCE_ACCURATE_EXCEPTIONS =SystemProperties.getBoolean("ta.accurateExceptions");
/**
* Repository of information about thrown exceptions computed for
* a basic block and its outgoing exception edges.
* It contains a result TypeFrame, which is used to detect
* when the exception information needs to be recomputed
* for the block.
*/
private class CachedExceptionSet {
private TypeFrame result;
private ExceptionSet exceptionSet;
private Map<Edge, ExceptionSet> edgeExceptionMap;
public CachedExceptionSet(TypeFrame result, ExceptionSet exceptionSet) {
this.result = result;
this.exceptionSet = exceptionSet;
this.edgeExceptionMap = new HashMap<Edge, ExceptionSet>();
}
public boolean isUpToDate(TypeFrame result) {
return this.result.equals(result);
}
public ExceptionSet getExceptionSet() {
return exceptionSet;
}
public void setEdgeExceptionSet(Edge edge, ExceptionSet exceptionSet) {
edgeExceptionMap.put(edge, exceptionSet);
}
public ExceptionSet getEdgeExceptionSet(Edge edge) {
ExceptionSet edgeExceptionSet = edgeExceptionMap.get(edge);
if (edgeExceptionSet == null) {
edgeExceptionSet = exceptionSetFactory.createExceptionSet();
edgeExceptionMap.put(edge, edgeExceptionSet);
}
return edgeExceptionSet;
}
}
/**
* Cached information about an instanceof check.
*/
static class InstanceOfCheck {
final ValueNumber valueNumber;
final Type type;
InstanceOfCheck(ValueNumber valueNumber, Type type) {
this.valueNumber = valueNumber;
this.type = type;
}
/**
* @return Returns the valueNumber.
*/
public ValueNumber getValueNumber() {
return valueNumber;
}
/**
* @return Returns the type.
*/
public Type getType() {
return type;
}
}
protected MethodGen methodGen;
protected CFG cfg;
private TypeMerger typeMerger;
private TypeFrameModelingVisitor visitor;
private Map<BasicBlock, CachedExceptionSet> thrownExceptionSetMap;
private RepositoryLookupFailureCallback lookupFailureCallback;
private ExceptionSetFactory exceptionSetFactory;
private ValueNumberDataflow valueNumberDataflow;
private Map<BasicBlock, InstanceOfCheck> instanceOfCheckMap;
/**
* Constructor.
*
* @param methodGen the MethodGen whose CFG we'll be analyzing
* @param cfg the control flow graph
* @param dfs DepthFirstSearch of the method
* @param typeMerger object to merge types
* @param visitor a TypeFrameModelingVisitor to use to model the effect
* of instructions
* @param lookupFailureCallback lookup failure callback
* @param exceptionSetFactory factory for creating ExceptionSet objects
*/
public TypeAnalysis(MethodGen methodGen, CFG cfg, DepthFirstSearch dfs,
TypeMerger typeMerger, TypeFrameModelingVisitor visitor,
RepositoryLookupFailureCallback lookupFailureCallback,
ExceptionSetFactory exceptionSetFactory) {
super(dfs);
this.methodGen = methodGen;
this.cfg = cfg;
this.typeMerger = typeMerger;
this.visitor = visitor;
this.thrownExceptionSetMap = new HashMap<BasicBlock, CachedExceptionSet>();
this.lookupFailureCallback = lookupFailureCallback;
this.exceptionSetFactory = exceptionSetFactory;
this.instanceOfCheckMap = new HashMap<BasicBlock, InstanceOfCheck>();
if (DEBUG) {
System.out.println("\n\nAnalyzing " + methodGen);
}
}
/**
* Constructor.
*
* @param methodGen the MethodGen whose CFG we'll be analyzing
* @param cfg the control flow graph
* @param dfs DepthFirstSearch of the method
* @param typeMerger object to merge types
* @param lookupFailureCallback lookup failure callback
* @param exceptionSetFactory factory for creating ExceptionSet objects
*/
public TypeAnalysis(MethodGen methodGen, CFG cfg, DepthFirstSearch dfs,
TypeMerger typeMerger, RepositoryLookupFailureCallback lookupFailureCallback,
ExceptionSetFactory exceptionSetFactory) {
this(methodGen, cfg, dfs, typeMerger,
new TypeFrameModelingVisitor(methodGen.getConstantPool()), lookupFailureCallback,
exceptionSetFactory);
}
/**
* Constructor which uses StandardTypeMerger.
*
* @param methodGen the MethodGen whose CFG we'll be analyzing
* @param cfg the control flow graph
* @param dfs DepthFirstSearch of the method
* @param lookupFailureCallback callback for Repository lookup failures
* @param exceptionSetFactory factory for creating ExceptionSet objects
*/
public TypeAnalysis(MethodGen methodGen, CFG cfg, DepthFirstSearch dfs,
RepositoryLookupFailureCallback lookupFailureCallback,
ExceptionSetFactory exceptionSetFactory) {
this(methodGen, cfg, dfs,
new StandardTypeMerger(lookupFailureCallback, exceptionSetFactory),
lookupFailureCallback, exceptionSetFactory);
}
/**
* Set the ValueNumberDataflow for the method being analyzed.
* This is optional; if set, it will be used to make instanceof
* instructions more precise.
*
* @param valueNumberDataflow the ValueNumberDataflow
*/
public void setValueNumberDataflow(ValueNumberDataflow valueNumberDataflow) {
this.valueNumberDataflow = valueNumberDataflow;
this.visitor.setValueNumberDataflow(valueNumberDataflow);
}
/**
* Set the FieldStoreTypeDatabase.
* This can be used to get more accurate types for values loaded
* from fields.
*
* @param database the FieldStoreTypeDatabase
*/
public void setFieldStoreTypeDatabase(FieldStoreTypeDatabase database) {
visitor.setFieldStoreTypeDatabase(database);
}
/**
* Get the set of exceptions that can be thrown on given edge.
* This should only be called after the analysis completes.
*
* @param edge the Edge
* @return the ExceptionSet
*/
public ExceptionSet getEdgeExceptionSet(Edge edge) {
CachedExceptionSet cachedExceptionSet = thrownExceptionSetMap.get(edge.getSource());
return cachedExceptionSet.getEdgeExceptionSet(edge);
}
public TypeFrame createFact() {
return new TypeFrame(methodGen.getMaxLocals());
}
public void initEntryFact(TypeFrame result) {
// Make the frame valid
result.setValid();
int slot = 0;
// Clear the stack slots in the frame
result.clearStack();
// Add local for "this" pointer, if present
if (!methodGen.isStatic())
result.setValue(slot++, ObjectTypeFactory.getInstance(methodGen.getClassName()));
// Add locals for parameters.
// Note that long and double parameters need to be handled
// specially because they occupy two locals.
Type[] argumentTypes = methodGen.getArgumentTypes();
for (Type argType : argumentTypes) {
// Add special "extra" type for long or double params.
// These occupy the slot before the "plain" type.
if (argType.getType() == Constants.T_LONG) {
result.setValue(slot++, TypeFrame.getLongExtraType());
} else if (argType.getType() == Constants.T_DOUBLE) {
result.setValue(slot++, TypeFrame.getDoubleExtraType());
}
// Add the plain parameter type.
result.setValue(slot++, argType);
}
// Set remaining locals to BOTTOM; this will cause any
// uses of them to be flagged
while (slot < methodGen.getMaxLocals())
result.setValue(slot++, TypeFrame.getBottomType());
}
@Override
public void copy(TypeFrame source, TypeFrame dest) {
dest.copyFrom(source);
}
@Override
public void initResultFact(TypeFrame result) {
// This is important. Sometimes we need to use a result value
// before having a chance to initialize it. We don't want such
// values to corrupt other TypeFrame values that we merge them with.
// So, all result values must be TOP.
result.setTop();
}
@Override
public void makeFactTop(TypeFrame fact) {
fact.setTop();
}
@Override
public boolean isFactValid(TypeFrame fact) {
return fact.isValid();
}
@Override
public boolean same(TypeFrame fact1, TypeFrame fact2) {
return fact1.sameAs(fact2);
}
@Override
public void transferInstruction(InstructionHandle handle, BasicBlock basicBlock, TypeFrame fact)
throws DataflowAnalysisException {
visitor.setFrameAndLocation(fact, new Location(handle, basicBlock));
visitor.analyzeInstruction(handle.getInstruction());
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.AbstractDataflowAnalysis#transfer(edu.umd.cs.findbugs.ba.BasicBlock, org.apache.bcel.generic.InstructionHandle, java.lang.Object, java.lang.Object)
*/
@Override
public void transfer(BasicBlock basicBlock, InstructionHandle end, TypeFrame start, TypeFrame result) throws DataflowAnalysisException {
visitor.startBasicBlock();
super.transfer(basicBlock, end, start, result);
// Compute thrown exception types
computeThrownExceptionTypes(basicBlock, end, result);
if (DEBUG) {
System.out.println("After " + basicBlock.getFirstInstruction() + " -> " + basicBlock.getLastInstruction());
System.out.println(" frame: " + result);
}
// If this block ends with an instanceof check,
// update the cached information about it.
instanceOfCheckMap.remove(basicBlock);
if (visitor.isInstanceOfFollowedByBranch()) {
InstanceOfCheck check = new InstanceOfCheck(visitor.getInstanceOfValueNumber(), visitor.getInstanceOfType());
instanceOfCheckMap.put(basicBlock, check);
}
}
private void computeThrownExceptionTypes(BasicBlock basicBlock, InstructionHandle end, TypeFrame result)
throws DataflowAnalysisException {
// Do nothing if we're not computing propagated exceptions
if (!(FORCE_ACCURATE_EXCEPTIONS ||
AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.ACCURATE_EXCEPTIONS)))
return;
// Also, nothing to do if the block is not an exception thrower
if (!basicBlock.isExceptionThrower())
return;
// If cached results are up to date, don't recompute.
CachedExceptionSet cachedExceptionSet = getCachedExceptionSet(basicBlock);
if (cachedExceptionSet.isUpToDate((TypeFrame) result))
return;
// Figure out what exceptions can be thrown out
// of the basic block, and mark each exception edge
// with the set of exceptions which can be propagated
// along the edge.
int exceptionEdgeCount = 0;
Edge lastExceptionEdge = null;
for (Iterator<Edge> i = cfg.outgoingEdgeIterator(basicBlock); i.hasNext();) {
Edge e = i.next();
if (e.isExceptionEdge()) {
exceptionEdgeCount++;
lastExceptionEdge = e;
}
}
if (exceptionEdgeCount == 0) {
// System.out.println("Shouldn't all blocks have an exception edge");
return;
}
// Compute exceptions that can be thrown by the
// basic block.
cachedExceptionSet = computeBlockExceptionSet(basicBlock, (TypeFrame) result);
if (exceptionEdgeCount == 1) {
cachedExceptionSet.setEdgeExceptionSet(lastExceptionEdge, cachedExceptionSet.getExceptionSet());
return;
}
// For each outgoing exception edge, compute exceptions
// that can be thrown. This assumes that the exception
// edges are enumerated in decreasing order of priority.
// In the process, this will remove exceptions from
// the thrown exception set.
ExceptionSet thrownExceptionSet = cachedExceptionSet.getExceptionSet();
if (!thrownExceptionSet.isEmpty()) thrownExceptionSet = thrownExceptionSet.duplicate();
for (Iterator<Edge> i = cfg.outgoingEdgeIterator(basicBlock); i.hasNext();) {
Edge edge = i.next();
if (edge.isExceptionEdge())
cachedExceptionSet.setEdgeExceptionSet(edge, computeEdgeExceptionSet(edge, thrownExceptionSet));
}
}
public void meetInto(TypeFrame fact, Edge edge, TypeFrame result) throws DataflowAnalysisException {
BasicBlock basicBlock = edge.getTarget();
if (fact.isValid()) {
TypeFrame tmpFact = null;
// Handling an exception?
if (basicBlock.isExceptionHandler()) {
tmpFact = modifyFrame(fact, tmpFact);
// Special case: when merging predecessor facts for entry to
// an exception handler, we clear the stack and push a
// single entry for the exception object. That way, the locals
// can still be merged.
CodeExceptionGen exceptionGen = basicBlock.getExceptionGen();
tmpFact.clearStack();
// Determine the type of exception(s) caught.
Type catchType = null;
if (FORCE_ACCURATE_EXCEPTIONS ||
AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.ACCURATE_EXCEPTIONS)) {
try {
// Ideally, the exceptions that can be propagated
// on this edge has already been computed.
CachedExceptionSet cachedExceptionSet = getCachedExceptionSet(edge.getSource());
ExceptionSet edgeExceptionSet = cachedExceptionSet.getEdgeExceptionSet(edge);
if (!edgeExceptionSet.isEmpty()) {
//System.out.println("Using computed edge exception set!");
catchType = ExceptionObjectType.fromExceptionSet(edgeExceptionSet);
}
} catch (ClassNotFoundException e) {
lookupFailureCallback.reportMissingClass(e);
}
}
if (catchType == null) {
// No information about propagated exceptions, so
// pick a type conservatively using the handler catch type.
catchType = exceptionGen.getCatchType();
if (catchType == null)
catchType = Type.THROWABLE; // handle catches anything throwable
}
tmpFact.pushValue(catchType);
}
// See if we can make some types more precise due to
// a successful instanceof check in the source block.
if (valueNumberDataflow != null) {
tmpFact = handleInstanceOfBranch(fact, tmpFact, edge);
}
if (tmpFact != null) {
fact = tmpFact;
}
}
mergeInto(fact, result);
}
private TypeFrame handleInstanceOfBranch(TypeFrame fact, TypeFrame tmpFact, Edge edge) throws DataflowAnalysisException {
InstanceOfCheck check = instanceOfCheckMap.get(edge.getSource());
if (check == null) {
//System.out.println("no instanceof check for block " + edge.getSource().getId());
return tmpFact;
}
if (check.getValueNumber() == null) {
//System.out.println("instanceof check for block " + edge.getSource().getId() + " has no value number");
return tmpFact;
}
ValueNumber instanceOfValueNumber = check.getValueNumber();
short branchOpcode = edge.getSource().getLastInstruction().getInstruction().getOpcode();
if ( (edge.getType() == EdgeTypes.IFCMP_EDGE &&
(branchOpcode == Constants.IFNE || branchOpcode == Constants.IFGT))
|| (edge.getType() == EdgeTypes.FALL_THROUGH_EDGE &&
(branchOpcode == Constants.IFEQ || branchOpcode == Constants.IFLE))
) {
//System.out.println("Successful check on edge " + edge);
// Successful instanceof check.
ValueNumberFrame vnaFrame = valueNumberDataflow.getStartFact(edge.getTarget());
if (!vnaFrame.isValid())
return tmpFact;
Type instanceOfType = check.getType();
if (!(instanceOfType instanceof ReferenceType))
return tmpFact;
int numSlots = Math.min(fact.getNumSlots(), vnaFrame.getNumSlots());
for (int i = 0; i < numSlots; ++i) {
if (!vnaFrame.getValue(i).equals(instanceOfValueNumber))
continue;
Type checkedType = fact.getValue(i);
if (!(checkedType instanceof ReferenceType))
continue;
// Only refine the type if the cast is feasible: i.e., a downcast.
// Otherwise, just set it to TOP.
try {
boolean feasibleCheck = Hierarchy.isSubtype(
(ReferenceType) instanceOfType,
(ReferenceType) checkedType);
if (!feasibleCheck && instanceOfType instanceof ObjectType
&& checkedType instanceof ObjectType) {
double v = DeepSubtypeAnalysis.deepInstanceOf(((ObjectType)instanceOfType).getClassName(),
((ObjectType)checkedType).getClassName());
if (v > 0.0) feasibleCheck = true;
}
tmpFact = modifyFrame(fact, tmpFact);
tmpFact.setValue(i, feasibleCheck ? instanceOfType : TopType.instance());
} catch (ClassNotFoundException e) {
lookupFailureCallback.reportMissingClass(e);
throw new MissingClassException(e);
}
}
}
return tmpFact;
}
@Override
protected void mergeValues(TypeFrame otherFrame, TypeFrame resultFrame, int slot) throws DataflowAnalysisException {
Type value = typeMerger.mergeTypes(resultFrame.getValue(slot), otherFrame.getValue(slot));
resultFrame.setValue(slot, value);
// Result type is exact IFF types are identical and both are exact
boolean typesAreIdentical =
otherFrame.getValue(slot).equals(resultFrame.getValue(slot));
boolean bothExact =
resultFrame.isExact(slot) && otherFrame.isExact(slot);
resultFrame.setExact(slot, typesAreIdentical && bothExact);
}
/**
* Get the cached set of exceptions that can be thrown
* from given basic block. If this information hasn't
* been computed yet, then an empty exception set is
* returned.
*
* @param basicBlock the block to get the cached exception set for
* @return the CachedExceptionSet for the block
*/
private CachedExceptionSet getCachedExceptionSet(BasicBlock basicBlock) {
CachedExceptionSet cachedExceptionSet = thrownExceptionSetMap.get(basicBlock);
if (cachedExceptionSet == null) {
// When creating the cached exception type set for the first time:
// - the block result is set to TOP, so it won't match
// any block result that has actually been computed
// using the analysis transfer function
// - the exception set is created as empty (which makes it
// return TOP as its common superclass)
TypeFrame top = createFact();
makeFactTop(top);
cachedExceptionSet = new CachedExceptionSet(top, exceptionSetFactory.createExceptionSet());
thrownExceptionSetMap.put(basicBlock, cachedExceptionSet);
}
return cachedExceptionSet;
}
/**
* Compute the set of exceptions that can be
* thrown from the given basic block.
* This should only be called if the existing cached
* exception set is out of date.
*
* @param basicBlock the basic block
* @param result the result fact for the block; this is used
* to determine whether or not the cached exception
* set is up to date
* @return the cached exception set for the block
*/
private CachedExceptionSet computeBlockExceptionSet(BasicBlock basicBlock, TypeFrame result)
throws DataflowAnalysisException {
ExceptionSet exceptionSet;
try {
exceptionSet = computeThrownExceptionTypes(basicBlock);
} catch (ClassNotFoundException e) {
// Special case: be as conservative as possible
// if a class hierarchy lookup fails.
lookupFailureCallback.reportMissingClass(e);
exceptionSet = exceptionSetFactory.createExceptionSet();
exceptionSet.addExplicit(Type.THROWABLE);
}
TypeFrame copyOfResult = createFact();
copy(result, copyOfResult);
CachedExceptionSet cachedExceptionSet = new CachedExceptionSet(copyOfResult, exceptionSet);
thrownExceptionSetMap.put(basicBlock, cachedExceptionSet);
return cachedExceptionSet;
}
/**
* Based on the set of exceptions that can be thrown
* from the source basic block,
* compute the set of exceptions that can propagate
* along given exception edge. This method should be
* called for each outgoing exception edge in sequence,
* so the caught exceptions can be removed from the
* thrown exception set as needed.
*
* @param edge the exception edge
* @param thrownExceptionSet current set of exceptions that
* can be thrown, taking earlier (higher priority)
* exception edges into account
* @return the set of exceptions that can propagate
* along this edge
*/
private ExceptionSet computeEdgeExceptionSet(Edge edge, ExceptionSet thrownExceptionSet) {
if (thrownExceptionSet.isEmpty()) return thrownExceptionSet;
ExceptionSet result = exceptionSetFactory.createExceptionSet();
if (edge.getType() == UNHANDLED_EXCEPTION_EDGE) {
// The unhandled exception edge always comes
// after all of the handled exception edges.
result.addAll(thrownExceptionSet);
thrownExceptionSet.clear();
return result;
}
BasicBlock handlerBlock = edge.getTarget();
CodeExceptionGen handler = handlerBlock.getExceptionGen();
ObjectType catchType = handler.getCatchType();
if (Hierarchy.isUniversalExceptionHandler(catchType)) {
result.addAll(thrownExceptionSet);
thrownExceptionSet.clear();
} else {
// Go through the set of thrown exceptions.
// Any that will DEFINITELY be caught be this handler, remove.
// Any that MIGHT be caught, but won't definitely be caught,
// remain.
for (ExceptionSet.ThrownExceptionIterator i = thrownExceptionSet.iterator(); i.hasNext();) {
//ThrownException thrownException = i.next();
ObjectType thrownType = i.next();
boolean explicit = i.isExplicit();
if (DEBUG)
System.out.println("\texception type " + thrownType +
", catch type " + catchType);
try {
if (Hierarchy.isSubtype(thrownType, catchType)) {
// Exception can be thrown along this edge
result.add(thrownType, explicit);
// And it will definitely be caught
i.remove();
if (DEBUG)
System.out.println("\tException is subtype of catch type: " +
"will definitely catch");
} else if (Hierarchy.isSubtype(catchType, thrownType)) {
// Exception possibly thrown along this edge
result.add(thrownType, explicit);
if (DEBUG)
System.out.println("\tException is supertype of catch type: " +
"might catch");
}
} catch (ClassNotFoundException e) {
// As a special case, if a class hierarchy lookup
// fails, then we will conservatively assume that the
// exception in question CAN, but WON'T NECESSARILY
// be caught by the handler.
AnalysisContext.reportMissingClass(e);
result.add(thrownType, explicit);
}
}
}
return result;
}
/**
* Compute the set of exception types that can
* be thrown by given basic block.
*
* @param basicBlock the basic block
* @return the set of exceptions that can be thrown by the block
*/
private ExceptionSet computeThrownExceptionTypes(BasicBlock basicBlock)
throws ClassNotFoundException, DataflowAnalysisException {
ExceptionSet exceptionTypeSet = exceptionSetFactory.createExceptionSet();
InstructionHandle pei = basicBlock.getExceptionThrower();
Instruction ins = pei.getInstruction();
// Get the exceptions that BCEL knows about.
// Note that all of these are unchecked.
ExceptionThrower exceptionThrower = (ExceptionThrower) ins;
Class[] exceptionList = exceptionThrower.getExceptions();
for (Class aExceptionList : exceptionList) {
exceptionTypeSet.addImplicit(ObjectTypeFactory.getInstance(aExceptionList.getName()));
}
// Assume that an Error may be thrown by any instruction.
exceptionTypeSet.addImplicit(Hierarchy.ERROR_TYPE);
if (ins instanceof ATHROW) {
// For ATHROW instructions, we generate *two* blocks
// for which the ATHROW is an exception thrower.
// - The first, empty basic block, does the null check
// - The second block, which actually contains the ATHROW,
// throws the object on the top of the operand stack
// We make a special case of the block containing the ATHROW,
// by removing all of the implicit exceptions,
// and using type information to figure out what is thrown.
if (basicBlock.containsInstruction(pei)) {
// This is the actual ATHROW, not the null check
// and implicit exceptions.
exceptionTypeSet.clear();
// The frame containing the thrown value is the start fact
// for the block, because ATHROW is guaranteed to be
// the only instruction in the block.
TypeFrame frame = getStartFact(basicBlock);
// Check whether or not the frame is valid.
// Sun's javac sometimes emits unreachable code.
// For example, it will emit code that follows a JSR
// subroutine call that never returns.
// If the frame is invalid, then we can just make
// a conservative assumption that anything could be
// thrown at this ATHROW.
if (!frame.isValid()) {
exceptionTypeSet.addExplicit(Type.THROWABLE);
} else if (frame.getStackDepth() == 0) {
throw new IllegalStateException("empty stack " +
" thrown by " + pei + " in " +
SignatureConverter.convertMethodSignature(methodGen));
} else {
Type throwType = frame.getTopValue();
if (throwType instanceof ObjectType) {
exceptionTypeSet.addExplicit((ObjectType) throwType);
} else if (throwType instanceof ExceptionObjectType) {
exceptionTypeSet.addAll(((ExceptionObjectType) throwType).getExceptionSet());
} else {
// Not sure what is being thrown here.
// Be conservative.
if (DEBUG) {
System.out.println("Non object type " + throwType +
" thrown by " + pei + " in " +
SignatureConverter.convertMethodSignature(methodGen));
}
exceptionTypeSet.addExplicit(Type.THROWABLE);
}
}
}
}
// If it's an InvokeInstruction, add declared exceptions and RuntimeException
if (ins instanceof InvokeInstruction) {
ConstantPoolGen cpg = methodGen.getConstantPool();
InvokeInstruction inv = (InvokeInstruction) ins;
ObjectType[] declaredExceptionList = Hierarchy.findDeclaredExceptions(inv, cpg);
if (declaredExceptionList == null) {
// Couldn't find declared exceptions,
// so conservatively assume it could thrown any checked exception.
if (DEBUG)
System.out.println("Couldn't find declared exceptions for " +
SignatureConverter.convertMethodSignature(inv, cpg));
exceptionTypeSet.addExplicit(Hierarchy.EXCEPTION_TYPE);
} else {
for (ObjectType aDeclaredExceptionList : declaredExceptionList) {
exceptionTypeSet.addExplicit(aDeclaredExceptionList);
}
}
exceptionTypeSet.addImplicit(Hierarchy.RUNTIME_EXCEPTION_TYPE);
}
if (DEBUG) System.out.println(pei + " can throw " + exceptionTypeSet);
return exceptionTypeSet;
}
public static void main(String[] argv) throws Exception {
if (argv.length != 1) {
System.err.println("Usage: " + TypeAnalysis.class.getName() + " <class file>");
System.exit(1);
}
DataflowTestDriver<TypeFrame, TypeAnalysis> driver = new DataflowTestDriver<TypeFrame, TypeAnalysis>() {
@Override
public Dataflow<TypeFrame, TypeAnalysis> createDataflow(ClassContext classContext, Method method)
throws CFGBuilderException, DataflowAnalysisException {
return classContext.getTypeDataflow(method);
}
};
driver.execute(argv[0]);
}
}
// vim:ts=3 |
package edu.umd.cs.findbugs.detect;
import java.util.BitSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ATHROW;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.FindBugsAnalysisFeatures;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.DataflowValueChooser;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.Hierarchy;
import edu.umd.cs.findbugs.ba.JavaClassAndMethod;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.MissingClassException;
import edu.umd.cs.findbugs.ba.NullnessAnnotation;
import edu.umd.cs.findbugs.ba.NullnessAnnotationDatabase;
import edu.umd.cs.findbugs.ba.SignatureConverter;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.interproc.PropertyDatabase;
import edu.umd.cs.findbugs.ba.npe.IsNullValue;
import edu.umd.cs.findbugs.ba.npe.IsNullValueDataflow;
import edu.umd.cs.findbugs.ba.npe.IsNullValueFrame;
import edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonCollector;
import edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonFinder;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessProperty;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessPropertyDatabase;
import edu.umd.cs.findbugs.ba.npe.RedundantBranch;
import edu.umd.cs.findbugs.ba.type.TypeDataflow;
import edu.umd.cs.findbugs.ba.type.TypeFrame;
import edu.umd.cs.findbugs.ba.vna.ValueNumber;
import edu.umd.cs.findbugs.ba.vna.ValueNumberDataflow;
import edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;
import edu.umd.cs.findbugs.props.GeneralWarningProperty;
import edu.umd.cs.findbugs.props.WarningPropertySet;
import edu.umd.cs.findbugs.props.WarningPropertyUtil;
/**
* A Detector to find instructions where a NullPointerException
* might be raised. We also look for useless reference comparisons
* involving null and non-null values.
*
* @author David Hovemeyer
* @author William Pugh
* @see edu.umd.cs.findbugs.ba.npe.IsNullValueAnalysis
*/
public class FindNullDeref
implements Detector, NullDerefAndRedundantComparisonCollector {
private static final boolean DEBUG = Boolean.getBoolean("fnd.debug");
private static final boolean DEBUG_NULLARG = Boolean.getBoolean("fnd.debug.nullarg");
private static final boolean DEBUG_NULLRETURN = Boolean.getBoolean("fnd.debug.nullreturn");
private static final boolean REPORT_SAFE_METHOD_TARGETS = true;
private static final String METHOD = System.getProperty("fnd.method");
// Fields
private BugReporter bugReporter;
// Cached database stuff
private ParameterNullnessPropertyDatabase unconditionalDerefParamDatabase;
private boolean checkUnconditionalDeref;
private boolean checkedDatabases = false;
// Transient state
private ClassContext classContext;
private Method method;
private IsNullValueDataflow invDataflow;
private BitSet previouslyDeadBlocks;
private NullnessAnnotation methodAnnotation;
public FindNullDeref(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visitClassContext(ClassContext classContext) {
this.classContext = classContext;
try {
JavaClass jclass = classContext.getJavaClass();
Method[] methodList = jclass.getMethods();
for (Method method : methodList) {
if (method.isAbstract() || method.isNative() || method.getCode() == null)
continue;
if (METHOD != null && !method.getName().equals(METHOD))
continue;
if (DEBUG) System.out.println("Checking for NP in " + method.getName());
analyzeMethod(classContext, method);
}
} catch (MissingClassException e) {
bugReporter.reportMissingClass(e.getClassNotFoundException());
} catch (DataflowAnalysisException e) {
bugReporter.logError("FindNullDeref caught dae exception", e);
} catch (CFGBuilderException e) {
bugReporter.logError("FindNullDeref caught cfgb exception", e);
}
}
private void analyzeMethod(ClassContext classContext, Method method)
throws CFGBuilderException, DataflowAnalysisException {
MethodGen methodGen = classContext.getMethodGen(method);
if (methodGen == null)
return;
if (!checkedDatabases) {
checkDatabases();
checkedDatabases = true;
}
this.method = method;
this.methodAnnotation = getMethodNullnessAnnotation();
if (DEBUG || DEBUG_NULLARG)
System.out.println("FND: " + SignatureConverter.convertMethodSignature(methodGen));
this.previouslyDeadBlocks = findPreviouslyDeadBlocks();
// Get the IsNullValueDataflow for the method from the ClassContext
invDataflow = classContext.getIsNullValueDataflow(method);
// Create a NullDerefAndRedundantComparisonFinder object to do the actual
// work. It will call back to report null derefs and redundant null comparisons
// through the NullDerefAndRedundantComparisonCollector interface we implement.
NullDerefAndRedundantComparisonFinder worker = new NullDerefAndRedundantComparisonFinder(
classContext,
method,
invDataflow,
this);
worker.execute();
checkCallSitesAndReturnInstructions();
}
/**
* Find set of blocks which were known to be dead before doing the
* null pointer analysis.
*
* @return set of previously dead blocks, indexed by block id
* @throws CFGBuilderException
* @throws DataflowAnalysisException
*/
private BitSet findPreviouslyDeadBlocks() throws DataflowAnalysisException, CFGBuilderException {
BitSet deadBlocks = new BitSet();
ValueNumberDataflow vnaDataflow = classContext.getValueNumberDataflow(method);
for (Iterator<BasicBlock> i = vnaDataflow.getCFG().blockIterator(); i.hasNext();) {
BasicBlock block = i.next();
ValueNumberFrame vnaFrame = vnaDataflow.getStartFact(block);
if (vnaFrame.isTop()) {
deadBlocks.set(block.getId());
}
}
return deadBlocks;
}
/**
* Check whether or not the various interprocedural databases we can
* use exist and are nonempty.
*/
private void checkDatabases() {
AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext();
unconditionalDerefParamDatabase = analysisContext.getUnconditionalDerefParamDatabase();
}
private<
DatabaseType extends PropertyDatabase<?,?>> boolean isDatabaseNonEmpty(DatabaseType database) {
return database != null && !database.isEmpty();
}
/**
* See if the currently-visited method declares a @NonNull annotation,
* or overrides a method which declares a @NonNull annotation.
*/
private NullnessAnnotation getMethodNullnessAnnotation() {
if (method.getSignature().indexOf(")L") >= 0 || method.getSignature().indexOf(")[") >= 0 ) {
if (DEBUG_NULLRETURN) {
System.out.println("Checking return annotation for " +
SignatureConverter.convertMethodSignature(classContext.getJavaClass(), method));
}
XMethod m = XFactory.createXMethod(classContext.getJavaClass(), method);
return AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase()
.getResolvedAnnotation(m, false);
}
return NullnessAnnotation.UNKNOWN_NULLNESS;
}
private void checkCallSitesAndReturnInstructions()
throws CFGBuilderException, DataflowAnalysisException {
ConstantPoolGen cpg = classContext.getConstantPoolGen();
TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
for (Iterator<Location> i = classContext.getCFG(method).locationIterator(); i.hasNext();) {
Location location = i.next();
Instruction ins = location.getHandle().getInstruction();
try {
if (ins instanceof InvokeInstruction) {
examineCallSite(location, cpg, typeDataflow);
} else if (methodAnnotation == NullnessAnnotation.NONNULL && ins.getOpcode() == Constants.ARETURN) {
examineReturnInstruction(location);
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
}
}
private void examineCallSite(
Location location,
ConstantPoolGen cpg,
TypeDataflow typeDataflow)
throws DataflowAnalysisException, CFGBuilderException, ClassNotFoundException {
InvokeInstruction invokeInstruction = (InvokeInstruction)
location.getHandle().getInstruction();
if (DEBUG_NULLARG) {
// System.out.println("Examining call site: " + location.getHandle());
}
String methodName = invokeInstruction.getName(cpg);
String signature = invokeInstruction.getSignature(cpg);
// Don't check equals() calls.
// If an equals() call unconditionally dereferences the parameter,
// it is the fault of the method, not the caller.
if (methodName.equals("equals") && signature.equals("(Ljava/lang/Object;)Z"))
return;
int returnTypeStart = signature.indexOf(')');
if (returnTypeStart < 0)
return;
String paramList = signature.substring(0, returnTypeStart + 1);
if (paramList.equals("()") ||
(paramList.indexOf("L") < 0 && paramList.indexOf('[') < 0))
// Method takes no arguments, or takes no reference arguments
return;
// See if any null arguments are passed
IsNullValueFrame frame =
classContext.getIsNullValueDataflow(method).getFactAtLocation(location);
if (!frame.isValid())
return;
BitSet nullArgSet = frame.getArgumentSet(invokeInstruction, cpg, new DataflowValueChooser<IsNullValue>() {
public boolean choose(IsNullValue value) {
// Only choose non-exception values.
// Values null on an exception path might be due to
// infeasible control flow.
return value.mightBeNull() && !value.isException();
}
});
BitSet definitelyNullArgSet = frame.getArgumentSet(invokeInstruction, cpg, new DataflowValueChooser<IsNullValue>() {
public boolean choose(IsNullValue value) {
return value.isDefinitelyNull();
}
});
if (nullArgSet.isEmpty())
return;
if (DEBUG_NULLARG) {
System.out.println("Null arguments passed: " + nullArgSet);
System.out.println("Frame is: " + frame);
System.out.println("# arguments: " + frame.getNumArguments(invokeInstruction, cpg));
XMethod xm = XFactory.createXMethod(invokeInstruction, cpg);
System.out.print("Signature: " + xm.getSignature());
}
if (unconditionalDerefParamDatabase != null) {
checkUnconditionallyDereferencedParam(location, cpg, typeDataflow, invokeInstruction, nullArgSet, definitelyNullArgSet);
}
if (DEBUG_NULLARG) {
System.out.println("Checking nonnull params");
}
checkNonNullParam(location, cpg, typeDataflow, invokeInstruction, nullArgSet, definitelyNullArgSet);
}
private void examineReturnInstruction(Location location) throws DataflowAnalysisException, CFGBuilderException {
if (DEBUG_NULLRETURN) {
System.out.println("Checking null return at " + location);
}
IsNullValueDataflow invDataflow = classContext.getIsNullValueDataflow(method);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
if (!frame.isValid())
return;
IsNullValue tos = frame.getTopValue();
if (tos.mightBeNull()) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance warning = new BugInstance("NP_NONNULL_RETURN_VIOLATION", tos.isDefinitelyNull() ?
HIGH_PRIORITY : NORMAL_PRIORITY)
.addClassAndMethod(methodGen, sourceFile)
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
bugReporter.reportBug(warning);
}
}
private void checkUnconditionallyDereferencedParam(
Location location,
ConstantPoolGen cpg,
TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction,
BitSet nullArgSet, BitSet definitelyNullArgSet) throws DataflowAnalysisException, ClassNotFoundException {
// See what methods might be called here
TypeFrame typeFrame = typeDataflow.getFactAtLocation(location);
Set<JavaClassAndMethod> targetMethodSet = Hierarchy.resolveMethodCallTargets(invokeInstruction, typeFrame, cpg);
if (DEBUG_NULLARG) {
System.out.println("Possibly called methods: " + targetMethodSet);
}
// See if any call targets unconditionally dereference one of the null arguments
BitSet unconditionallyDereferencedNullArgSet = new BitSet();
List<JavaClassAndMethod> dangerousCallTargetList = new LinkedList<JavaClassAndMethod>();
List<JavaClassAndMethod> veryDangerousCallTargetList = new LinkedList<JavaClassAndMethod>();
for (JavaClassAndMethod targetMethod : targetMethodSet) {
if (DEBUG_NULLARG) {
System.out.println("For target method " + targetMethod);
}
ParameterNullnessProperty property = unconditionalDerefParamDatabase.getProperty(targetMethod.toXMethod());
if (property == null)
continue;
if (DEBUG_NULLARG) {
System.out.println("\tUnconditionally dereferenced params: " + property);
}
BitSet targetUnconditionallyDereferencedNullArgSet =
property.getViolatedParamSet(nullArgSet);
if (targetUnconditionallyDereferencedNullArgSet.isEmpty())
continue;
dangerousCallTargetList.add(targetMethod);
unconditionallyDereferencedNullArgSet.or(targetUnconditionallyDereferencedNullArgSet);
if (!property.getViolatedParamSet(definitelyNullArgSet).isEmpty())
veryDangerousCallTargetList.add(targetMethod);
}
if (dangerousCallTargetList.isEmpty())
return;
WarningPropertySet propertySet = new WarningPropertySet();
// See if there are any safe targets
Set<JavaClassAndMethod> safeCallTargetSet = new HashSet<JavaClassAndMethod>();
safeCallTargetSet.addAll(targetMethodSet);
safeCallTargetSet.removeAll(dangerousCallTargetList);
if (safeCallTargetSet.isEmpty()) {
propertySet.addProperty(NullArgumentWarningProperty.ALL_DANGEROUS_TARGETS);
if (dangerousCallTargetList.size() == 1) {
propertySet.addProperty(NullArgumentWarningProperty.MONOMORPHIC_CALL_SITE);
}
}
// Call to private method? In theory there should be only one possible target.
boolean privateCall =
safeCallTargetSet.isEmpty()
&& dangerousCallTargetList.size() == 1
&& dangerousCallTargetList.get(0).getMethod().isPrivate();
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
String bugType;
int priority;
if (privateCall
|| invokeInstruction.getOpcode() == Constants.INVOKESTATIC
|| invokeInstruction.getOpcode() == Constants.INVOKESPECIAL) {
bugType = "NP_NULL_PARAM_DEREF_NONVIRTUAL";
priority = HIGH_PRIORITY;
} else if (safeCallTargetSet.isEmpty()) {
bugType = "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS";
priority = NORMAL_PRIORITY;
} else {
bugType = "NP_NULL_PARAM_DEREF";
priority = LOW_PRIORITY;
}
if (dangerousCallTargetList.size() > veryDangerousCallTargetList.size())
priority++;
else
propertySet.addProperty(NullArgumentWarningProperty.ACTUAL_PARAMETER_GUARANTEED_NULL);
BugInstance warning = new BugInstance(bugType, priority)
.addClassAndMethod(methodGen, sourceFile)
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle())
.addMethod(XFactory.createXMethod(invokeInstruction, cpg)).describe("METHOD_CALLED");
// Check which params might be null
addParamAnnotations(definitelyNullArgSet, unconditionallyDereferencedNullArgSet, propertySet, warning);
// Add annotations for dangerous method call targets
for (JavaClassAndMethod dangerousCallTarget : veryDangerousCallTargetList) {
warning.addMethod(dangerousCallTarget).describe("METHOD_DANGEROUS_TARGET_ACTUAL_GUARANTEED_NULL");
}
dangerousCallTargetList.removeAll(veryDangerousCallTargetList);
// Add annotations for dangerous method call targets
for (JavaClassAndMethod dangerousCallTarget : dangerousCallTargetList) {
warning.addMethod(dangerousCallTarget).describe("METHOD_DANGEROUS_TARGET");
}
// Add safe method call targets.
// This is useful to see which other call targets the analysis
// considered.
for (JavaClassAndMethod safeMethod : safeCallTargetSet) {
warning.addMethod(safeMethod).describe("METHOD_SAFE_TARGET");
}
decorateWarning(location, propertySet, warning);
bugReporter.reportBug(warning);
}
private void decorateWarning(Location location, WarningPropertySet propertySet, BugInstance warning) {
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
}
propertySet.decorateBugInstance(warning);
}
private void addParamAnnotations(
BitSet definitelyNullArgSet,
BitSet violatedParamSet,
WarningPropertySet propertySet,
BugInstance warning) {
for (int i = 0; i < 32; ++i) {
if (violatedParamSet.get(i)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (definitelyNull) {
propertySet.addProperty(NullArgumentWarningProperty.ARG_DEFINITELY_NULL);
}
// Note: we report params as being indexed starting from 1, not 0
warning.addInt(i + 1).describe(
definitelyNull ? "INT_NULL_ARG" : "INT_MAYBE_NULL_ARG");
}
}
}
/**
* We have a method invocation in which a possibly or definitely null
* parameter is passed. Check it against the library of nonnull annotations.
*
* @param location
* @param cpg
* @param typeDataflow
* @param invokeInstruction
* @param nullArgSet
* @param definitelyNullArgSet
* @throws ClassNotFoundException
*/
private void checkNonNullParam(
Location location,
ConstantPoolGen cpg,
TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction,
BitSet nullArgSet,
BitSet definitelyNullArgSet) throws ClassNotFoundException {
XMethod m = XFactory.createXMethod(invokeInstruction, cpg);
NullnessAnnotationDatabase db
= AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase();
for(int i=nullArgSet.nextSetBit(0); i>=0; i=nullArgSet.nextSetBit(i+1)) {
int paramNum = 0;
String signature = invokeInstruction.getSignature(cpg);
Type[] args = Type.getArgumentTypes(signature);
int words =0;
while (words < i)
words += args[paramNum++].getSize();
if (db.parameterMustBeNonNull(m, paramNum)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (DEBUG_NULLARG) {
System.out.println("QQQ2: " + i + " -- " + paramNum + " is null");
System.out.println("QQQ nullArgSet: " + nullArgSet);
System.out.println("QQQ dnullArgSet: " + definitelyNullArgSet);
}
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance warning = new BugInstance("NP_NONNULL_PARAM_VIOLATION",
definitelyNull ? HIGH_PRIORITY : NORMAL_PRIORITY)
.addClassAndMethod(methodGen, sourceFile)
.addMethod(m).describe("METHOD_CALLED")
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
warning.addInt(i).describe("INT_NONNULL_PARAM");
bugReporter.reportBug(warning);
}
}
}
public void report() {
}
public void foundNullDeref(Location location, ValueNumber valueNumber, IsNullValue refValue) {
WarningPropertySet propertySet = new WarningPropertySet();
boolean onExceptionPath = refValue.isException();
if (onExceptionPath) {
propertySet.addProperty(GeneralWarningProperty.ON_EXCEPTION_PATH);
}
if (refValue.isDefinitelyNull()) {
String type = onExceptionPath ? "NP_ALWAYS_NULL_EXCEPTION" : "NP_ALWAYS_NULL";
int priority = onExceptionPath ? NORMAL_PRIORITY : HIGH_PRIORITY;
reportNullDeref(propertySet, classContext, method, location, type, priority);
} else if (refValue.isNullOnSomePath()) {
String type = onExceptionPath ? "NP_NULL_ON_SOME_PATH_EXCEPTION" : "NP_NULL_ON_SOME_PATH";
int priority = onExceptionPath ? LOW_PRIORITY : NORMAL_PRIORITY;
if (refValue.isReturnValue())
type = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE";
if (DEBUG) System.out.println("Reporting null on some path: value=" + refValue);
reportNullDeref(propertySet, classContext, method, location, type, priority);
}
}
private void reportNullDeref(
WarningPropertySet propertySet,
ClassContext classContext,
Method method,
Location location,
String type,
int priority) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance bugInstance = new BugInstance(this, type, priority)
.addClassAndMethod(methodGen, sourceFile)
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
if (DEBUG)
bugInstance.addInt(location.getHandle().getPosition()).describe("INT_BYTECODE_OFFSET");
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
propertySet.decorateBugInstance(bugInstance);
}
bugReporter.reportBug(bugInstance);
}
public static boolean isThrower(BasicBlock target) {
InstructionHandle ins = target.getFirstInstruction();
int maxCount = 7;
while (ins != null) {
if (maxCount-- <= 0) break;
Instruction i = ins.getInstruction();
if (i instanceof ATHROW) {
return true;
}
if (i instanceof InstructionTargeter
|| i instanceof ReturnInstruction) return false;
ins = ins.getNext();
}
return false;
}
public void foundRedundantNullCheck(Location location, RedundantBranch redundantBranch) {
String sourceFile = classContext.getJavaClass().getSourceFileName();
MethodGen methodGen = classContext.getMethodGen(method);
boolean isChecked = redundantBranch.firstValue.isChecked();
boolean wouldHaveBeenAKaboom = redundantBranch.firstValue.wouldHaveBeenAKaboom();
Location locationOfKaBoom = redundantBranch.firstValue.getLocationOfKaBoom();
boolean createdDeadCode = false;
boolean infeasibleEdgeSimplyThrowsException = false;
Edge infeasibleEdge = redundantBranch.infeasibleEdge;
if (infeasibleEdge != null) {
if (DEBUG) System.out.println("Check if " + redundantBranch + " creates dead code");
BasicBlock target = infeasibleEdge.getTarget();
if (DEBUG) System.out.println("Target block is " + (target.isExceptionThrower() ? " exception thrower" : " not exception thrower"));
// If the block is empty, it probably doesn't matter that it was killed.
// FIXME: really, we should crawl the immediately reachable blocks
// starting at the target block to see if any of them are dead and nonempty.
boolean empty = !target.isExceptionThrower() &&
(target.isEmpty() || isGoto(target.getFirstInstruction().getInstruction()));
if (!empty) {
try {
if (classContext.getCFG(method).getNumIncomingEdges(target) > 1) {
if (DEBUG) System.out.println("Target of infeasible edge has multiple incoming edges");
empty = true;
}}
catch (CFGBuilderException e) {
assert true; // ignore it
}
}
if (DEBUG) System.out.println("Target block is " + (empty ? "empty" : "not empty"));
if (!empty) {
if (isThrower(target)) infeasibleEdgeSimplyThrowsException = true;
}
if (!empty && !previouslyDeadBlocks.get(target.getId())) {
if (DEBUG) System.out.println("target was alive previously");
// Block was not dead before the null pointer analysis.
// See if it is dead now by inspecting the null value frame.
// If it's TOP, then the block became dead.
IsNullValueFrame invFrame = invDataflow.getStartFact(target);
createdDeadCode = invFrame.isTop();
if (DEBUG) System.out.println("target is now " + (createdDeadCode ? "dead" : "alive"));
}
}
int priority;
boolean valueIsNull = true;
String warning;
if (redundantBranch.secondValue == null) {
if (redundantBranch.firstValue.isDefinitelyNull() ) {
warning = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE";
priority = NORMAL_PRIORITY;
}
else {
warning = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE";
valueIsNull = false;
priority = isChecked ? NORMAL_PRIORITY : LOW_PRIORITY;
}
} else {
boolean bothNull = redundantBranch.firstValue.isDefinitelyNull() && redundantBranch.secondValue.isDefinitelyNull();
if (redundantBranch.secondValue.isChecked()) isChecked = true;
if (redundantBranch.secondValue.wouldHaveBeenAKaboom()) wouldHaveBeenAKaboom = true;
if (bothNull) {
warning = "RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES";
priority = NORMAL_PRIORITY;
}
else {
warning = "RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE";
priority = isChecked ? NORMAL_PRIORITY : LOW_PRIORITY;
}
}
if (wouldHaveBeenAKaboom) {
priority = HIGH_PRIORITY;
warning = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE";
if (locationOfKaBoom == null) throw new NullPointerException("location of KaBoom is null");
}
if (DEBUG) System.out.println(createdDeadCode + " " + infeasibleEdgeSimplyThrowsException + " " + valueIsNull + " " + priority);
if (createdDeadCode && !infeasibleEdgeSimplyThrowsException) {
priority += 0;
} else if (createdDeadCode && infeasibleEdgeSimplyThrowsException) {
// throw clause
if (valueIsNull)
priority += 0;
else
priority += 1;
} else {
// didn't create any dead code
priority += 1;
}
if (DEBUG) {
System.out.println("RCN" + priority + " "
+ redundantBranch.firstValue + " =? "
+ redundantBranch.secondValue
+ " : " + warning
);
if (isChecked) System.out.println("isChecked");
if (wouldHaveBeenAKaboom) System.out.println("wouldHaveBeenAKaboom");
if (createdDeadCode) System.out.println("createdDeadCode");
}
BugInstance bugInstance =
new BugInstance(this, warning, priority)
.addClassAndMethod(methodGen, sourceFile);
if (wouldHaveBeenAKaboom)
bugInstance.addSourceLine(classContext, methodGen, sourceFile, locationOfKaBoom.getHandle());
bugInstance.addSourceLine(classContext, methodGen, sourceFile, location.getHandle()).describe("SOURCE_REDUNDANT_NULL_CHECK");
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertySet propertySet = new WarningPropertySet();
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
if (isChecked)
propertySet.addProperty(NullDerefProperty.CHECKED_VALUE);
if (wouldHaveBeenAKaboom)
propertySet.addProperty(NullDerefProperty.WOULD_HAVE_BEEN_A_KABOOM);
if (createdDeadCode)
propertySet.addProperty(NullDerefProperty.CREATED_DEAD_CODE);
propertySet.decorateBugInstance(bugInstance);
priority = propertySet.computePriority(NORMAL_PRIORITY);
bugInstance.setPriority(priority);
}
bugReporter.reportBug(bugInstance);
}
/**
* Determine whether or not given instruction is a goto.
*
* @param instruction the instruction
* @return true if the instruction is a goto, false otherwise
*/
private boolean isGoto(Instruction instruction) {
return instruction.getOpcode() == Constants.GOTO
|| instruction.getOpcode() == Constants.GOTO_W;
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs.detect;
import java.util.BitSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LineNumberTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.MethodGen;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.FindBugsAnalysisProperties;
import edu.umd.cs.findbugs.StatelessDetector;
import edu.umd.cs.findbugs.WarningSuppressor;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisException;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.IsNullValue;
import edu.umd.cs.findbugs.ba.IsNullValueAnalysis;
import edu.umd.cs.findbugs.ba.IsNullValueDataflow;
import edu.umd.cs.findbugs.ba.IsNullValueFrame;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.SignatureConverter;
import edu.umd.cs.findbugs.props.GeneralWarningProperty;
import edu.umd.cs.findbugs.props.WarningPropertySet;
import edu.umd.cs.findbugs.props.WarningPropertyUtil;
/**
* A Detector to find instructions where a NullPointerException
* might be raised. We also look for useless reference comparisons
* involving null and non-null values.
*
* @author David Hovemeyer
* @see IsNullValueAnalysis
*/
public class FindNullDeref implements Detector, StatelessDetector {
/**
* An instruction recorded as a redundant reference comparison.
* We keep track of the line number, in order to ensure that if
* the branch was duplicated, all duplicates are determined in
* the same way. (If they aren't, then we don't report it.)
*/
private static class RedundantBranch {
public final Location location;
public final int lineNumber;
public boolean checkedValue;
public RedundantBranch(Location location, int lineNumber, boolean checkedValue) {
this.location = location;
this.lineNumber = lineNumber;
this.checkedValue = checkedValue;
}
public String toString() {
return location.toString() + ": line " + lineNumber;
}
}
private static final boolean DEBUG = Boolean.getBoolean("fnd.debug");
private BugReporter bugReporter;
private List<RedundantBranch> redundantBranchList;
private BitSet definitelySameBranchSet;
private BitSet definitelyDifferentBranchSet;
private BitSet undeterminedBranchSet;
public FindNullDeref(BugReporter bugReporter) {
this.bugReporter = bugReporter;
this.redundantBranchList = new LinkedList<RedundantBranch>();
this.definitelySameBranchSet = new BitSet();
this.definitelyDifferentBranchSet = new BitSet();
this.undeterminedBranchSet = new BitSet();
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public void setAnalysisContext(AnalysisContext analysisContext) {
}
public void visitClassContext(ClassContext classContext) {
try {
JavaClass jclass = classContext.getJavaClass();
Method[] methodList = jclass.getMethods();
for (int i = 0; i < methodList.length; ++i) {
Method method = methodList[i];
if (method.isAbstract() || method.isNative() || method.getCode() == null)
continue;
analyzeMethod(classContext, method);
}
} catch (DataflowAnalysisException e) {
throw new AnalysisException("FindNullDeref caught exception: " + e, e);
} catch (CFGBuilderException e) {
throw new AnalysisException(e.getMessage());
}
}
private void analyzeMethod(ClassContext classContext, Method method)
throws CFGBuilderException, DataflowAnalysisException {
if (DEBUG) System.out.println("Clearing redundant branch information");
redundantBranchList.clear();
definitelySameBranchSet.clear();
definitelyDifferentBranchSet.clear();
undeterminedBranchSet.clear();
if (DEBUG)
System.out.println(SignatureConverter.convertMethodSignature(classContext.getMethodGen(method)));
// Get the IsNullValueAnalysis for the method from the ClassContext
IsNullValueDataflow invDataflow = classContext.getIsNullValueDataflow(method);
// Look for null check blocks where the reference being checked
// is definitely null, or null on some path
Iterator<BasicBlock> bbIter = invDataflow.getCFG().blockIterator();
while (bbIter.hasNext()) {
BasicBlock basicBlock = bbIter.next();
if (basicBlock.isNullCheck()) {
analyzeNullCheck(classContext, method, invDataflow, basicBlock);
} else if (!basicBlock.isEmpty()) {
// Look for all reference comparisons where
// - both values compared are definitely null, or
// - one value is definitely null and one is definitely not null
// These cases are not null dereferences,
// but they are quite likely to indicate an error, so while we've got
// information about null values, we may as well report them.
InstructionHandle lastHandle = basicBlock.getLastInstruction();
Instruction last = lastHandle.getInstruction();
switch (last.getOpcode()) {
case Constants.IF_ACMPEQ:
case Constants.IF_ACMPNE:
analyzeRefComparisonBranch(method, invDataflow, basicBlock, lastHandle);
break;
case Constants.IFNULL:
case Constants.IFNONNULL:
analyzeIfNullBranch(method, invDataflow, basicBlock, lastHandle);
break;
}
}
}
Iterator<RedundantBranch> i = redundantBranchList.iterator();
while (i.hasNext()) {
RedundantBranch redundantBranch = i.next();
if (DEBUG) System.out.println("Redundant branch: " + redundantBranch);
int lineNumber = redundantBranch.lineNumber;
// The source to bytecode compiler may sometimes duplicate blocks of
// code along different control paths. So, to report the bug,
// we check to ensure that the branch is REALLY determined each
// place it is duplicated, and that it is determined in the same way.
if (!undeterminedBranchSet.get(lineNumber) &&
!(definitelySameBranchSet.get(lineNumber) && definitelyDifferentBranchSet.get(lineNumber))) {
reportRedundantNullCheck(classContext, method, redundantBranch.location, redundantBranch);
}
}
}
private void analyzeNullCheck(ClassContext classContext, Method method, IsNullValueDataflow invDataflow,
BasicBlock basicBlock)
throws DataflowAnalysisException {
// Look for null checks where the value checked is definitely
// null or null on some path.
InstructionHandle exceptionThrowerHandle = basicBlock.getExceptionThrower();
Instruction exceptionThrower = exceptionThrowerHandle.getInstruction();
// Figurinformation out where the reference operand is in the stack frame.
int consumed = exceptionThrower.consumeStack(classContext.getConstantPoolGen());
if (consumed == Constants.UNPREDICTABLE)
throw new DataflowAnalysisException("Unpredictable stack consumption for " + exceptionThrower);
// Get the stack values at entry to the null check.
IsNullValueFrame frame = invDataflow.getStartFact(basicBlock);
if (!frame.isValid())
return;
// Could the reference be null?
IsNullValue refValue = frame.getValue(frame.getNumSlots() - consumed);
if (!refValue.mightBeNull())
return;
// Issue a warning
issueNullDerefWarning(classContext, method, new Location(exceptionThrowerHandle, basicBlock), refValue);
}
private void issueNullDerefWarning(
ClassContext classContext,
Method method,
Location location,
IsNullValue refValue) {
WarningPropertySet propertySet = new WarningPropertySet();
boolean onExceptionPath = refValue.isException();
if (onExceptionPath) {
propertySet.addProperty(GeneralWarningProperty.ON_EXCEPTION_PATH);
}
if (refValue.isDefinitelyNull()) {
String type = onExceptionPath ? "NP_ALWAYS_NULL_EXCEPTION" : "NP_ALWAYS_NULL";
int priority = onExceptionPath ? LOW_PRIORITY : HIGH_PRIORITY;
reportNullDeref(propertySet, classContext, method, location, type, priority);
} else if (refValue.isNullOnSomePath()) {
String type = onExceptionPath ? "NP_NULL_ON_SOME_PATH_EXCEPTION" : "NP_NULL_ON_SOME_PATH";
int priority = onExceptionPath ? LOW_PRIORITY : NORMAL_PRIORITY;
if (DEBUG) System.out.println("Reporting null on some path: value=" + refValue);
reportNullDeref(propertySet, classContext, method, location, type, priority);
}
}
private void analyzeRefComparisonBranch(
Method method,
IsNullValueDataflow invDataflow,
BasicBlock basicBlock,
InstructionHandle lastHandle) throws DataflowAnalysisException {
Location location = new Location(lastHandle, basicBlock);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
if (!frame.isValid()) {
// Probably dead code due to pruning infeasible exception edges.
return;
}
if (frame.getStackDepth() < 2)
throw new AnalysisException("Stack underflow at " + lastHandle);
// Find the line number.
int lineNumber = getLineNumber(method, lastHandle);
if (lineNumber < 0)
return;
int numSlots = frame.getNumSlots();
IsNullValue top = frame.getValue(numSlots - 1);
IsNullValue topNext = frame.getValue(numSlots - 2);
boolean definitelySame = top.isDefinitelyNull() && topNext.isDefinitelyNull();
boolean definitelyDifferent =
(top.isDefinitelyNull() && topNext.isDefinitelyNotNull()) ||
(top.isDefinitelyNotNull() && topNext.isDefinitelyNull());
if (definitelySame || definitelyDifferent) {
if (definitelySame) {
if (DEBUG) System.out.println("Line " + lineNumber + " always same");
definitelySameBranchSet.set(lineNumber);
}
if (definitelyDifferent) {
if (DEBUG) System.out.println("Line " + lineNumber + " always different");
definitelyDifferentBranchSet.set(lineNumber);
}
// If at least one of the values compared was
// the result of an explicit null value or null check,
// remember it. We report these cases as low
// priority.
boolean checkedValue = top.isChecked() || topNext.isChecked();
//reportRedundantNullCheck(classContext, method, lastHandle);
RedundantBranch redundantBranch = new RedundantBranch(location, lineNumber, checkedValue);
if (DEBUG) System.out.println("Adding redundant branch: " + redundantBranch);
redundantBranchList.add(redundantBranch);
} else {
if (DEBUG) System.out.println("Line " + lineNumber + " undetermined");
undeterminedBranchSet.set(lineNumber);
}
}
// This is called for both IFNULL and IFNONNULL instructions.
private void analyzeIfNullBranch(
Method method,
IsNullValueDataflow invDataflow,
BasicBlock basicBlock,
InstructionHandle lastHandle) throws DataflowAnalysisException {
Location location = new Location(lastHandle, basicBlock);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
if (!frame.isValid()) {
// This is probably dead code due to an infeasible exception edge.
return;
}
IsNullValue top = frame.getTopValue();
// Find the line number.
int lineNumber = getLineNumber(method, lastHandle);
if (lineNumber < 0)
return;
if (!(top.isDefinitelyNull() || top.isDefinitelyNotNull())) {
if (DEBUG) System.out.println("Line " + lineNumber + " undetermined");
undeterminedBranchSet.set(lineNumber);
return;
}
// Figure out if the branch is always taken
// or always not taken.
short opcode = lastHandle.getInstruction().getOpcode();
boolean definitelySame = top.isDefinitelyNull();
if (opcode != Constants.IFNULL) definitelySame = !definitelySame;
if (definitelySame) {
if (DEBUG) System.out.println("Line " + lineNumber + " always same");
definitelySameBranchSet.set(lineNumber);
} else {
if (DEBUG) System.out.println("Line " + lineNumber + " always different");
definitelyDifferentBranchSet.set(lineNumber);
}
// Is this a null check made redundant by an earlier check?
// Such code is not as likely to be an error
// as when a check is done after an explicit dereference.
boolean redundantNullCheck = top.isChecked();
RedundantBranch redundantBranch = new RedundantBranch(location, lineNumber, redundantNullCheck);
if (DEBUG) System.out.println("Adding redundant branch: " + redundantBranch);
redundantBranchList.add(redundantBranch);
}
private static int getLineNumber(Method method, InstructionHandle handle) {
LineNumberTable table = method.getCode().getLineNumberTable();
if (table == null)
return -1;
return table.getSourceLine(handle.getPosition());
}
private void reportNullDeref(
WarningPropertySet propertySet,
ClassContext classContext,
Method method,
Location location,
String type,
int priority) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance bugInstance = new BugInstance(this, type, priority)
.addClassAndMethod(methodGen, sourceFile)
.addSourceLine(methodGen, sourceFile, location.getHandle());
if (DEBUG)
bugInstance.addInt(location.getHandle().getPosition()).describe("INT_BYTECODE_OFFSET");
if (AnalysisContext.currentAnalysisContext().getBoolProperty(
FindBugsAnalysisProperties.RELAXED_REPORTING_MODE)) {
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
propertySet.decorateBugInstance(bugInstance);
}
bugReporter.reportBug(bugInstance);
}
private void reportRedundantNullCheck(
ClassContext classContext,
Method method,
Location location,
RedundantBranch redundantBranch) {
String sourceFile = classContext.getJavaClass().getSourceFileName();
MethodGen methodGen = classContext.getMethodGen(method);
boolean redundantNullCheck = redundantBranch.checkedValue;
// String type = redundantNullCheck
// ? "RCN_REDUNDANT_CHECKED_NULL_COMPARISON"
// : "RCN_REDUNDANT_COMPARISON_TO_NULL";
int priority = redundantNullCheck ? LOW_PRIORITY : NORMAL_PRIORITY;
BugInstance bugInstance =
new BugInstance(this, "RCN_REDUNDANT_COMPARISON_TO_NULL", priority)
.addClassAndMethod(methodGen, sourceFile)
.addSourceLine(methodGen, sourceFile, location.getHandle());
if (AnalysisContext.currentAnalysisContext().getBoolProperty(
FindBugsAnalysisProperties.RELAXED_REPORTING_MODE)) {
WarningPropertySet propertySet = new WarningPropertySet();
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
if (redundantBranch.checkedValue) {
propertySet.addProperty(NullDerefProperty.CHECKED_VALUE);
}
propertySet.decorateBugInstance(bugInstance);
priority = propertySet.computePriority(NORMAL_PRIORITY);
bugInstance.setPriority(priority);
}
bugReporter.reportBug(bugInstance);
}
public void report() {
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs.detect;
import java.util.BitSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ATHROW;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.BugAnnotation;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.FieldAnnotation;
import edu.umd.cs.findbugs.FindBugsAnalysisFeatures;
import edu.umd.cs.findbugs.LocalVariableAnnotation;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.DataflowValueChooser;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.Frame;
import edu.umd.cs.findbugs.ba.Hierarchy;
import edu.umd.cs.findbugs.ba.JavaClassAndMethod;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.MissingClassException;
import edu.umd.cs.findbugs.ba.NullnessAnnotation;
import edu.umd.cs.findbugs.ba.NullnessAnnotationDatabase;
import edu.umd.cs.findbugs.ba.SignatureConverter;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.interproc.PropertyDatabase;
import edu.umd.cs.findbugs.ba.npe.IsNullValue;
import edu.umd.cs.findbugs.ba.npe.IsNullValueDataflow;
import edu.umd.cs.findbugs.ba.npe.IsNullValueFrame;
import edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonCollector;
import edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonFinder;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessProperty;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessPropertyDatabase;
import edu.umd.cs.findbugs.ba.npe.RedundantBranch;
import edu.umd.cs.findbugs.ba.type.TypeDataflow;
import edu.umd.cs.findbugs.ba.type.TypeFrame;
import edu.umd.cs.findbugs.ba.vna.AvailableLoad;
import edu.umd.cs.findbugs.ba.vna.ValueNumber;
import edu.umd.cs.findbugs.ba.vna.ValueNumberDataflow;
import edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;
import edu.umd.cs.findbugs.classfile.FieldDescriptor;
import edu.umd.cs.findbugs.props.GeneralWarningProperty;
import edu.umd.cs.findbugs.props.WarningPropertySet;
import edu.umd.cs.findbugs.props.WarningPropertyUtil;
/**
* A Detector to find instructions where a NullPointerException
* might be raised. We also look for useless reference comparisons
* involving null and non-null values.
*
* @author David Hovemeyer
* @author William Pugh
* @see edu.umd.cs.findbugs.ba.npe.IsNullValueAnalysis
*/
public class FindNullDeref
implements Detector, NullDerefAndRedundantComparisonCollector {
private static final boolean DEBUG = SystemProperties.getBoolean("fnd.debug");
private static final boolean DEBUG_NULLARG = SystemProperties.getBoolean("fnd.debug.nullarg");
private static final boolean DEBUG_NULLRETURN = SystemProperties.getBoolean("fnd.debug.nullreturn");
private static final boolean REPORT_SAFE_METHOD_TARGETS = true;
private static final String METHOD = SystemProperties.getProperty("fnd.method");
// Fields
private BugReporter bugReporter;
// Cached database stuff
private ParameterNullnessPropertyDatabase unconditionalDerefParamDatabase;
private boolean checkedDatabases = false;
// Transient state
private ClassContext classContext;
private Method method;
private IsNullValueDataflow invDataflow;
private BitSet previouslyDeadBlocks;
private NullnessAnnotation methodAnnotation;
public FindNullDeref(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visitClassContext(ClassContext classContext) {
this.classContext = classContext;
JavaClass jclass = classContext.getJavaClass();
Method[] methodList = jclass.getMethods();
for (Method method : methodList) {
try {
if (method.isAbstract() || method.isNative()
|| method.getCode() == null)
continue;
if (METHOD != null && !method.getName().equals(METHOD))
continue;
if (DEBUG)
System.out
.println("Checking for NP in " + method.getName());
analyzeMethod(classContext, method);
} catch (MissingClassException e) {
bugReporter.reportMissingClass(e.getClassNotFoundException());
} catch (DataflowAnalysisException e) {
bugReporter.logError("FindNullDeref caught dae exception", e);
} catch (CFGBuilderException e) {
bugReporter.logError("FindNullDeref caught cfgb exception", e);
}
}
}
private void analyzeMethod(ClassContext classContext, Method method)
throws CFGBuilderException, DataflowAnalysisException {
if (DEBUG || DEBUG_NULLARG)
System.out.println("Pre FND ");
MethodGen methodGen = classContext.getMethodGen(method);
if (methodGen == null)
return;
if (!checkedDatabases) {
checkDatabases();
checkedDatabases = true;
}
this.method = method;
this.methodAnnotation = getMethodNullnessAnnotation();
if (DEBUG || DEBUG_NULLARG)
System.out.println("FND: " + SignatureConverter.convertMethodSignature(methodGen));
this.previouslyDeadBlocks = findPreviouslyDeadBlocks();
// Get the IsNullValueDataflow for the method from the ClassContext
invDataflow = classContext.getIsNullValueDataflow(method);
// Create a NullDerefAndRedundantComparisonFinder object to do the actual
// work. It will call back to report null derefs and redundant null comparisons
// through the NullDerefAndRedundantComparisonCollector interface we implement.
NullDerefAndRedundantComparisonFinder worker = new NullDerefAndRedundantComparisonFinder(
classContext,
method,
this);
worker.execute();
checkCallSitesAndReturnInstructions();
}
/**
* Find set of blocks which were known to be dead before doing the
* null pointer analysis.
*
* @return set of previously dead blocks, indexed by block id
* @throws CFGBuilderException
* @throws DataflowAnalysisException
*/
private BitSet findPreviouslyDeadBlocks() throws DataflowAnalysisException, CFGBuilderException {
BitSet deadBlocks = new BitSet();
ValueNumberDataflow vnaDataflow = classContext.getValueNumberDataflow(method);
for (Iterator<BasicBlock> i = vnaDataflow.getCFG().blockIterator(); i.hasNext();) {
BasicBlock block = i.next();
ValueNumberFrame vnaFrame = vnaDataflow.getStartFact(block);
if (vnaFrame.isTop()) {
deadBlocks.set(block.getId());
}
}
return deadBlocks;
}
/**
* Check whether or not the various interprocedural databases we can
* use exist and are nonempty.
*/
private void checkDatabases() {
AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext();
unconditionalDerefParamDatabase = analysisContext.getUnconditionalDerefParamDatabase();
}
private<
DatabaseType extends PropertyDatabase<?,?>> boolean isDatabaseNonEmpty(DatabaseType database) {
return database != null && !database.isEmpty();
}
/**
* See if the currently-visited method declares a @NonNull annotation,
* or overrides a method which declares a @NonNull annotation.
*/
private NullnessAnnotation getMethodNullnessAnnotation() {
if (method.getSignature().indexOf(")L") >= 0 || method.getSignature().indexOf(")[") >= 0 ) {
if (DEBUG_NULLRETURN) {
System.out.println("Checking return annotation for " +
SignatureConverter.convertMethodSignature(classContext.getJavaClass(), method));
}
XMethod m = XFactory.createXMethod(classContext.getJavaClass(), method);
return AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase()
.getResolvedAnnotation(m, false);
}
return NullnessAnnotation.UNKNOWN_NULLNESS;
}
private void checkCallSitesAndReturnInstructions()
throws CFGBuilderException, DataflowAnalysisException {
ConstantPoolGen cpg = classContext.getConstantPoolGen();
TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
for (Iterator<Location> i = classContext.getCFG(method).locationIterator(); i.hasNext();) {
Location location = i.next();
Instruction ins = location.getHandle().getInstruction();
try {
if (ins instanceof InvokeInstruction) {
examineCallSite(location, cpg, typeDataflow);
} else if (methodAnnotation == NullnessAnnotation.NONNULL && ins.getOpcode() == Constants.ARETURN) {
examineReturnInstruction(location);
} else if (ins instanceof PUTFIELD) {
examinePutfieldInstruction(location, (PUTFIELD) ins, cpg);
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
}
}
private void examineCallSite(
Location location,
ConstantPoolGen cpg,
TypeDataflow typeDataflow)
throws DataflowAnalysisException, CFGBuilderException, ClassNotFoundException {
InvokeInstruction invokeInstruction = (InvokeInstruction)
location.getHandle().getInstruction();
String methodName = invokeInstruction.getName(cpg);
String signature = invokeInstruction.getSignature(cpg);
// Don't check equals() calls.
// If an equals() call unconditionally dereferences the parameter,
// it is the fault of the method, not the caller.
if (methodName.equals("equals") && signature.equals("(Ljava/lang/Object;)Z"))
return;
int returnTypeStart = signature.indexOf(')');
if (returnTypeStart < 0)
return;
String paramList = signature.substring(0, returnTypeStart + 1);
if (paramList.equals("()") ||
(paramList.indexOf("L") < 0 && paramList.indexOf('[') < 0))
// Method takes no arguments, or takes no reference arguments
return;
// See if any null arguments are passed
IsNullValueFrame frame =
classContext.getIsNullValueDataflow(method).getFactAtLocation(location);
if (!frame.isValid())
return;
BitSet nullArgSet = frame.getArgumentSet(invokeInstruction, cpg, new DataflowValueChooser<IsNullValue>() {
public boolean choose(IsNullValue value) {
// Only choose non-exception values.
// Values null on an exception path might be due to
// infeasible control flow.
return value.mightBeNull() && !value.isException() && !value.isReturnValue();
}
});
BitSet definitelyNullArgSet = frame.getArgumentSet(invokeInstruction, cpg, new DataflowValueChooser<IsNullValue>() {
public boolean choose(IsNullValue value) {
return value.isDefinitelyNull();
}
});
if (nullArgSet.isEmpty())
return;
if (DEBUG_NULLARG) {
System.out.println("Null arguments passed: " + nullArgSet);
System.out.println("Frame is: " + frame);
System.out.println("# arguments: " + frame.getNumArguments(invokeInstruction, cpg));
XMethod xm = XFactory.createXMethod(invokeInstruction, cpg);
System.out.print("Signature: " + xm.getSignature());
}
if (unconditionalDerefParamDatabase != null) {
checkUnconditionallyDereferencedParam(location, cpg, typeDataflow, invokeInstruction, nullArgSet, definitelyNullArgSet);
}
if (DEBUG_NULLARG) {
System.out.println("Checking nonnull params");
}
checkNonNullParam(location, cpg, typeDataflow, invokeInstruction, nullArgSet, definitelyNullArgSet);
}
private void examinePutfieldInstruction(Location location, PUTFIELD ins, ConstantPoolGen cpg) throws DataflowAnalysisException, CFGBuilderException {
IsNullValueDataflow invDataflow = classContext.getIsNullValueDataflow(method);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
if (!frame.isValid())
return;
IsNullValue tos = frame.getTopValue();
if (tos.mightBeNull()) {
XField field = XFactory.createXField(ins.getClassName(cpg), ins.getFieldName(cpg), ins.getSignature(cpg), false, 0);
NullnessAnnotation annotation = AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase().getResolvedAnnotation(field, false);
if (annotation == NullnessAnnotation.NONNULL) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance warning = new BugInstance("NP_STORE_INTO_NONNULL_FIELD", tos.isDefinitelyNull() ?
HIGH_PRIORITY : NORMAL_PRIORITY)
.addClassAndMethod(methodGen, sourceFile)
.addField(field)
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
bugReporter.reportBug(warning);
}
}
}
private void examineReturnInstruction(Location location) throws DataflowAnalysisException, CFGBuilderException {
if (DEBUG_NULLRETURN) {
System.out.println("Checking null return at " + location);
}
IsNullValueDataflow invDataflow = classContext.getIsNullValueDataflow(method);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
if (!frame.isValid())
return;
IsNullValue tos = frame.getTopValue();
if (tos.mightBeNull()) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance warning = new BugInstance("NP_NONNULL_RETURN_VIOLATION", tos.isDefinitelyNull() ?
HIGH_PRIORITY : NORMAL_PRIORITY)
.addClassAndMethod(methodGen, sourceFile)
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
bugReporter.reportBug(warning);
}
}
private void checkUnconditionallyDereferencedParam(
Location location,
ConstantPoolGen cpg,
TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction,
BitSet nullArgSet, BitSet definitelyNullArgSet) throws DataflowAnalysisException, ClassNotFoundException {
// See what methods might be called here
TypeFrame typeFrame = typeDataflow.getFactAtLocation(location);
Set<JavaClassAndMethod> targetMethodSet = Hierarchy.resolveMethodCallTargets(invokeInstruction, typeFrame, cpg);
if (DEBUG_NULLARG) {
System.out.println("Possibly called methods: " + targetMethodSet);
}
// See if any call targets unconditionally dereference one of the null arguments
BitSet unconditionallyDereferencedNullArgSet = new BitSet();
List<JavaClassAndMethod> dangerousCallTargetList = new LinkedList<JavaClassAndMethod>();
List<JavaClassAndMethod> veryDangerousCallTargetList = new LinkedList<JavaClassAndMethod>();
for (JavaClassAndMethod targetMethod : targetMethodSet) {
if (DEBUG_NULLARG) {
System.out.println("For target method " + targetMethod);
}
ParameterNullnessProperty property = unconditionalDerefParamDatabase.getProperty(targetMethod.toXMethod());
if (property == null)
continue;
if (DEBUG_NULLARG) {
System.out.println("\tUnconditionally dereferenced params: " + property);
}
BitSet targetUnconditionallyDereferencedNullArgSet =
property.getViolatedParamSet(nullArgSet);
if (targetUnconditionallyDereferencedNullArgSet.isEmpty())
continue;
dangerousCallTargetList.add(targetMethod);
unconditionallyDereferencedNullArgSet.or(targetUnconditionallyDereferencedNullArgSet);
if (!property.getViolatedParamSet(definitelyNullArgSet).isEmpty())
veryDangerousCallTargetList.add(targetMethod);
}
if (dangerousCallTargetList.isEmpty())
return;
WarningPropertySet propertySet = new WarningPropertySet();
// See if there are any safe targets
Set<JavaClassAndMethod> safeCallTargetSet = new HashSet<JavaClassAndMethod>();
safeCallTargetSet.addAll(targetMethodSet);
safeCallTargetSet.removeAll(dangerousCallTargetList);
if (safeCallTargetSet.isEmpty()) {
propertySet.addProperty(NullArgumentWarningProperty.ALL_DANGEROUS_TARGETS);
if (dangerousCallTargetList.size() == 1) {
propertySet.addProperty(NullArgumentWarningProperty.MONOMORPHIC_CALL_SITE);
}
}
// Call to private method? In theory there should be only one possible target.
boolean privateCall =
safeCallTargetSet.isEmpty()
&& dangerousCallTargetList.size() == 1
&& dangerousCallTargetList.get(0).getMethod().isPrivate();
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
String bugType;
int priority;
if (privateCall
|| invokeInstruction.getOpcode() == Constants.INVOKESTATIC
|| invokeInstruction.getOpcode() == Constants.INVOKESPECIAL) {
bugType = "NP_NULL_PARAM_DEREF_NONVIRTUAL";
priority = HIGH_PRIORITY;
} else if (safeCallTargetSet.isEmpty()) {
bugType = "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS";
priority = NORMAL_PRIORITY;
} else {
bugType = "NP_NULL_PARAM_DEREF";
priority = LOW_PRIORITY;
}
if (dangerousCallTargetList.size() > veryDangerousCallTargetList.size())
priority++;
else
propertySet.addProperty(NullArgumentWarningProperty.ACTUAL_PARAMETER_GUARANTEED_NULL);
BugInstance warning = new BugInstance(bugType, priority)
.addClassAndMethod(methodGen, sourceFile)
.addMethod(XFactory.createXMethod(invokeInstruction, cpg)).describe("METHOD_CALLED")
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle())
;
// Check which params might be null
addParamAnnotations(definitelyNullArgSet, unconditionallyDereferencedNullArgSet, propertySet, warning);
// Add annotations for dangerous method call targets
for (JavaClassAndMethod dangerousCallTarget : veryDangerousCallTargetList) {
warning.addMethod(dangerousCallTarget).describe("METHOD_DANGEROUS_TARGET_ACTUAL_GUARANTEED_NULL");
}
dangerousCallTargetList.removeAll(veryDangerousCallTargetList);
// Add annotations for dangerous method call targets
for (JavaClassAndMethod dangerousCallTarget : dangerousCallTargetList) {
warning.addMethod(dangerousCallTarget).describe("METHOD_DANGEROUS_TARGET");
}
// Add safe method call targets.
// This is useful to see which other call targets the analysis
// considered.
for (JavaClassAndMethod safeMethod : safeCallTargetSet) {
warning.addMethod(safeMethod).describe("METHOD_SAFE_TARGET");
}
decorateWarning(location, propertySet, warning);
bugReporter.reportBug(warning);
}
private void decorateWarning(Location location, WarningPropertySet propertySet, BugInstance warning) {
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
}
propertySet.decorateBugInstance(warning);
}
private void addParamAnnotations(
BitSet definitelyNullArgSet,
BitSet violatedParamSet,
WarningPropertySet propertySet,
BugInstance warning) {
for (int i = 0; i < 32; ++i) {
if (violatedParamSet.get(i)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (definitelyNull) {
propertySet.addProperty(NullArgumentWarningProperty.ARG_DEFINITELY_NULL);
}
// Note: we report params as being indexed starting from 1, not 0
warning.addInt(i + 1).describe(
definitelyNull ? "INT_NULL_ARG" : "INT_MAYBE_NULL_ARG");
}
}
}
/**
* We have a method invocation in which a possibly or definitely null
* parameter is passed. Check it against the library of nonnull annotations.
*
* @param location
* @param cpg
* @param typeDataflow
* @param invokeInstruction
* @param nullArgSet
* @param definitelyNullArgSet
* @throws ClassNotFoundException
*/
private void checkNonNullParam(
Location location,
ConstantPoolGen cpg,
TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction,
BitSet nullArgSet,
BitSet definitelyNullArgSet) throws ClassNotFoundException {
XMethod m = XFactory.createXMethod(invokeInstruction, cpg);
NullnessAnnotationDatabase db
= AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase();
for(int i=nullArgSet.nextSetBit(0); i>=0; i=nullArgSet.nextSetBit(i+1)) {
int paramNum = 0;
String signature = invokeInstruction.getSignature(cpg);
Type[] args = Type.getArgumentTypes(signature);
int words =0;
while (words < i)
words += args[paramNum++].getSize();
if (db.parameterMustBeNonNull(m, paramNum)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (DEBUG_NULLARG) {
System.out.println("QQQ2: " + i + " -- " + paramNum + " is null");
System.out.println("QQQ nullArgSet: " + nullArgSet);
System.out.println("QQQ dnullArgSet: " + definitelyNullArgSet);
}
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance warning = new BugInstance("NP_NONNULL_PARAM_VIOLATION",
definitelyNull ? HIGH_PRIORITY : NORMAL_PRIORITY)
.addClassAndMethod(methodGen, sourceFile)
.addMethod(m).describe("METHOD_CALLED")
.addInt(i).describe("INT_NONNULL_PARAM")
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
bugReporter.reportBug(warning);
}
}
}
public void report() {
}
public void foundNullDeref(ClassContext classContext, Location location, ValueNumber valueNumber, IsNullValue refValue, ValueNumberFrame vnaFrame) {
WarningPropertySet propertySet = new WarningPropertySet();
boolean onExceptionPath = refValue.isException();
if (onExceptionPath) {
propertySet.addProperty(GeneralWarningProperty.ON_EXCEPTION_PATH);
}
int pc = location.getHandle().getPosition();
BugAnnotation variable = findLocalVariable(location, valueNumber, vnaFrame);
boolean duplicated = false;
try {
CFG cfg = classContext.getCFG(method);
duplicated = cfg.getLocationsContainingInstructionWithOffset(pc).size() > 1;
} catch (CFGBuilderException e) {
}
if (!duplicated && refValue.isDefinitelyNull()) {
String type = onExceptionPath ? "NP_ALWAYS_NULL_EXCEPTION" : "NP_ALWAYS_NULL";
int priority = onExceptionPath ? NORMAL_PRIORITY : HIGH_PRIORITY;
reportNullDeref(propertySet, classContext, method, location, type, priority, variable);
} else if (refValue.isNullOnSomePath() || duplicated && refValue.isDefinitelyNull()) {
String type = "NP_NULL_ON_SOME_PATH";
int priority = NORMAL_PRIORITY;
if (onExceptionPath) type = "NP_NULL_ON_SOME_PATH_EXCEPTION";
else if (refValue.isReturnValue())
type = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE";
else if (refValue.isParamValue()) {
if (method.getName().equals("equals")
&& method.getSignature().equals("(Ljava/lang/Object;)Z"))
type = "NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT";
else
type = "NP_ARGUMENT_MIGHT_BE_NULL";
}
if (DEBUG) System.out.println("Reporting null on some path: value=" + refValue);
reportNullDeref(propertySet, classContext, method, location, type, priority, variable);
}
}
/**
* @param location
* @param valueNumber
* @param vnaFrame
* @return
*/
BugAnnotation findLocalVariable(Location location, ValueNumber valueNumber, ValueNumberFrame vnaFrame) {
BugAnnotation variable = null;
if (DEBUG) {
System.out.println("Dereference at " + location + " of " + valueNumber);
System.out.println("Value number frame: " + vnaFrame);
}
if (vnaFrame != null && !vnaFrame.isBottom() && !vnaFrame.isTop())
for(int i = 0; i < vnaFrame.getNumLocals(); i++) {
if (valueNumber.equals(vnaFrame.getValue(i))) {
if (DEBUG) System.out.println("Found it in local " + i);
InstructionHandle handle = location.getHandle();
int position1 = handle.getPrev().getPosition();
int position2 = handle.getPosition();
variable = LocalVariableAnnotation.getLocalVariableAnnotation(method, i, position1, position2);
if (variable != null) break;
}
}
if (variable == null) {
AvailableLoad load = vnaFrame.getLoad(valueNumber);
if (load != null) {
XField field = load.getField();
variable = new FieldAnnotation(field.getClassName(), field.getName(), field.getSignature(), field.isStatic());
}
}
return variable;
}
private void reportNullDeref(
WarningPropertySet propertySet,
ClassContext classContext,
Method method,
Location location,
String type,
int priority, BugAnnotation variable) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance bugInstance = new BugInstance(this, type, priority)
.addClassAndMethod(methodGen, sourceFile);
if (variable != null)
bugInstance.add(variable);
else bugInstance.add(new LocalVariableAnnotation("?",-1,-1));
bugInstance.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
propertySet.decorateBugInstance(bugInstance);
}
bugReporter.reportBug(bugInstance);
}
public static boolean isThrower(BasicBlock target) {
InstructionHandle ins = target.getFirstInstruction();
int maxCount = 7;
while (ins != null) {
if (maxCount-- <= 0) break;
Instruction i = ins.getInstruction();
if (i instanceof ATHROW) {
return true;
}
if (i instanceof InstructionTargeter
|| i instanceof ReturnInstruction) return false;
ins = ins.getNext();
}
return false;
}
public void foundRedundantNullCheck(Location location, RedundantBranch redundantBranch) {
String sourceFile = classContext.getJavaClass().getSourceFileName();
MethodGen methodGen = classContext.getMethodGen(method);
boolean isChecked = redundantBranch.firstValue.isChecked();
boolean wouldHaveBeenAKaboom = redundantBranch.firstValue.wouldHaveBeenAKaboom();
Location locationOfKaBoom = redundantBranch.firstValue.getLocationOfKaBoom();
boolean createdDeadCode = false;
boolean infeasibleEdgeSimplyThrowsException = false;
Edge infeasibleEdge = redundantBranch.infeasibleEdge;
if (infeasibleEdge != null) {
if (DEBUG) System.out.println("Check if " + redundantBranch + " creates dead code");
BasicBlock target = infeasibleEdge.getTarget();
if (DEBUG) System.out.println("Target block is " + (target.isExceptionThrower() ? " exception thrower" : " not exception thrower"));
// If the block is empty, it probably doesn't matter that it was killed.
// FIXME: really, we should crawl the immediately reachable blocks
// starting at the target block to see if any of them are dead and nonempty.
boolean empty = !target.isExceptionThrower() &&
(target.isEmpty() || isGoto(target.getFirstInstruction().getInstruction()));
if (!empty) {
try {
if (classContext.getCFG(method).getNumIncomingEdges(target) > 1) {
if (DEBUG) System.out.println("Target of infeasible edge has multiple incoming edges");
empty = true;
}}
catch (CFGBuilderException e) {
assert true; // ignore it
}
}
if (DEBUG) System.out.println("Target block is " + (empty ? "empty" : "not empty"));
if (!empty) {
if (isThrower(target)) infeasibleEdgeSimplyThrowsException = true;
}
if (!empty && !previouslyDeadBlocks.get(target.getId())) {
if (DEBUG) System.out.println("target was alive previously");
// Block was not dead before the null pointer analysis.
// See if it is dead now by inspecting the null value frame.
// If it's TOP, then the block became dead.
IsNullValueFrame invFrame = invDataflow.getStartFact(target);
createdDeadCode = invFrame.isTop();
if (DEBUG) System.out.println("target is now " + (createdDeadCode ? "dead" : "alive"));
}
}
int priority;
boolean valueIsNull = true;
String warning;
if (redundantBranch.secondValue == null) {
if (redundantBranch.firstValue.isDefinitelyNull() ) {
warning = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE";
priority = NORMAL_PRIORITY;
}
else {
warning = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE";
valueIsNull = false;
priority = isChecked ? NORMAL_PRIORITY : LOW_PRIORITY;
}
} else {
boolean bothNull = redundantBranch.firstValue.isDefinitelyNull() && redundantBranch.secondValue.isDefinitelyNull();
if (redundantBranch.secondValue.isChecked()) isChecked = true;
if (redundantBranch.secondValue.wouldHaveBeenAKaboom()) {
wouldHaveBeenAKaboom = true;
locationOfKaBoom = redundantBranch.secondValue.getLocationOfKaBoom();
}
if (bothNull) {
warning = "RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES";
priority = NORMAL_PRIORITY;
}
else {
warning = "RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE";
priority = isChecked ? NORMAL_PRIORITY : LOW_PRIORITY;
}
}
if (wouldHaveBeenAKaboom) {
priority = HIGH_PRIORITY;
warning = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE";
if (locationOfKaBoom == null) throw new NullPointerException("location of KaBoom is null");
}
if (DEBUG) System.out.println(createdDeadCode + " " + infeasibleEdgeSimplyThrowsException + " " + valueIsNull + " " + priority);
if (createdDeadCode && !infeasibleEdgeSimplyThrowsException) {
priority += 0;
} else if (createdDeadCode && infeasibleEdgeSimplyThrowsException) {
// throw clause
if (valueIsNull)
priority += 0;
else
priority += 1;
} else {
// didn't create any dead code
priority += 1;
}
if (DEBUG) {
System.out.println("RCN" + priority + " "
+ redundantBranch.firstValue + " =? "
+ redundantBranch.secondValue
+ " : " + warning
);
if (isChecked) System.out.println("isChecked");
if (wouldHaveBeenAKaboom) System.out.println("wouldHaveBeenAKaboom");
if (createdDeadCode) System.out.println("createdDeadCode");
}
BugAnnotation variableAnnotation = null;
try {
// Get the value number
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
if (vnaFrame.isValid()) {
Instruction ins = location.getHandle().getInstruction();
ValueNumber valueNumber = vnaFrame.getInstance(ins, classContext.getConstantPoolGen());
variableAnnotation = findLocalVariable(location, valueNumber, vnaFrame);
}
} catch (DataflowAnalysisException e) {
// ignore
} catch (CFGBuilderException e) {
// ignore
}
BugInstance bugInstance =
new BugInstance(this, warning, priority)
.addClassAndMethod(methodGen, sourceFile);
if (variableAnnotation != null) bugInstance.add(variableAnnotation);
else bugInstance.add(new LocalVariableAnnotation("?", -1, -1));
if (wouldHaveBeenAKaboom)
bugInstance.addSourceLine(classContext, methodGen, sourceFile, locationOfKaBoom.getHandle());
bugInstance.addSourceLine(classContext, methodGen, sourceFile, location.getHandle()).describe("SOURCE_REDUNDANT_NULL_CHECK");
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertySet propertySet = new WarningPropertySet();
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
if (isChecked)
propertySet.addProperty(NullDerefProperty.CHECKED_VALUE);
if (wouldHaveBeenAKaboom)
propertySet.addProperty(NullDerefProperty.WOULD_HAVE_BEEN_A_KABOOM);
if (createdDeadCode)
propertySet.addProperty(NullDerefProperty.CREATED_DEAD_CODE);
propertySet.decorateBugInstance(bugInstance);
priority = propertySet.computePriority(NORMAL_PRIORITY);
bugInstance.setPriority(priority);
}
bugReporter.reportBug(bugInstance);
}
/**
* Determine whether or not given instruction is a goto.
*
* @param instruction the instruction
* @return true if the instruction is a goto, false otherwise
*/
private boolean isGoto(Instruction instruction) {
return instruction.getOpcode() == Constants.GOTO
|| instruction.getOpcode() == Constants.GOTO_W;
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonCollector#foundGuaranteedNullDeref(java.util.Set, java.util.Set, edu.umd.cs.findbugs.ba.vna.ValueNumber, boolean)
*/
public void foundGuaranteedNullDeref(
@NonNull Set<Location> assignedNullLocationSet,
@NonNull Set<Location> derefLocationSet,
ValueNumber refValue,
boolean alwaysOnExceptionPath, boolean npeIfStatementCovered) {
if (DEBUG) {
System.out.println("Found guaranteed null deref in " + method.getName());
}
String bugType = alwaysOnExceptionPath
? "NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH"
: "NP_GUARANTEED_DEREF";
int priority = alwaysOnExceptionPath ? NORMAL_PRIORITY : HIGH_PRIORITY;
if (!npeIfStatementCovered) priority++;
// Create BugInstance
BugInstance bugInstance = new BugInstance(this, bugType, priority)
.addClassAndMethod(classContext.getJavaClass(), method);
// Add Locations in the set of locations at least one of which
// is guaranteed to be dereferenced
TreeSet<Location> sortedDerefLocationSet = new TreeSet<Location>(derefLocationSet);
for (Location loc : sortedDerefLocationSet) {
bugInstance.addSourceLine(classContext, method, loc).describe("SOURCE_LINE_DEREF");
}
// Add Locations where the value was observed to become null
TreeSet<Location> sortedAssignedNullLocationSet = new TreeSet<Location>(assignedNullLocationSet);
for (Location loc : sortedAssignedNullLocationSet) {
bugInstance.addSourceLine(classContext, method, loc).describe("SOURCE_LINE_NULL_VALUE");
}
// Report it
bugReporter.reportBug(bugInstance);
}
}
// vim:ts=4 |
package com.esotericsoftware.kryonet.rmi;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.KryoSerializable;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.FieldSerializer;
import com.esotericsoftware.kryo.util.IntMap;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.EndPoint;
import com.esotericsoftware.kryonet.FrameworkMessage;
import com.esotericsoftware.kryonet.Listener;
import static com.esotericsoftware.minlog.Log.*;
/** Allows methods on objects to be invoked remotely over TCP. Objects are {@link #register(int, Object) registered} with an ID.
* The remote end of connections that have been {@link #addConnection(Connection) added} are allowed to
* {@link #getRemoteObject(Connection, int, Class) access} registered objects.
* <p>
* It costs at least 2 bytes more to use remote method invocation than just sending the parameters. If the method has a return
* value which is not {@link RemoteObject#setNonBlocking(boolean, boolean) ignored}, an extra byte is written. If the type of a
* parameter is not final (note primitives are final) then an extra byte is written for that parameter.
* @author Nathan Sweet <misc@n4te.com> */
public class ObjectSpace {
static private final Object instancesLock = new Object();
static ObjectSpace[] instances = new ObjectSpace[0];
static private final HashMap<Class, CachedMethod[]> methodCache = new HashMap();
final IntMap idToObject = new IntMap();
Connection[] connections = {};
final Object connectionsLock = new Object();
private final Listener invokeListener = new Listener() {
public void received (Connection connection, Object object) {
if (!(object instanceof InvokeMethod)) return;
if (connections != null) {
int i = 0, n = connections.length;
for (; i < n; i++)
if (connection == connections[i]) break;
if (i == n) return; // The InvokeMethod message is not for a connection in this ObjectSpace.
}
InvokeMethod invokeMethod = (InvokeMethod)object;
Object target = idToObject.get(invokeMethod.objectID);
if (target == null) {
if (WARN) warn("kryonet", "Ignoring remote invocation request for unknown object ID: " + invokeMethod.objectID);
return;
}
invoke(connection, target, invokeMethod);
}
public void disconnected (Connection connection) {
removeConnection(connection);
}
};
/** Creates an ObjectSpace with no connections. Connections must be {@link #addConnection(Connection) added} to allow the remote
* end of the connections to access objects in this ObjectSpace. */
public ObjectSpace () {
synchronized (instancesLock) {
ObjectSpace[] instances = ObjectSpace.instances;
ObjectSpace[] newInstances = new ObjectSpace[instances.length + 1];
newInstances[0] = this;
System.arraycopy(instances, 0, newInstances, 1, instances.length);
ObjectSpace.instances = newInstances;
}
}
/** Creates an ObjectSpace with the specified connection. More connections can be {@link #addConnection(Connection) added}. */
public ObjectSpace (Connection connection) {
this();
addConnection(connection);
}
/** Registers an object to allow the remote end of the ObjectSpace's connections to access it using the specified ID.
* <p>
* If a connection is added to multiple ObjectSpaces, the same object ID should not be registered in more than one of those
* ObjectSpaces.
* @see #getRemoteObject(Connection, int, Class...) */
public void register (int objectID, Object object) {
if (object == null) throw new IllegalArgumentException("object cannot be null.");
idToObject.put(objectID, object);
if (TRACE) trace("kryonet", "Object registered with ObjectSpace as " + objectID + ": " + object);
}
/** Removes an object. The remote end of the ObjectSpace's connections will no longer be able to access it. */
public void remove (int objectID) {
Object object = idToObject.remove(objectID);
if (TRACE) trace("kryonet", "Object " + objectID + " removed from ObjectSpace: " + object);
}
/** Removes an object. The remote end of the ObjectSpace's connections will no longer be able to access it. */
public void remove (Object object) {
if (!idToObject.containsValue(object, true)) return;
int objectID = idToObject.findKey(object, true, -1);
idToObject.remove(objectID);
if (TRACE) trace("kryonet", "Object " + objectID + " removed from ObjectSpace: " + object);
}
/** Causes this ObjectSpace to stop listening to the connections for method invocation messages. */
public void close () {
Connection[] connections = this.connections;
for (int i = 0; i < connections.length; i++)
connections[i].removeListener(invokeListener);
synchronized (instancesLock) {
ArrayList<Connection> temp = new ArrayList(Arrays.asList(instances));
temp.remove(this);
instances = temp.toArray(new ObjectSpace[temp.size()]);
}
if (TRACE) trace("kryonet", "Closed ObjectSpace.");
}
/** Allows the remote end of the specified connection to access objects registered in this ObjectSpace. */
public void addConnection (Connection connection) {
if (connection == null) throw new IllegalArgumentException("connection cannot be null.");
synchronized (connectionsLock) {
Connection[] newConnections = new Connection[connections.length + 1];
newConnections[0] = connection;
System.arraycopy(connections, 0, newConnections, 1, connections.length);
connections = newConnections;
}
connection.addListener(invokeListener);
if (TRACE) trace("kryonet", "Added connection to ObjectSpace: " + connection);
}
/** Removes the specified connection, it will no longer be able to access objects registered in this ObjectSpace. */
public void removeConnection (Connection connection) {
if (connection == null) throw new IllegalArgumentException("connection cannot be null.");
connection.removeListener(invokeListener);
synchronized (connectionsLock) {
ArrayList<Connection> temp = new ArrayList(Arrays.asList(connections));
temp.remove(connection);
connections = temp.toArray(new Connection[temp.size()]);
}
if (TRACE) trace("kryonet", "Removed connection from ObjectSpace: " + connection);
}
/** Invokes the method on the object and, if necessary, sends the result back to the connection that made the invocation
* request. This method is invoked on the update thread of the {@link EndPoint} for this ObjectSpace and can be overridden to
* perform invocations on a different thread.
* @param connection The remote side of this connection requested the invocation. */
protected void invoke (Connection connection, Object target, InvokeMethod invokeMethod) {
if (DEBUG) {
String argString = "";
if (invokeMethod.args != null) {
argString = Arrays.deepToString(invokeMethod.args);
argString = argString.substring(1, argString.length() - 1);
}
debug("kryonet", connection + " received: " + target.getClass().getSimpleName() + "#" + invokeMethod.method.getName()
+ "(" + argString + ")");
}
Object result;
Method method = invokeMethod.method;
try {
result = method.invoke(target, invokeMethod.args);
} catch (Exception ex) {
throw new RuntimeException("Error invoking method: " + method.getDeclaringClass().getName() + "." + method.getName(), ex);
}
byte responseID = invokeMethod.responseID;
if (method.getReturnType() == void.class || responseID == 0) return;
InvokeMethodResult invokeMethodResult = new InvokeMethodResult();
invokeMethodResult.objectID = invokeMethod.objectID;
invokeMethodResult.responseID = responseID;
invokeMethodResult.result = result;
int length = connection.sendTCP(invokeMethodResult);
if (DEBUG) debug("kryonet", connection + " sent: " + result + " (" + length + ")");
}
/** Identical to {@link #getRemoteObject(Connection, int, Class...)} except returns the object cast to the specified interface
* type. The returned object still implements {@link RemoteObject}. */
static public <T> T getRemoteObject (final Connection connection, int objectID, Class<T> iface) {
return (T)getRemoteObject(connection, objectID, new Class[] {iface});
}
/** Returns a proxy object that implements the specified interfaces. Methods invoked on the proxy object will be invoked
* remotely on the object with the specified ID in the ObjectSpace for the specified connection. If the remote end of the
* connection has not {@link #addConnection(Connection) added} the connection to the ObjectSpace, the remote method invocations
* will be ignored.
* <p>
* Methods that return a value will throw {@link TimeoutException} if the response is not received with the
* {@link RemoteObject#setResponseTimeout(int) response timeout}.
* <p>
* If {@link RemoteObject#setNonBlocking(boolean, boolean) non-blocking} is false (the default), then methods that return a
* value must not be called from the update thread for the connection. An exception will be thrown if this occurs. Methods with
* a void return value can be called on the update thread.
* <p>
* If a proxy returned from this method is part of an object graph sent over the network, the object graph on the receiving
* side will have the proxy object replaced with the registered object.
* @see RemoteObject */
static public RemoteObject getRemoteObject (Connection connection, int objectID, Class... ifaces) {
if (connection == null) throw new IllegalArgumentException("connection cannot be null.");
if (ifaces == null) throw new IllegalArgumentException("ifaces cannot be null.");
Class[] temp = new Class[ifaces.length + 1];
temp[0] = RemoteObject.class;
System.arraycopy(ifaces, 0, temp, 1, ifaces.length);
return (RemoteObject)Proxy.newProxyInstance(ObjectSpace.class.getClassLoader(), temp, new RemoteInvocationHandler(
connection, objectID));
}
/** Handles network communication when methods are invoked on a proxy. */
static private class RemoteInvocationHandler implements InvocationHandler {
private final Connection connection;
final int objectID;
private int timeoutMillis = 3000;
private boolean nonBlocking, ignoreResponses;
private Byte lastResponseID;
final ArrayList<InvokeMethodResult> responseQueue = new ArrayList();
private byte nextResponseID = 1;
private Listener responseListener;
public RemoteInvocationHandler (Connection connection, final int objectID) {
super();
this.connection = connection;
this.objectID = objectID;
responseListener = new Listener() {
public void received (Connection connection, Object object) {
if (!(object instanceof InvokeMethodResult)) return;
InvokeMethodResult invokeMethodResult = (InvokeMethodResult)object;
if (invokeMethodResult.objectID != objectID) return;
synchronized (responseQueue) {
responseQueue.add(invokeMethodResult);
responseQueue.notifyAll();
}
}
public void disconnected (Connection connection) {
close();
}
};
connection.addListener(responseListener);
}
public Object invoke (Object proxy, Method method, Object[] args) {
if (method.getDeclaringClass() == RemoteObject.class) {
String name = method.getName();
if (name.equals("close")) {
close();
return null;
} else if (name.equals("setResponseTimeout")) {
timeoutMillis = (Integer)args[0];
return null;
} else if (name.equals("setNonBlocking")) {
nonBlocking = (Boolean)args[0];
ignoreResponses = (Boolean)args[1];
return null;
} else if (name.equals("waitForLastResponse")) {
if (lastResponseID == null) throw new IllegalStateException("There is no last response to wait for.");
return waitForResponse(lastResponseID);
} else if (name.equals("getLastResponseID")) {
if (lastResponseID == null) throw new IllegalStateException("There is no last response ID.");
return lastResponseID;
} else if (name.equals("waitForResponse")) {
if (ignoreResponses) throw new IllegalStateException("This RemoteObject is configured to ignore all responses.");
return waitForResponse((Byte)args[0]);
}
} else if (method.getDeclaringClass() == Object.class) {
if (method.getName().equals("toString")) return "<proxy>";
try {
return method.invoke(proxy, args);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
InvokeMethod invokeMethod = new InvokeMethod();
invokeMethod.objectID = objectID;
invokeMethod.method = method;
invokeMethod.args = args;
boolean hasReturnValue = method.getReturnType() != void.class;
if (hasReturnValue && !ignoreResponses) {
byte responseID = nextResponseID++;
if (nextResponseID == 0) nextResponseID++; // Zero means don't send back a response.
invokeMethod.responseID = responseID;
}
int length = connection.sendTCP(invokeMethod);
if (DEBUG) {
String argString = "";
if (args != null) {
argString = Arrays.deepToString(args);
argString = argString.substring(1, argString.length() - 1);
}
debug("kryonet", connection + " sent: " + method.getDeclaringClass().getSimpleName() + "#" + method.getName() + "("
+ argString + ") (" + length + ")");
}
if (!hasReturnValue) return null;
if (nonBlocking) {
if (!ignoreResponses) lastResponseID = invokeMethod.responseID;
Class returnType = method.getReturnType();
if (returnType.isPrimitive()) {
if (returnType == int.class) return 0;
if (returnType == boolean.class) return Boolean.FALSE;
if (returnType == float.class) return 0f;
if (returnType == char.class) return (char)0;
if (returnType == long.class) return 0l;
if (returnType == short.class) return (short)0;
if (returnType == byte.class) return (byte)0;
if (returnType == double.class) return 0d;
}
return null;
}
try {
return waitForResponse(invokeMethod.responseID);
} catch (TimeoutException ex) {
throw new TimeoutException("Response timed out: " + method.getDeclaringClass().getName() + "." + method.getName());
}
}
private Object waitForResponse (int responseID) {
if (connection.getEndPoint().getUpdateThread() == Thread.currentThread())
throw new IllegalStateException("Cannot wait for an RMI response on the connection's update thread.");
long endTime = System.currentTimeMillis() + timeoutMillis;
synchronized (responseQueue) {
while (true) {
int remaining = (int)(endTime - System.currentTimeMillis());
for (int i = responseQueue.size() - 1; i >= 0; i
InvokeMethodResult invokeMethodResult = responseQueue.get(i);
if (invokeMethodResult.responseID == responseID) {
responseQueue.remove(invokeMethodResult);
lastResponseID = null;
return invokeMethodResult.result;
}
}
if (remaining <= 0) throw new TimeoutException("Response timed out.");
try {
responseQueue.wait(remaining);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
}
}
void close () {
connection.removeListener(responseListener);
}
}
/** Internal message to invoke methods remotely. */
static public class InvokeMethod implements FrameworkMessage, KryoSerializable {
public int objectID;
public Method method;
public Object[] args;
public byte responseID;
public void write (Kryo kryo, Output output) {
output.writeInt(objectID, true);
int methodClassID = kryo.getRegistration(method.getDeclaringClass()).getId();
output.writeInt(methodClassID, true);
CachedMethod[] cachedMethods = getMethods(kryo, method.getDeclaringClass());
CachedMethod cachedMethod = null;
for (int i = 0, n = cachedMethods.length; i < n; i++) {
cachedMethod = cachedMethods[i];
if (cachedMethod.method.equals(method)) {
output.writeByte(i);
break;
}
}
for (int i = 0, n = cachedMethod.serializers.length; i < n; i++) {
Serializer serializer = cachedMethod.serializers[i];
if (serializer != null)
kryo.writeObjectOrNull(output, args[i], serializer);
else
kryo.writeClassAndObject(output, args[i]);
}
if (method.getReturnType() != void.class) output.writeByte(responseID);
}
public void read (Kryo kryo, Input input) {
objectID = input.readInt(true);
int methodClassID = input.readInt(true);
Class methodClass = kryo.getRegistration(methodClassID).getType();
byte methodIndex = input.readByte();
CachedMethod cachedMethod;
try {
cachedMethod = getMethods(kryo, methodClass)[methodIndex];
} catch (IndexOutOfBoundsException ex) {
throw new KryoException("Invalid method index " + methodIndex + " for class: " + methodClass.getName());
}
method = cachedMethod.method;
args = new Object[cachedMethod.serializers.length];
for (int i = 0, n = args.length; i < n; i++) {
Serializer serializer = cachedMethod.serializers[i];
if (serializer != null)
args[i] = kryo.readObjectOrNull(input, method.getParameterTypes()[i], serializer);
else
args[i] = kryo.readClassAndObject(input);
}
if (method.getReturnType() != void.class) responseID = input.readByte();
}
}
/** Internal message to return the result of a remotely invoked method. */
static public class InvokeMethodResult implements FrameworkMessage {
public int objectID;
public byte responseID;
public Object result;
}
static CachedMethod[] getMethods (Kryo kryo, Class type) {
CachedMethod[] cachedMethods = methodCache.get(type);
if (cachedMethods != null) return cachedMethods;
ArrayList<Method> allMethods = new ArrayList();
Class nextClass = type;
while (nextClass != null && nextClass != Object.class) {
Collections.addAll(allMethods, nextClass.getDeclaredMethods());
nextClass = nextClass.getSuperclass();
}
PriorityQueue<Method> methods = new PriorityQueue(Math.max(1, allMethods.size()), new Comparator<Method>() {
public int compare (Method o1, Method o2) {
// Methods are sorted so they can be represented as an index.
int diff = o1.getName().compareTo(o2.getName());
if (diff != 0) return diff;
Class[] argTypes1 = o1.getParameterTypes();
Class[] argTypes2 = o2.getParameterTypes();
if (argTypes1.length > argTypes2.length) return 1;
if (argTypes1.length < argTypes2.length) return -1;
for (int i = 0; i < argTypes1.length; i++) {
diff = argTypes1[i].getName().compareTo(argTypes2[i].getName());
if (diff != 0) return diff;
}
throw new RuntimeException("Two methods with same signature!"); // Impossible.
}
});
for (int i = 0, n = allMethods.size(); i < n; i++) {
Method method = allMethods.get(i);
int modifiers = method.getModifiers();
if (Modifier.isStatic(modifiers)) continue;
if (Modifier.isPrivate(modifiers)) continue;
if (method.isSynthetic()) continue;
methods.add(method);
}
int n = methods.size();
cachedMethods = new CachedMethod[n];
for (int i = 0; i < n; i++) {
CachedMethod cachedMethod = new CachedMethod();
cachedMethod.method = methods.poll();
// Store the serializer for each final parameter.
Class[] parameterTypes = cachedMethod.method.getParameterTypes();
cachedMethod.serializers = new Serializer[parameterTypes.length];
for (int ii = 0, nn = parameterTypes.length; ii < nn; ii++)
if (kryo.isFinal(parameterTypes[ii])) cachedMethod.serializers[ii] = kryo.getSerializer(parameterTypes[ii]);
cachedMethods[i] = cachedMethod;
}
methodCache.put(type, cachedMethods);
return cachedMethods;
}
/** Returns the first object registered with the specified ID in any of the ObjectSpaces the specified connection belongs to. */
static Object getRegisteredObject (Connection connection, int objectID) {
ObjectSpace[] instances = ObjectSpace.instances;
for (int i = 0, n = instances.length; i < n; i++) {
ObjectSpace objectSpace = instances[i];
// Check if the connection is in this ObjectSpace.
Connection[] connections = objectSpace.connections;
for (int j = 0; j < connections.length; j++) {
if (connections[j] != connection) continue;
// Find an object with the objectID.
Object object = objectSpace.idToObject.get(objectID);
if (object != null) return object;
}
}
return null;
}
/** Registers the classes needed to use ObjectSpaces. This should be called before any connections are opened.
* @see Kryo#register(Class, Serializer) */
static public void registerClasses (final Kryo kryo) {
kryo.register(Object[].class);
kryo.register(InvokeMethod.class);
FieldSerializer serializer = (FieldSerializer)kryo.register(InvokeMethodResult.class).getSerializer();
serializer.getField("objectID").setClass(int.class, new Serializer<Integer>() {
public void write (Kryo kryo, Output output, Integer object) {
output.writeInt(object, true);
}
public Integer create (Kryo kryo, Input input, Class<Integer> type) {
return input.readInt(true);
}
});
kryo.register(InvocationHandler.class, new Serializer() {
public void write (Kryo kryo, Output output, Object object) {
RemoteInvocationHandler handler = (RemoteInvocationHandler)Proxy.getInvocationHandler(object);
output.writeInt(handler.objectID, true);
}
public Object create (Kryo kryo, Input input, Class type) {
int objectID = input.readInt(true);
Connection connection = (Connection)kryo.getContext().get("connection");
Object object = getRegisteredObject(connection, objectID);
if (WARN && object == null) warn("kryonet", "Unknown object ID " + objectID + " for connection: " + connection);
return object;
}
});
}
static class CachedMethod {
Method method;
Serializer[] serializers;
}
} |
package edu.umd.cs.findbugs.detect;
import java.util.BitSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ATHROW;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.FindBugsAnalysisFeatures;
import edu.umd.cs.findbugs.LocalVariableAnnotation;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.DataflowValueChooser;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.Hierarchy;
import edu.umd.cs.findbugs.ba.JavaClassAndMethod;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.MissingClassException;
import edu.umd.cs.findbugs.ba.NullnessAnnotation;
import edu.umd.cs.findbugs.ba.NullnessAnnotationDatabase;
import edu.umd.cs.findbugs.ba.SignatureConverter;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.interproc.PropertyDatabase;
import edu.umd.cs.findbugs.ba.npe.IsNullValue;
import edu.umd.cs.findbugs.ba.npe.IsNullValueDataflow;
import edu.umd.cs.findbugs.ba.npe.IsNullValueFrame;
import edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonCollector;
import edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonFinder;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessProperty;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessPropertyDatabase;
import edu.umd.cs.findbugs.ba.npe.RedundantBranch;
import edu.umd.cs.findbugs.ba.type.TypeDataflow;
import edu.umd.cs.findbugs.ba.type.TypeFrame;
import edu.umd.cs.findbugs.ba.vna.ValueNumber;
import edu.umd.cs.findbugs.ba.vna.ValueNumberDataflow;
import edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;
import edu.umd.cs.findbugs.props.GeneralWarningProperty;
import edu.umd.cs.findbugs.props.WarningPropertySet;
import edu.umd.cs.findbugs.props.WarningPropertyUtil;
/**
* A Detector to find instructions where a NullPointerException
* might be raised. We also look for useless reference comparisons
* involving null and non-null values.
*
* @author David Hovemeyer
* @author William Pugh
* @see edu.umd.cs.findbugs.ba.npe.IsNullValueAnalysis
*/
public class FindNullDeref
implements Detector, NullDerefAndRedundantComparisonCollector {
private static final boolean DEBUG = SystemProperties.getBoolean("fnd.debug");
private static final boolean DEBUG_NULLARG = SystemProperties.getBoolean("fnd.debug.nullarg");
private static final boolean DEBUG_NULLRETURN = SystemProperties.getBoolean("fnd.debug.nullreturn");
private static final boolean REPORT_SAFE_METHOD_TARGETS = true;
private static final String METHOD = SystemProperties.getProperty("fnd.method");
// Fields
private BugReporter bugReporter;
// Cached database stuff
private ParameterNullnessPropertyDatabase unconditionalDerefParamDatabase;
private boolean checkedDatabases = false;
// Transient state
private ClassContext classContext;
private Method method;
private IsNullValueDataflow invDataflow;
private BitSet previouslyDeadBlocks;
private NullnessAnnotation methodAnnotation;
public FindNullDeref(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visitClassContext(ClassContext classContext) {
this.classContext = classContext;
try {
JavaClass jclass = classContext.getJavaClass();
Method[] methodList = jclass.getMethods();
for (Method method : methodList) {
if (method.isAbstract() || method.isNative() || method.getCode() == null)
continue;
if (METHOD != null && !method.getName().equals(METHOD))
continue;
if (DEBUG) System.out.println("Checking for NP in " + method.getName());
analyzeMethod(classContext, method);
}
} catch (MissingClassException e) {
bugReporter.reportMissingClass(e.getClassNotFoundException());
} catch (DataflowAnalysisException e) {
bugReporter.logError("FindNullDeref caught dae exception", e);
} catch (CFGBuilderException e) {
bugReporter.logError("FindNullDeref caught cfgb exception", e);
}
}
private void analyzeMethod(ClassContext classContext, Method method)
throws CFGBuilderException, DataflowAnalysisException {
MethodGen methodGen = classContext.getMethodGen(method);
if (methodGen == null)
return;
if (!checkedDatabases) {
checkDatabases();
checkedDatabases = true;
}
this.method = method;
this.methodAnnotation = getMethodNullnessAnnotation();
if (DEBUG || DEBUG_NULLARG)
System.out.println("FND: " + SignatureConverter.convertMethodSignature(methodGen));
this.previouslyDeadBlocks = findPreviouslyDeadBlocks();
// Get the IsNullValueDataflow for the method from the ClassContext
invDataflow = classContext.getIsNullValueDataflow(method);
// Create a NullDerefAndRedundantComparisonFinder object to do the actual
// work. It will call back to report null derefs and redundant null comparisons
// through the NullDerefAndRedundantComparisonCollector interface we implement.
NullDerefAndRedundantComparisonFinder worker = new NullDerefAndRedundantComparisonFinder(
classContext,
method,
this);
worker.execute();
checkCallSitesAndReturnInstructions();
}
/**
* Find set of blocks which were known to be dead before doing the
* null pointer analysis.
*
* @return set of previously dead blocks, indexed by block id
* @throws CFGBuilderException
* @throws DataflowAnalysisException
*/
private BitSet findPreviouslyDeadBlocks() throws DataflowAnalysisException, CFGBuilderException {
BitSet deadBlocks = new BitSet();
ValueNumberDataflow vnaDataflow = classContext.getValueNumberDataflow(method);
for (Iterator<BasicBlock> i = vnaDataflow.getCFG().blockIterator(); i.hasNext();) {
BasicBlock block = i.next();
ValueNumberFrame vnaFrame = vnaDataflow.getStartFact(block);
if (vnaFrame.isTop()) {
deadBlocks.set(block.getId());
}
}
return deadBlocks;
}
/**
* Check whether or not the various interprocedural databases we can
* use exist and are nonempty.
*/
private void checkDatabases() {
AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext();
unconditionalDerefParamDatabase = analysisContext.getUnconditionalDerefParamDatabase();
}
private<
DatabaseType extends PropertyDatabase<?,?>> boolean isDatabaseNonEmpty(DatabaseType database) {
return database != null && !database.isEmpty();
}
/**
* See if the currently-visited method declares a @NonNull annotation,
* or overrides a method which declares a @NonNull annotation.
*/
private NullnessAnnotation getMethodNullnessAnnotation() {
if (method.getSignature().indexOf(")L") >= 0 || method.getSignature().indexOf(")[") >= 0 ) {
if (DEBUG_NULLRETURN) {
System.out.println("Checking return annotation for " +
SignatureConverter.convertMethodSignature(classContext.getJavaClass(), method));
}
XMethod m = XFactory.createXMethod(classContext.getJavaClass(), method);
return AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase()
.getResolvedAnnotation(m, false);
}
return NullnessAnnotation.UNKNOWN_NULLNESS;
}
private void checkCallSitesAndReturnInstructions()
throws CFGBuilderException, DataflowAnalysisException {
ConstantPoolGen cpg = classContext.getConstantPoolGen();
TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
for (Iterator<Location> i = classContext.getCFG(method).locationIterator(); i.hasNext();) {
Location location = i.next();
Instruction ins = location.getHandle().getInstruction();
try {
if (ins instanceof InvokeInstruction) {
examineCallSite(location, cpg, typeDataflow);
} else if (methodAnnotation == NullnessAnnotation.NONNULL && ins.getOpcode() == Constants.ARETURN) {
examineReturnInstruction(location);
} else if (ins instanceof PUTFIELD) {
examinePutfieldInstruction(location, (PUTFIELD) ins, cpg);
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
}
}
private void examineCallSite(
Location location,
ConstantPoolGen cpg,
TypeDataflow typeDataflow)
throws DataflowAnalysisException, CFGBuilderException, ClassNotFoundException {
InvokeInstruction invokeInstruction = (InvokeInstruction)
location.getHandle().getInstruction();
String methodName = invokeInstruction.getName(cpg);
String signature = invokeInstruction.getSignature(cpg);
// Don't check equals() calls.
// If an equals() call unconditionally dereferences the parameter,
// it is the fault of the method, not the caller.
if (methodName.equals("equals") && signature.equals("(Ljava/lang/Object;)Z"))
return;
int returnTypeStart = signature.indexOf(')');
if (returnTypeStart < 0)
return;
String paramList = signature.substring(0, returnTypeStart + 1);
if (paramList.equals("()") ||
(paramList.indexOf("L") < 0 && paramList.indexOf('[') < 0))
// Method takes no arguments, or takes no reference arguments
return;
// See if any null arguments are passed
IsNullValueFrame frame =
classContext.getIsNullValueDataflow(method).getFactAtLocation(location);
if (!frame.isValid())
return;
BitSet nullArgSet = frame.getArgumentSet(invokeInstruction, cpg, new DataflowValueChooser<IsNullValue>() {
public boolean choose(IsNullValue value) {
// Only choose non-exception values.
// Values null on an exception path might be due to
// infeasible control flow.
return value.mightBeNull() && !value.isException() && !value.isReturnValue();
}
});
BitSet definitelyNullArgSet = frame.getArgumentSet(invokeInstruction, cpg, new DataflowValueChooser<IsNullValue>() {
public boolean choose(IsNullValue value) {
return value.isDefinitelyNull();
}
});
if (nullArgSet.isEmpty())
return;
if (DEBUG_NULLARG) {
System.out.println("Null arguments passed: " + nullArgSet);
System.out.println("Frame is: " + frame);
System.out.println("# arguments: " + frame.getNumArguments(invokeInstruction, cpg));
XMethod xm = XFactory.createXMethod(invokeInstruction, cpg);
System.out.print("Signature: " + xm.getSignature());
}
if (unconditionalDerefParamDatabase != null) {
checkUnconditionallyDereferencedParam(location, cpg, typeDataflow, invokeInstruction, nullArgSet, definitelyNullArgSet);
}
if (DEBUG_NULLARG) {
System.out.println("Checking nonnull params");
}
checkNonNullParam(location, cpg, typeDataflow, invokeInstruction, nullArgSet, definitelyNullArgSet);
}
private void examinePutfieldInstruction(Location location, PUTFIELD ins, ConstantPoolGen cpg) throws DataflowAnalysisException, CFGBuilderException {
IsNullValueDataflow invDataflow = classContext.getIsNullValueDataflow(method);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
if (!frame.isValid())
return;
IsNullValue tos = frame.getTopValue();
if (tos.mightBeNull()) {
XField field = XFactory.createXField(ins.getClassName(cpg), ins.getFieldName(cpg), ins.getSignature(cpg), false, 0);
NullnessAnnotation annotation = AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase().getResolvedAnnotation(field, false);
if (annotation == NullnessAnnotation.NONNULL) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance warning = new BugInstance("NP_STORE_INTO_NONNULL_FIELD", tos.isDefinitelyNull() ?
HIGH_PRIORITY : NORMAL_PRIORITY)
.addClassAndMethod(methodGen, sourceFile)
.addField(field)
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
bugReporter.reportBug(warning);
}
}
}
private void examineReturnInstruction(Location location) throws DataflowAnalysisException, CFGBuilderException {
if (DEBUG_NULLRETURN) {
System.out.println("Checking null return at " + location);
}
IsNullValueDataflow invDataflow = classContext.getIsNullValueDataflow(method);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
if (!frame.isValid())
return;
IsNullValue tos = frame.getTopValue();
if (tos.mightBeNull()) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance warning = new BugInstance("NP_NONNULL_RETURN_VIOLATION", tos.isDefinitelyNull() ?
HIGH_PRIORITY : NORMAL_PRIORITY)
.addClassAndMethod(methodGen, sourceFile)
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
bugReporter.reportBug(warning);
}
}
private void checkUnconditionallyDereferencedParam(
Location location,
ConstantPoolGen cpg,
TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction,
BitSet nullArgSet, BitSet definitelyNullArgSet) throws DataflowAnalysisException, ClassNotFoundException {
// See what methods might be called here
TypeFrame typeFrame = typeDataflow.getFactAtLocation(location);
Set<JavaClassAndMethod> targetMethodSet = Hierarchy.resolveMethodCallTargets(invokeInstruction, typeFrame, cpg);
if (DEBUG_NULLARG) {
System.out.println("Possibly called methods: " + targetMethodSet);
}
// See if any call targets unconditionally dereference one of the null arguments
BitSet unconditionallyDereferencedNullArgSet = new BitSet();
List<JavaClassAndMethod> dangerousCallTargetList = new LinkedList<JavaClassAndMethod>();
List<JavaClassAndMethod> veryDangerousCallTargetList = new LinkedList<JavaClassAndMethod>();
for (JavaClassAndMethod targetMethod : targetMethodSet) {
if (DEBUG_NULLARG) {
System.out.println("For target method " + targetMethod);
}
ParameterNullnessProperty property = unconditionalDerefParamDatabase.getProperty(targetMethod.toXMethod());
if (property == null)
continue;
if (DEBUG_NULLARG) {
System.out.println("\tUnconditionally dereferenced params: " + property);
}
BitSet targetUnconditionallyDereferencedNullArgSet =
property.getViolatedParamSet(nullArgSet);
if (targetUnconditionallyDereferencedNullArgSet.isEmpty())
continue;
dangerousCallTargetList.add(targetMethod);
unconditionallyDereferencedNullArgSet.or(targetUnconditionallyDereferencedNullArgSet);
if (!property.getViolatedParamSet(definitelyNullArgSet).isEmpty())
veryDangerousCallTargetList.add(targetMethod);
}
if (dangerousCallTargetList.isEmpty())
return;
WarningPropertySet propertySet = new WarningPropertySet();
// See if there are any safe targets
Set<JavaClassAndMethod> safeCallTargetSet = new HashSet<JavaClassAndMethod>();
safeCallTargetSet.addAll(targetMethodSet);
safeCallTargetSet.removeAll(dangerousCallTargetList);
if (safeCallTargetSet.isEmpty()) {
propertySet.addProperty(NullArgumentWarningProperty.ALL_DANGEROUS_TARGETS);
if (dangerousCallTargetList.size() == 1) {
propertySet.addProperty(NullArgumentWarningProperty.MONOMORPHIC_CALL_SITE);
}
}
// Call to private method? In theory there should be only one possible target.
boolean privateCall =
safeCallTargetSet.isEmpty()
&& dangerousCallTargetList.size() == 1
&& dangerousCallTargetList.get(0).getMethod().isPrivate();
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
String bugType;
int priority;
if (privateCall
|| invokeInstruction.getOpcode() == Constants.INVOKESTATIC
|| invokeInstruction.getOpcode() == Constants.INVOKESPECIAL) {
bugType = "NP_NULL_PARAM_DEREF_NONVIRTUAL";
priority = HIGH_PRIORITY;
} else if (safeCallTargetSet.isEmpty()) {
bugType = "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS";
priority = NORMAL_PRIORITY;
} else {
bugType = "NP_NULL_PARAM_DEREF";
priority = LOW_PRIORITY;
}
if (dangerousCallTargetList.size() > veryDangerousCallTargetList.size())
priority++;
else
propertySet.addProperty(NullArgumentWarningProperty.ACTUAL_PARAMETER_GUARANTEED_NULL);
BugInstance warning = new BugInstance(bugType, priority)
.addClassAndMethod(methodGen, sourceFile)
.addMethod(XFactory.createXMethod(invokeInstruction, cpg)).describe("METHOD_CALLED")
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle())
;
// Check which params might be null
addParamAnnotations(definitelyNullArgSet, unconditionallyDereferencedNullArgSet, propertySet, warning);
// Add annotations for dangerous method call targets
for (JavaClassAndMethod dangerousCallTarget : veryDangerousCallTargetList) {
warning.addMethod(dangerousCallTarget).describe("METHOD_DANGEROUS_TARGET_ACTUAL_GUARANTEED_NULL");
}
dangerousCallTargetList.removeAll(veryDangerousCallTargetList);
// Add annotations for dangerous method call targets
for (JavaClassAndMethod dangerousCallTarget : dangerousCallTargetList) {
warning.addMethod(dangerousCallTarget).describe("METHOD_DANGEROUS_TARGET");
}
// Add safe method call targets.
// This is useful to see which other call targets the analysis
// considered.
for (JavaClassAndMethod safeMethod : safeCallTargetSet) {
warning.addMethod(safeMethod).describe("METHOD_SAFE_TARGET");
}
decorateWarning(location, propertySet, warning);
bugReporter.reportBug(warning);
}
private void decorateWarning(Location location, WarningPropertySet propertySet, BugInstance warning) {
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
}
propertySet.decorateBugInstance(warning);
}
private void addParamAnnotations(
BitSet definitelyNullArgSet,
BitSet violatedParamSet,
WarningPropertySet propertySet,
BugInstance warning) {
for (int i = 0; i < 32; ++i) {
if (violatedParamSet.get(i)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (definitelyNull) {
propertySet.addProperty(NullArgumentWarningProperty.ARG_DEFINITELY_NULL);
}
// Note: we report params as being indexed starting from 1, not 0
warning.addInt(i + 1).describe(
definitelyNull ? "INT_NULL_ARG" : "INT_MAYBE_NULL_ARG");
}
}
}
/**
* We have a method invocation in which a possibly or definitely null
* parameter is passed. Check it against the library of nonnull annotations.
*
* @param location
* @param cpg
* @param typeDataflow
* @param invokeInstruction
* @param nullArgSet
* @param definitelyNullArgSet
* @throws ClassNotFoundException
*/
private void checkNonNullParam(
Location location,
ConstantPoolGen cpg,
TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction,
BitSet nullArgSet,
BitSet definitelyNullArgSet) throws ClassNotFoundException {
XMethod m = XFactory.createXMethod(invokeInstruction, cpg);
NullnessAnnotationDatabase db
= AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase();
for(int i=nullArgSet.nextSetBit(0); i>=0; i=nullArgSet.nextSetBit(i+1)) {
int paramNum = 0;
String signature = invokeInstruction.getSignature(cpg);
Type[] args = Type.getArgumentTypes(signature);
int words =0;
while (words < i)
words += args[paramNum++].getSize();
if (db.parameterMustBeNonNull(m, paramNum)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (DEBUG_NULLARG) {
System.out.println("QQQ2: " + i + " -- " + paramNum + " is null");
System.out.println("QQQ nullArgSet: " + nullArgSet);
System.out.println("QQQ dnullArgSet: " + definitelyNullArgSet);
}
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance warning = new BugInstance("NP_NONNULL_PARAM_VIOLATION",
definitelyNull ? HIGH_PRIORITY : NORMAL_PRIORITY)
.addClassAndMethod(methodGen, sourceFile)
.addMethod(m).describe("METHOD_CALLED")
.addInt(i).describe("INT_NONNULL_PARAM")
.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
bugReporter.reportBug(warning);
}
}
}
public void report() {
}
public void foundNullDeref(ClassContext classContext, Location location, ValueNumber valueNumber, IsNullValue refValue, ValueNumberFrame vnaFrame) {
WarningPropertySet propertySet = new WarningPropertySet();
boolean onExceptionPath = refValue.isException();
if (onExceptionPath) {
propertySet.addProperty(GeneralWarningProperty.ON_EXCEPTION_PATH);
}
int pc = location.getHandle().getPosition();
LocalVariableAnnotation variable = findLocalVariable(location, valueNumber, vnaFrame);
boolean duplicated = false;
try {
CFG cfg = classContext.getCFG(method);
duplicated = cfg.getLocationsContainingInstructionWithOffset(pc).size() > 1;
} catch (CFGBuilderException e) {
}
if (!duplicated && refValue.isDefinitelyNull()) {
String type = onExceptionPath ? "NP_ALWAYS_NULL_EXCEPTION" : "NP_ALWAYS_NULL";
int priority = onExceptionPath ? NORMAL_PRIORITY : HIGH_PRIORITY;
reportNullDeref(propertySet, classContext, method, location, type, priority, variable);
} else if (refValue.isNullOnSomePath() || duplicated && refValue.isDefinitelyNull()) {
String type = "NP_NULL_ON_SOME_PATH";
int priority = NORMAL_PRIORITY;
if (onExceptionPath) type = "NP_NULL_ON_SOME_PATH_EXCEPTION";
else if (refValue.isReturnValue())
type = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE";
else if (refValue.isParamValue()) {
if (method.getName().equals("equals")
&& method.getSignature().equals("(Ljava/lang/Object;)Z"))
type = "NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT";
else
type = "NP_ARGUMENT_MIGHT_BE_NULL";
}
if (DEBUG) System.out.println("Reporting null on some path: value=" + refValue);
reportNullDeref(propertySet, classContext, method, location, type, priority, variable);
}
}
/**
* @param location
* @param valueNumber
* @param vnaFrame
* @return
*/
LocalVariableAnnotation findLocalVariable(Location location, ValueNumber valueNumber, ValueNumberFrame vnaFrame) {
LocalVariableAnnotation variable = null;
if (DEBUG) {
System.out.println("Dereference at " + location + " of " + valueNumber);
System.out.println("Value number frame: " + vnaFrame);
}
if (vnaFrame != null && !vnaFrame.isBottom() && !vnaFrame.isTop())
for(int i = 0; i < vnaFrame.getNumLocals(); i++) {
if (valueNumber.equals(vnaFrame.getValue(i))) {
if (DEBUG) System.out.println("Found it in local " + i);
InstructionHandle handle = location.getHandle();
int position1 = handle.getPrev().getPosition();
int position2 = handle.getPosition();
variable = LocalVariableAnnotation.getLocalVariableAnnotation(method, i, position1, position2);
if (variable != null) break;
}
}
return variable;
}
private void reportNullDeref(
WarningPropertySet propertySet,
ClassContext classContext,
Method method,
Location location,
String type,
int priority, LocalVariableAnnotation variable) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance bugInstance = new BugInstance(this, type, priority)
.addClassAndMethod(methodGen, sourceFile);
if (variable != null)
bugInstance.add(variable);
else bugInstance.add(new LocalVariableAnnotation("?",-1,-1));
bugInstance.addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
propertySet.decorateBugInstance(bugInstance);
}
bugReporter.reportBug(bugInstance);
}
public static boolean isThrower(BasicBlock target) {
InstructionHandle ins = target.getFirstInstruction();
int maxCount = 7;
while (ins != null) {
if (maxCount-- <= 0) break;
Instruction i = ins.getInstruction();
if (i instanceof ATHROW) {
return true;
}
if (i instanceof InstructionTargeter
|| i instanceof ReturnInstruction) return false;
ins = ins.getNext();
}
return false;
}
public void foundRedundantNullCheck(Location location, RedundantBranch redundantBranch) {
String sourceFile = classContext.getJavaClass().getSourceFileName();
MethodGen methodGen = classContext.getMethodGen(method);
boolean isChecked = redundantBranch.firstValue.isChecked();
boolean wouldHaveBeenAKaboom = redundantBranch.firstValue.wouldHaveBeenAKaboom();
Location locationOfKaBoom = redundantBranch.firstValue.getLocationOfKaBoom();
boolean createdDeadCode = false;
boolean infeasibleEdgeSimplyThrowsException = false;
Edge infeasibleEdge = redundantBranch.infeasibleEdge;
if (infeasibleEdge != null) {
if (DEBUG) System.out.println("Check if " + redundantBranch + " creates dead code");
BasicBlock target = infeasibleEdge.getTarget();
if (DEBUG) System.out.println("Target block is " + (target.isExceptionThrower() ? " exception thrower" : " not exception thrower"));
// If the block is empty, it probably doesn't matter that it was killed.
// FIXME: really, we should crawl the immediately reachable blocks
// starting at the target block to see if any of them are dead and nonempty.
boolean empty = !target.isExceptionThrower() &&
(target.isEmpty() || isGoto(target.getFirstInstruction().getInstruction()));
if (!empty) {
try {
if (classContext.getCFG(method).getNumIncomingEdges(target) > 1) {
if (DEBUG) System.out.println("Target of infeasible edge has multiple incoming edges");
empty = true;
}}
catch (CFGBuilderException e) {
assert true; // ignore it
}
}
if (DEBUG) System.out.println("Target block is " + (empty ? "empty" : "not empty"));
if (!empty) {
if (isThrower(target)) infeasibleEdgeSimplyThrowsException = true;
}
if (!empty && !previouslyDeadBlocks.get(target.getId())) {
if (DEBUG) System.out.println("target was alive previously");
// Block was not dead before the null pointer analysis.
// See if it is dead now by inspecting the null value frame.
// If it's TOP, then the block became dead.
IsNullValueFrame invFrame = invDataflow.getStartFact(target);
createdDeadCode = invFrame.isTop();
if (DEBUG) System.out.println("target is now " + (createdDeadCode ? "dead" : "alive"));
}
}
int priority;
boolean valueIsNull = true;
String warning;
if (redundantBranch.secondValue == null) {
if (redundantBranch.firstValue.isDefinitelyNull() ) {
warning = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE";
priority = NORMAL_PRIORITY;
}
else {
warning = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE";
valueIsNull = false;
priority = isChecked ? NORMAL_PRIORITY : LOW_PRIORITY;
}
} else {
boolean bothNull = redundantBranch.firstValue.isDefinitelyNull() && redundantBranch.secondValue.isDefinitelyNull();
if (redundantBranch.secondValue.isChecked()) isChecked = true;
if (redundantBranch.secondValue.wouldHaveBeenAKaboom()) {
wouldHaveBeenAKaboom = true;
locationOfKaBoom = redundantBranch.secondValue.getLocationOfKaBoom();
}
if (bothNull) {
warning = "RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES";
priority = NORMAL_PRIORITY;
}
else {
warning = "RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE";
priority = isChecked ? NORMAL_PRIORITY : LOW_PRIORITY;
}
}
if (wouldHaveBeenAKaboom) {
priority = HIGH_PRIORITY;
warning = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE";
if (locationOfKaBoom == null) throw new NullPointerException("location of KaBoom is null");
}
if (DEBUG) System.out.println(createdDeadCode + " " + infeasibleEdgeSimplyThrowsException + " " + valueIsNull + " " + priority);
if (createdDeadCode && !infeasibleEdgeSimplyThrowsException) {
priority += 0;
} else if (createdDeadCode && infeasibleEdgeSimplyThrowsException) {
// throw clause
if (valueIsNull)
priority += 0;
else
priority += 1;
} else {
// didn't create any dead code
priority += 1;
}
if (DEBUG) {
System.out.println("RCN" + priority + " "
+ redundantBranch.firstValue + " =? "
+ redundantBranch.secondValue
+ " : " + warning
);
if (isChecked) System.out.println("isChecked");
if (wouldHaveBeenAKaboom) System.out.println("wouldHaveBeenAKaboom");
if (createdDeadCode) System.out.println("createdDeadCode");
}
LocalVariableAnnotation variableAnnotation = null;
try {
// Get the value number
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
if (vnaFrame.isValid()) {
Instruction ins = location.getHandle().getInstruction();
ValueNumber valueNumber = vnaFrame.getInstance(ins, classContext.getConstantPoolGen());
variableAnnotation = findLocalVariable(location, valueNumber, vnaFrame);
}
} catch (DataflowAnalysisException e) {
// ignore
} catch (CFGBuilderException e) {
// ignore
}
BugInstance bugInstance =
new BugInstance(this, warning, priority)
.addClassAndMethod(methodGen, sourceFile);
if (variableAnnotation != null) bugInstance.add(variableAnnotation);
else bugInstance.add(new LocalVariableAnnotation("?", -1, -1));
if (wouldHaveBeenAKaboom)
bugInstance.addSourceLine(classContext, methodGen, sourceFile, locationOfKaBoom.getHandle());
bugInstance.addSourceLine(classContext, methodGen, sourceFile, location.getHandle()).describe("SOURCE_REDUNDANT_NULL_CHECK");
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertySet propertySet = new WarningPropertySet();
WarningPropertyUtil.addPropertiesForLocation(propertySet, classContext, method, location);
if (isChecked)
propertySet.addProperty(NullDerefProperty.CHECKED_VALUE);
if (wouldHaveBeenAKaboom)
propertySet.addProperty(NullDerefProperty.WOULD_HAVE_BEEN_A_KABOOM);
if (createdDeadCode)
propertySet.addProperty(NullDerefProperty.CREATED_DEAD_CODE);
propertySet.decorateBugInstance(bugInstance);
priority = propertySet.computePriority(NORMAL_PRIORITY);
bugInstance.setPriority(priority);
}
bugReporter.reportBug(bugInstance);
}
/**
* Determine whether or not given instruction is a goto.
*
* @param instruction the instruction
* @return true if the instruction is a goto, false otherwise
*/
private boolean isGoto(Instruction instruction) {
return instruction.getOpcode() == Constants.GOTO
|| instruction.getOpcode() == Constants.GOTO_W;
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonCollector#foundGuaranteedNullDeref(java.util.Set, java.util.Set, edu.umd.cs.findbugs.ba.vna.ValueNumber)
*/
public void foundGuaranteedNullDeref(@NonNull Set<Location> assignedNullLocationSet, @NonNull Set<Location> derefLocationSet, ValueNumber refValue) {
if (DEBUG) {
System.out.println("Found guaranteed null deref in " + method.getName());
}
// Create BugInstance
BugInstance bugInstance = new BugInstance(this, "NP_GUARANTEED_DEREF", HIGH_PRIORITY)
.addClassAndMethod(classContext.getJavaClass(), method);
// Add Locations in the set of locations at least one of which
// is guaranteed to be dereferenced
TreeSet<Location> sortedDerefLocationSet = new TreeSet<Location>(derefLocationSet);
for (Location loc : sortedDerefLocationSet) {
bugInstance.addSourceLine(classContext, method, loc).describe("SOURCE_LINE_DEREF");
}
// Add Locations where the value was observed to become null
TreeSet<Location> sortedAssignedNullLocationSet = new TreeSet<Location>(assignedNullLocationSet);
for (Location loc : sortedAssignedNullLocationSet) {
bugInstance.addSourceLine(classContext, method, loc).describe("SOURCE_LINE_NULL_VALUE");
}
// Report it
bugReporter.reportBug(bugInstance);
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs.detect;
import java.util.BitSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LineNumberTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ATHROW;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.bcel.generic.ReturnInstruction;
import edu.umd.cs.findbugs.BugAnnotation;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.FieldAnnotation;
import edu.umd.cs.findbugs.FindBugsAnalysisFeatures;
import edu.umd.cs.findbugs.LocalVariableAnnotation;
import edu.umd.cs.findbugs.MethodAnnotation;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.UseAnnotationDatabase;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.DataflowValueChooser;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.Hierarchy;
import edu.umd.cs.findbugs.ba.INullnessAnnotationDatabase;
import edu.umd.cs.findbugs.ba.JavaClassAndMethod;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.MissingClassException;
import edu.umd.cs.findbugs.ba.NullnessAnnotation;
import edu.umd.cs.findbugs.ba.SignatureConverter;
import edu.umd.cs.findbugs.ba.SignatureParser;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.XMethodParameter;
import edu.umd.cs.findbugs.ba.interproc.PropertyDatabase;
import edu.umd.cs.findbugs.ba.npe.IsNullValue;
import edu.umd.cs.findbugs.ba.npe.IsNullValueDataflow;
import edu.umd.cs.findbugs.ba.npe.IsNullValueFrame;
import edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonCollector;
import edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonFinder;
import edu.umd.cs.findbugs.ba.npe.NullValueUnconditionalDeref;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessProperty;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessPropertyDatabase;
import edu.umd.cs.findbugs.ba.npe.PointerUsageRequiringNonNullValue;
import edu.umd.cs.findbugs.ba.npe.RedundantBranch;
import edu.umd.cs.findbugs.ba.npe.ReturnPathType;
import edu.umd.cs.findbugs.ba.npe.ReturnPathTypeDataflow;
import edu.umd.cs.findbugs.ba.npe.UsagesRequiringNonNullValues;
import edu.umd.cs.findbugs.ba.type.TypeDataflow;
import edu.umd.cs.findbugs.ba.type.TypeFrame;
import edu.umd.cs.findbugs.ba.vna.ValueNumberSourceInfo;
import edu.umd.cs.findbugs.ba.vna.ValueNumber;
import edu.umd.cs.findbugs.ba.vna.ValueNumberDataflow;
import edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.props.GeneralWarningProperty;
import edu.umd.cs.findbugs.props.WarningProperty;
import edu.umd.cs.findbugs.props.WarningPropertySet;
import edu.umd.cs.findbugs.props.WarningPropertyUtil;
import edu.umd.cs.findbugs.visitclass.Util;
/**
* A Detector to find instructions where a NullPointerException might be raised.
* We also look for useless reference comparisons involving null and non-null
* values.
*
* @author David Hovemeyer
* @author William Pugh
* @see edu.umd.cs.findbugs.ba.npe.IsNullValueAnalysis
*/
public class FindNullDeref implements Detector, UseAnnotationDatabase,
NullDerefAndRedundantComparisonCollector {
public static final boolean DEBUG = SystemProperties
.getBoolean("fnd.debug");
private static final boolean DEBUG_NULLARG = SystemProperties
.getBoolean("fnd.debug.nullarg");
private static final boolean DEBUG_NULLRETURN = SystemProperties
.getBoolean("fnd.debug.nullreturn");
private static final boolean MARK_DOOMED = SystemProperties
.getBoolean("fnd.markdoomed", true);
private static final boolean REPORT_SAFE_METHOD_TARGETS = true;
private static final String METHOD = SystemProperties
.getProperty("fnd.method");
private static final String CLASS = SystemProperties
.getProperty("fnd.class");
// Fields
private BugReporter bugReporter;
// Cached database stuff
private ParameterNullnessPropertyDatabase unconditionalDerefParamDatabase;
private boolean checkedDatabases = false;
// Transient state
private ClassContext classContext;
private Method method;
private IsNullValueDataflow invDataflow;
private BitSet previouslyDeadBlocks;
private NullnessAnnotation methodAnnotation;
public FindNullDeref(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visitClassContext(ClassContext classContext) {
this.classContext = classContext;
String currentMethod = null;
JavaClass jclass = classContext.getJavaClass();
String className = jclass.getClassName();
if (CLASS != null && !className.equals(CLASS))
return;
Method[] methodList = jclass.getMethods();
for (Method method : methodList) {
try {
if (method.isAbstract() || method.isNative()
|| method.getCode() == null)
continue;
MethodGen mg = classContext.getMethodGen(method);
if (mg == null) {
continue;
}
currentMethod = SignatureConverter.convertMethodSignature(mg);
if (METHOD != null && !method.getName().equals(METHOD))
continue;
if (DEBUG)
System.out.println("Checking for NP in " + currentMethod);
analyzeMethod(classContext, method);
} catch (MissingClassException e) {
bugReporter.reportMissingClass(e.getClassNotFoundException());
} catch (DataflowAnalysisException e) {
bugReporter.logError("While analyzing " + currentMethod
+ ": FindNullDeref caught dae exception", e);
} catch (CFGBuilderException e) {
bugReporter.logError("While analyzing " + currentMethod
+ ": FindNullDeref caught cfgb exception", e);
}
}
}
private void analyzeMethod(ClassContext classContext, Method method) throws DataflowAnalysisException, CFGBuilderException
{
if (DEBUG || DEBUG_NULLARG)
System.out.println("Pre FND ");
MethodGen methodGen = classContext.getMethodGen(method);
if (methodGen == null)
return;
if (!checkedDatabases) {
checkDatabases();
checkedDatabases = true;
}
// UsagesRequiringNonNullValues uses =
// classContext.getUsagesRequiringNonNullValues(method);
this.method = method;
this.methodAnnotation = getMethodNullnessAnnotation();
if (DEBUG || DEBUG_NULLARG)
System.out.println("FND: "
+ SignatureConverter.convertMethodSignature(methodGen));
this.previouslyDeadBlocks = findPreviouslyDeadBlocks();
// Get the IsNullValueDataflow for the method from the ClassContext
invDataflow = classContext.getIsNullValueDataflow(method);
// Create a NullDerefAndRedundantComparisonFinder object to do the
// actual
// work. It will call back to report null derefs and redundant null
// comparisons
// through the NullDerefAndRedundantComparisonCollector interface we
// implement.
NullDerefAndRedundantComparisonFinder worker = new NullDerefAndRedundantComparisonFinder(
classContext, method, this);
worker.execute();
checkCallSitesAndReturnInstructions();
}
/**
* Find set of blocks which were known to be dead before doing the null
* pointer analysis.
*
* @return set of previously dead blocks, indexed by block id
* @throws CFGBuilderException
* @throws DataflowAnalysisException
*/
private BitSet findPreviouslyDeadBlocks() throws DataflowAnalysisException,
CFGBuilderException {
BitSet deadBlocks = new BitSet();
ValueNumberDataflow vnaDataflow = classContext
.getValueNumberDataflow(method);
for (Iterator<BasicBlock> i = vnaDataflow.getCFG().blockIterator(); i
.hasNext();) {
BasicBlock block = i.next();
ValueNumberFrame vnaFrame = vnaDataflow.getStartFact(block);
if (vnaFrame.isTop()) {
deadBlocks.set(block.getLabel());
}
}
return deadBlocks;
}
/**
* Check whether or not the various interprocedural databases we can use
* exist and are nonempty.
*/
private void checkDatabases() {
AnalysisContext analysisContext = AnalysisContext
.currentAnalysisContext();
unconditionalDerefParamDatabase = analysisContext
.getUnconditionalDerefParamDatabase();
}
private <DatabaseType extends PropertyDatabase<?, ?>> boolean isDatabaseNonEmpty(
DatabaseType database) {
return database != null && !database.isEmpty();
}
/**
* See if the currently-visited method declares a
*
* @NonNull annotation, or overrides a method which declares a
* @NonNull annotation.
*/
private NullnessAnnotation getMethodNullnessAnnotation() {
if (method.getSignature().indexOf(")L") >= 0
|| method.getSignature().indexOf(")[") >= 0) {
if (DEBUG_NULLRETURN) {
System.out.println("Checking return annotation for "
+ SignatureConverter.convertMethodSignature(
classContext.getJavaClass(), method));
}
XMethod m = XFactory.createXMethod(classContext.getJavaClass(),
method);
return AnalysisContext.currentAnalysisContext()
.getNullnessAnnotationDatabase().getResolvedAnnotation(m,
false);
}
return NullnessAnnotation.UNKNOWN_NULLNESS;
}
private void checkCallSitesAndReturnInstructions() {
try {
ConstantPoolGen cpg = classContext.getConstantPoolGen();
TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
for (Iterator<Location> i = classContext.getCFG(method)
.locationIterator(); i.hasNext();) {
Location location = i.next();
Instruction ins = location.getHandle().getInstruction();
try {
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
if (!vnaFrame.isValid()) continue;
if (ins instanceof InvokeInstruction) {
examineCallSite(location, cpg, typeDataflow);
} else if (methodAnnotation == NullnessAnnotation.NONNULL
&& ins.getOpcode() == Constants.ARETURN) {
examineReturnInstruction(location);
} else if (ins instanceof PUTFIELD) {
examinePutfieldInstruction(location, (PUTFIELD) ins, cpg);
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
}
} catch (CheckedAnalysisException e) {
AnalysisContext.logError("error:", e);
}
}
private void examineCallSite(Location location, ConstantPoolGen cpg,
TypeDataflow typeDataflow) throws DataflowAnalysisException,
CFGBuilderException, ClassNotFoundException {
InvokeInstruction invokeInstruction = (InvokeInstruction) location
.getHandle().getInstruction();
String methodName = invokeInstruction.getName(cpg);
String signature = invokeInstruction.getSignature(cpg);
// Don't check equals() calls.
// If an equals() call unconditionally dereferences the parameter,
// it is the fault of the method, not the caller.
if (methodName.equals("equals")
&& signature.equals("(Ljava/lang/Object;)Z"))
return;
int returnTypeStart = signature.indexOf(')');
if (returnTypeStart < 0)
return;
String paramList = signature.substring(0, returnTypeStart + 1);
if (paramList.equals("()")
|| (paramList.indexOf("L") < 0 && paramList.indexOf('[') < 0))
// Method takes no arguments, or takes no reference arguments
return;
// See if any null arguments are passed
IsNullValueFrame frame = classContext.getIsNullValueDataflow(method)
.getFactAtLocation(location);
if (!frame.isValid())
return;
BitSet nullArgSet = frame.getArgumentSet(invokeInstruction, cpg,
new DataflowValueChooser<IsNullValue>() {
public boolean choose(IsNullValue value) {
// Only choose non-exception values.
// Values null on an exception path might be due to
// infeasible control flow.
return value.mightBeNull() && !value.isException()
&& !value.isReturnValue();
}
});
BitSet definitelyNullArgSet = frame.getArgumentSet(invokeInstruction,
cpg, new DataflowValueChooser<IsNullValue>() {
public boolean choose(IsNullValue value) {
return value.isDefinitelyNull();
}
});
nullArgSet.and(definitelyNullArgSet);
if (nullArgSet.isEmpty())
return;
if (DEBUG_NULLARG) {
System.out.println("Null arguments passed: " + nullArgSet);
System.out.println("Frame is: " + frame);
System.out.println("# arguments: "
+ frame.getNumArguments(invokeInstruction, cpg));
XMethod xm = XFactory.createXMethod(invokeInstruction, cpg);
System.out.print("Signature: " + xm.getSignature());
}
if (unconditionalDerefParamDatabase != null) {
checkUnconditionallyDereferencedParam(location, cpg, typeDataflow,
invokeInstruction, nullArgSet, definitelyNullArgSet);
}
if (DEBUG_NULLARG) {
System.out.println("Checking nonnull params");
}
checkNonNullParam(location, cpg, typeDataflow, invokeInstruction,
nullArgSet, definitelyNullArgSet);
}
private void examinePutfieldInstruction(Location location, PUTFIELD ins,
ConstantPoolGen cpg) throws DataflowAnalysisException,
CFGBuilderException {
IsNullValueDataflow invDataflow = classContext
.getIsNullValueDataflow(method);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
if (!frame.isValid())
return;
IsNullValue tos = frame.getTopValue();
if (tos.isDefinitelyNull()) {
XField field = XFactory.createXField(ins, cpg);
NullnessAnnotation annotation = AnalysisContext
.currentAnalysisContext().getNullnessAnnotationDatabase()
.getResolvedAnnotation(field, false);
if (annotation == NullnessAnnotation.NONNULL) {
BugAnnotation variableAnnotation = null;
try {
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
ValueNumber valueNumber = vnaFrame.getTopValue();
variableAnnotation = ValueNumberSourceInfo.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("error", e);
} catch (CFGBuilderException e) {
AnalysisContext.logError("error", e);
}
BugInstance warning = new BugInstance(this,
"NP_STORE_INTO_NONNULL_FIELD",
tos.isDefinitelyNull() ? HIGH_PRIORITY
: NORMAL_PRIORITY).addClassAndMethod(classContext.getJavaClass(),method)
.addField(field).addOptionalAnnotation(variableAnnotation).addSourceLine(classContext,
method, location);
bugReporter.reportBug(warning);
}
}
}
private void examineReturnInstruction(Location location)
throws DataflowAnalysisException, CFGBuilderException {
if (DEBUG_NULLRETURN) {
System.out.println("Checking null return at " + location);
}
IsNullValueDataflow invDataflow = classContext
.getIsNullValueDataflow(method);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
if (!vnaFrame.isValid()) return;
ValueNumber valueNumber = vnaFrame.getTopValue();
if (!frame.isValid())
return;
IsNullValue tos = frame.getTopValue();
if (tos.isDefinitelyNull()) {
BugAnnotation variable = ValueNumberSourceInfo.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
String bugPattern = "NP_NONNULL_RETURN_VIOLATION";
int priority = NORMAL_PRIORITY;
if (tos.isDefinitelyNull() && !tos.isException())
priority = HIGH_PRIORITY;
String methodName = method.getName();
if (methodName.equals("clone")) {
bugPattern = "NP_CLONE_COULD_RETURN_NULL";
priority = NORMAL_PRIORITY;
} else if (methodName.equals("toString")) {
bugPattern = "NP_TOSTRING_COULD_RETURN_NULL";
priority = NORMAL_PRIORITY;
}
BugInstance warning = new BugInstance(this, bugPattern, priority)
.addClassAndMethod(classContext.getJavaClass(), method).addOptionalAnnotation(variable).addSourceLine(
classContext, method,
location);
bugReporter.reportBug(warning);
}
}
private void checkUnconditionallyDereferencedParam(Location location,
ConstantPoolGen cpg, TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction, BitSet nullArgSet,
BitSet definitelyNullArgSet) throws DataflowAnalysisException,
ClassNotFoundException {
boolean caught = inCatchNullBlock(location);
if (caught && skipIfInsideCatchNull())
return;
// See what methods might be called here
TypeFrame typeFrame = typeDataflow.getFactAtLocation(location);
Set<JavaClassAndMethod> targetMethodSet = Hierarchy
.resolveMethodCallTargets(invokeInstruction, typeFrame, cpg);
if (DEBUG_NULLARG) {
System.out.println("Possibly called methods: " + targetMethodSet);
}
// See if any call targets unconditionally dereference one of the null
// arguments
BitSet unconditionallyDereferencedNullArgSet = new BitSet();
List<JavaClassAndMethod> dangerousCallTargetList = new LinkedList<JavaClassAndMethod>();
List<JavaClassAndMethod> veryDangerousCallTargetList = new LinkedList<JavaClassAndMethod>();
for (JavaClassAndMethod targetMethod : targetMethodSet) {
if (DEBUG_NULLARG) {
System.out.println("For target method " + targetMethod);
}
ParameterNullnessProperty property = unconditionalDerefParamDatabase
.getProperty(targetMethod.toMethodDescriptor());
if (property == null)
continue;
if (DEBUG_NULLARG) {
System.out.println("\tUnconditionally dereferenced params: "
+ property);
}
BitSet targetUnconditionallyDereferencedNullArgSet = property
.getViolatedParamSet(nullArgSet);
if (targetUnconditionallyDereferencedNullArgSet.isEmpty())
continue;
dangerousCallTargetList.add(targetMethod);
unconditionallyDereferencedNullArgSet
.or(targetUnconditionallyDereferencedNullArgSet);
if (!property.getViolatedParamSet(definitelyNullArgSet).isEmpty())
veryDangerousCallTargetList.add(targetMethod);
}
if (dangerousCallTargetList.isEmpty())
return;
WarningPropertySet<WarningProperty> propertySet = new WarningPropertySet<WarningProperty>();
// See if there are any safe targets
Set<JavaClassAndMethod> safeCallTargetSet = new HashSet<JavaClassAndMethod>();
safeCallTargetSet.addAll(targetMethodSet);
safeCallTargetSet.removeAll(dangerousCallTargetList);
if (safeCallTargetSet.isEmpty()) {
propertySet
.addProperty(NullArgumentWarningProperty.ALL_DANGEROUS_TARGETS);
if (dangerousCallTargetList.size() == 1) {
propertySet
.addProperty(NullArgumentWarningProperty.MONOMORPHIC_CALL_SITE);
}
}
// Call to private method? In theory there should be only one possible
// target.
boolean privateCall = safeCallTargetSet.isEmpty()
&& dangerousCallTargetList.size() == 1
&& dangerousCallTargetList.get(0).getMethod().isPrivate();
String bugType;
int priority;
if (privateCall
|| invokeInstruction.getOpcode() == Constants.INVOKESTATIC
|| invokeInstruction.getOpcode() == Constants.INVOKESPECIAL) {
bugType = "NP_NULL_PARAM_DEREF_NONVIRTUAL";
priority = HIGH_PRIORITY;
} else if (safeCallTargetSet.isEmpty()) {
bugType = "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS";
priority = NORMAL_PRIORITY;
} else {
return;
}
if (caught)
priority++;
if (dangerousCallTargetList.size() > veryDangerousCallTargetList.size())
priority++;
else
propertySet
.addProperty(NullArgumentWarningProperty.ACTUAL_PARAMETER_GUARANTEED_NULL);
XMethod calledFrom = XFactory.createXMethod(classContext.getJavaClass(), method);
BugInstance warning = new BugInstance(this,bugType, priority)
.addClassAndMethod(classContext.getJavaClass(), method).addMethod(
XFactory.createXMethod(invokeInstruction, cpg))
.describe("METHOD_CALLED").addSourceLine(classContext,
method, location);
boolean uncallable = false;
if (!AnalysisContext.currentXFactory().isCalledDirectlyOrIndirectly(calledFrom)
&& !calledFrom.isPublic() && !(calledFrom.isProtected() && classContext.getJavaClass().isPublic())) {
propertySet
.addProperty(GeneralWarningProperty.IN_UNCALLABLE_METHOD);
uncallable = true;
}
// Check which params might be null
addParamAnnotations(location,
definitelyNullArgSet, unconditionallyDereferencedNullArgSet, propertySet, warning);
if (bugType.equals("NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS")) {
// Add annotations for dangerous method call targets
for (JavaClassAndMethod dangerousCallTarget : veryDangerousCallTargetList) {
warning.addMethod(dangerousCallTarget).describe(
MethodAnnotation.METHOD_DANGEROUS_TARGET_ACTUAL_GUARANTEED_NULL);
}
dangerousCallTargetList.removeAll(veryDangerousCallTargetList);
if (DEBUG_NULLARG) {
// Add annotations for dangerous method call targets
for (JavaClassAndMethod dangerousCallTarget : dangerousCallTargetList) {
warning.addMethod(dangerousCallTarget).describe(
MethodAnnotation.METHOD_DANGEROUS_TARGET);
}
// Add safe method call targets.
// This is useful to see which other call targets the analysis
// considered.
for (JavaClassAndMethod safeMethod : safeCallTargetSet) {
warning.addMethod(safeMethod).describe(MethodAnnotation.METHOD_SAFE_TARGET);
}
}}
decorateWarning(location, propertySet, warning);
if (uncallable) warning.lowerPriority();
bugReporter.reportBug(warning);
}
private void decorateWarning(Location location,
WarningPropertySet<?> propertySet, BugInstance warning) {
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertyUtil.addPropertiesForLocation(propertySet,
classContext, method, location);
}
propertySet.decorateBugInstance(warning);
}
private void addParamAnnotations(Location location,
BitSet definitelyNullArgSet, BitSet violatedParamSet,
WarningPropertySet<? super NullArgumentWarningProperty> propertySet, BugInstance warning) {
ValueNumberFrame vnaFrame = null;
try {
vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("error", e);
} catch (CFGBuilderException e) {
AnalysisContext.logError("error", e);
}
InvokeInstruction instruction = (InvokeInstruction) location.getHandle().getInstruction();
SignatureParser sigParser = new SignatureParser(instruction.getSignature(classContext.getConstantPoolGen()));
for (int i = violatedParamSet.nextSetBit(0); i >= 0; i = violatedParamSet.nextSetBit(i + 1)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (definitelyNull)
propertySet
.addProperty(NullArgumentWarningProperty.ARG_DEFINITELY_NULL);
ValueNumber valueNumber = null;
if (vnaFrame != null)
try {
valueNumber = vnaFrame. getArgument(instruction, classContext.getConstantPoolGen(), i, sigParser );
BugAnnotation variableAnnotation = ValueNumberSourceInfo.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
warning.addOptionalAnnotation(variableAnnotation);
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("error", e);
}
// Note: we report params as being indexed starting from 1, not
warning.addInt(i + 1).describe(
definitelyNull ? "INT_NULL_ARG" : "INT_MAYBE_NULL_ARG");
}
}
/**
* We have a method invocation in which a possibly or definitely null
* parameter is passed. Check it against the library of nonnull annotations.
*
* @param location
* @param cpg
* @param typeDataflow
* @param invokeInstruction
* @param nullArgSet
* @param definitelyNullArgSet
* @throws ClassNotFoundException
*/
private void checkNonNullParam(Location location, ConstantPoolGen cpg,
TypeDataflow typeDataflow, InvokeInstruction invokeInstruction,
BitSet nullArgSet, BitSet definitelyNullArgSet)
throws ClassNotFoundException {
boolean caught = inCatchNullBlock(location);
if (caught && skipIfInsideCatchNull())
return;
XMethod m = XFactory.createXMethod(invokeInstruction, cpg);
INullnessAnnotationDatabase db = AnalysisContext
.currentAnalysisContext().getNullnessAnnotationDatabase();
SignatureParser sigParser = new SignatureParser(invokeInstruction.getSignature(cpg));
for (int i = nullArgSet.nextSetBit(0); i >= 0; i = nullArgSet
.nextSetBit(i + 1)) {
if (db.parameterMustBeNonNull(m, i)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (DEBUG_NULLARG) {
System.out.println("QQQ2: " + i + " -- " + i + " is null");
System.out.println("QQQ nullArgSet: " + nullArgSet);
System.out.println("QQQ dnullArgSet: "
+ definitelyNullArgSet);
}
BugAnnotation variableAnnotation = null;
try {
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
ValueNumber valueNumber = vnaFrame. getArgument(invokeInstruction, cpg, i, sigParser );
variableAnnotation = ValueNumberSourceInfo.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("error", e);
} catch (CFGBuilderException e) {
AnalysisContext.logError("error", e);
}
int priority = definitelyNull ? HIGH_PRIORITY : NORMAL_PRIORITY;
if (caught)
priority++;
String description = definitelyNull ? "INT_NULL_ARG" : "INT_MAYBE_NULL_ARG";
BugInstance warning = new BugInstance(this,
"NP_NONNULL_PARAM_VIOLATION", priority)
.addClassAndMethod(classContext.getJavaClass(), method).addMethod(m)
.describe("METHOD_CALLED").addInt(i+1).describe(
description).addOptionalAnnotation(variableAnnotation).addSourceLine(
classContext, method,
location);
bugReporter.reportBug(warning);
}
}
}
public void report() {
}
public boolean skipIfInsideCatchNull() {
return classContext.getJavaClass().getClassName().indexOf("Test") >= 0
|| method.getName().indexOf("test") >= 0
|| method.getName().indexOf("Test") >= 0;
}
public void foundNullDeref(ClassContext classContext, Location location,
ValueNumber valueNumber, IsNullValue refValue,
ValueNumberFrame vnaFrame) {
WarningPropertySet<WarningProperty> propertySet = new WarningPropertySet<WarningProperty>();
if (valueNumber.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT))
return;
boolean onExceptionPath = refValue.isException();
if (onExceptionPath) {
propertySet.addProperty(GeneralWarningProperty.ON_EXCEPTION_PATH);
}
int pc = location.getHandle().getPosition();
BugAnnotation variable = ValueNumberSourceInfo.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
boolean duplicated = false;
try {
CFG cfg = classContext.getCFG(method);
duplicated = cfg.getLocationsContainingInstructionWithOffset(pc)
.size() > 1;
} catch (CFGBuilderException e) {
}
boolean caught = inCatchNullBlock(location);
if (caught && skipIfInsideCatchNull())
return;
if (!duplicated && refValue.isDefinitelyNull()) {
String type = onExceptionPath ? "NP_ALWAYS_NULL_EXCEPTION"
: "NP_ALWAYS_NULL";
int priority = onExceptionPath ? NORMAL_PRIORITY : HIGH_PRIORITY;
if (caught)
priority++;
reportNullDeref(propertySet, classContext, method, location, type,
priority, variable);
} else if (refValue.mightBeNull() && refValue.isParamValue()) {
String type;
int priority = NORMAL_PRIORITY;
if (caught)
priority++;
if (method.getName().equals("equals")
&& method.getSignature()
.equals("(Ljava/lang/Object;)Z")) {
if (caught)
return;
type = "NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT";
} else
type = "NP_ARGUMENT_MIGHT_BE_NULL";
if (DEBUG)
System.out.println("Reporting null on some path: value="
+ refValue);
reportNullDeref(propertySet, classContext, method, location, type,
priority, variable);
}
}
private void reportNullDeref(WarningPropertySet<WarningProperty> propertySet,
ClassContext classContext, Method method, Location location,
String type, int priority, BugAnnotation variable) {
BugInstance bugInstance = new BugInstance(this, type, priority)
.addClassAndMethod(classContext.getJavaClass(), method);
if (variable != null)
bugInstance.add(variable);
else
bugInstance.add(new LocalVariableAnnotation("?", -1, -1));
bugInstance.addSourceLine(classContext, method,
location).describe("SOURCE_LINE_DEREF");
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertyUtil.addPropertiesForLocation(propertySet,
classContext, method, location);
}
if (isDoomed(location)) {
// Add a WarningProperty
propertySet.addProperty(DoomedCodeWarningProperty.DOOMED_CODE);
}
propertySet.decorateBugInstance(bugInstance);
bugReporter.reportBug(bugInstance);
}
public static boolean isThrower(BasicBlock target) {
InstructionHandle ins = target.getFirstInstruction();
int maxCount = 7;
while (ins != null) {
if (maxCount
break;
Instruction i = ins.getInstruction();
if (i instanceof ATHROW) {
return true;
}
if (i instanceof InstructionTargeter
|| i instanceof ReturnInstruction)
return false;
ins = ins.getNext();
}
return false;
}
public void foundRedundantNullCheck(Location location,
RedundantBranch redundantBranch) {
boolean isChecked = redundantBranch.firstValue.isChecked();
boolean wouldHaveBeenAKaboom = redundantBranch.firstValue
.wouldHaveBeenAKaboom();
Location locationOfKaBoom = redundantBranch.firstValue
.getLocationOfKaBoom();
boolean createdDeadCode = false;
boolean infeasibleEdgeSimplyThrowsException = false;
Edge infeasibleEdge = redundantBranch.infeasibleEdge;
if (infeasibleEdge != null) {
if (DEBUG)
System.out.println("Check if " + redundantBranch
+ " creates dead code");
BasicBlock target = infeasibleEdge.getTarget();
if (DEBUG)
System.out.println("Target block is "
+ (target.isExceptionThrower() ? " exception thrower"
: " not exception thrower"));
// If the block is empty, it probably doesn't matter that it was
// killed.
// FIXME: really, we should crawl the immediately reachable blocks
// starting at the target block to see if any of them are dead and
// nonempty.
boolean empty = !target.isExceptionThrower()
&& (target.isEmpty() || isGoto(target.getFirstInstruction()
.getInstruction()));
if (!empty) {
try {
if (classContext.getCFG(method).getNumIncomingEdges(target) > 1) {
if (DEBUG)
System.out
.println("Target of infeasible edge has multiple incoming edges");
empty = true;
}
} catch (CFGBuilderException e) {
assert true; // ignore it
}
}
if (DEBUG)
System.out.println("Target block is "
+ (empty ? "empty" : "not empty"));
if (!empty) {
if (isThrower(target))
infeasibleEdgeSimplyThrowsException = true;
}
if (!empty && !previouslyDeadBlocks.get(target.getLabel())) {
if (DEBUG)
System.out.println("target was alive previously");
// Block was not dead before the null pointer analysis.
// See if it is dead now by inspecting the null value frame.
// If it's TOP, then the block became dead.
IsNullValueFrame invFrame = invDataflow.getStartFact(target);
createdDeadCode = invFrame.isTop();
if (DEBUG)
System.out.println("target is now "
+ (createdDeadCode ? "dead" : "alive"));
}
}
int priority;
boolean valueIsNull = true;
String warning;
if (redundantBranch.secondValue == null) {
if (redundantBranch.firstValue.isDefinitelyNull()) {
warning = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE";
priority = NORMAL_PRIORITY;
} else {
warning = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE";
valueIsNull = false;
priority = isChecked ? NORMAL_PRIORITY : LOW_PRIORITY;
}
} else {
boolean bothNull = redundantBranch.firstValue.isDefinitelyNull()
&& redundantBranch.secondValue.isDefinitelyNull();
if (redundantBranch.secondValue.isChecked())
isChecked = true;
if (redundantBranch.secondValue.wouldHaveBeenAKaboom()) {
wouldHaveBeenAKaboom = true;
locationOfKaBoom = redundantBranch.secondValue
.getLocationOfKaBoom();
}
if (bothNull) {
warning = "RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES";
priority = NORMAL_PRIORITY;
} else {
warning = "RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE";
priority = isChecked ? NORMAL_PRIORITY : LOW_PRIORITY;
}
}
if (wouldHaveBeenAKaboom) {
priority = HIGH_PRIORITY;
warning = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE";
if (locationOfKaBoom == null)
throw new NullPointerException("location of KaBoom is null");
}
if (DEBUG)
System.out.println(createdDeadCode + " "
+ infeasibleEdgeSimplyThrowsException + " " + valueIsNull
+ " " + priority);
if (createdDeadCode && !infeasibleEdgeSimplyThrowsException) {
priority += 0;
} else if (createdDeadCode && infeasibleEdgeSimplyThrowsException) {
// throw clause
if (valueIsNull)
priority += 0;
else
priority += 1;
} else {
// didn't create any dead code
priority += 1;
}
if (DEBUG) {
System.out.println("RCN" + priority + " "
+ redundantBranch.firstValue + " =? "
+ redundantBranch.secondValue + " : " + warning);
if (isChecked)
System.out.println("isChecked");
if (wouldHaveBeenAKaboom)
System.out.println("wouldHaveBeenAKaboom");
if (createdDeadCode)
System.out.println("createdDeadCode");
}
if (priority > LOW_PRIORITY) return;
BugAnnotation variableAnnotation = null;
try {
// Get the value number
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(
method).getFactAtLocation(location);
if (vnaFrame.isValid()) {
Instruction ins = location.getHandle().getInstruction();
ValueNumber valueNumber = vnaFrame.getInstance(ins,
classContext.getConstantPoolGen());
if (valueNumber.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT))
return;
variableAnnotation = ValueNumberSourceInfo.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
}
} catch (DataflowAnalysisException e) {
// ignore
} catch (CFGBuilderException e) {
// ignore
}
BugInstance bugInstance = new BugInstance(this, warning, priority)
.addClassAndMethod(classContext.getJavaClass(), method);
if (variableAnnotation != null)
bugInstance.add(variableAnnotation);
else
bugInstance.add(new LocalVariableAnnotation("?", -1, -1));
if (wouldHaveBeenAKaboom)
bugInstance.addSourceLine(classContext, method,
locationOfKaBoom);
bugInstance.addSourceLine(classContext, method,
location).describe("SOURCE_REDUNDANT_NULL_CHECK");
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertySet propertySet = new WarningPropertySet();
WarningPropertyUtil.addPropertiesForLocation(propertySet,
classContext, method, location);
if (isChecked)
propertySet.addProperty(NullDerefProperty.CHECKED_VALUE);
if (wouldHaveBeenAKaboom)
propertySet
.addProperty(NullDerefProperty.WOULD_HAVE_BEEN_A_KABOOM);
if (createdDeadCode)
propertySet.addProperty(NullDerefProperty.CREATED_DEAD_CODE);
propertySet.decorateBugInstance(bugInstance);
priority = propertySet.computePriority(NORMAL_PRIORITY);
bugInstance.setPriority(priority);
}
bugReporter.reportBug(bugInstance);
}
// XXX
BugAnnotation getVariableAnnotation(Location location) {
BugAnnotation variableAnnotation = null;
try {
// Get the value number
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(
method).getFactAtLocation(location);
if (vnaFrame.isValid()) {
Instruction ins = location.getHandle().getInstruction();
ValueNumber valueNumber = vnaFrame.getInstance(ins,
classContext.getConstantPoolGen());
if (valueNumber.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT))
return null;
variableAnnotation = ValueNumberSourceInfo.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
}
} catch (DataflowAnalysisException e) {
// ignore
} catch (CFGBuilderException e) {
// ignore
}
return variableAnnotation;
}
/**
* Determine whether or not given instruction is a goto.
*
* @param instruction
* the instruction
* @return true if the instruction is a goto, false otherwise
*/
private boolean isGoto(Instruction instruction) {
return instruction.getOpcode() == Constants.GOTO
|| instruction.getOpcode() == Constants.GOTO_W;
}
/*
* (non-Javadoc)
*
* @see edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonCollector#foundGuaranteedNullDeref(java.util.Set,
* java.util.Set, edu.umd.cs.findbugs.ba.vna.ValueNumber, boolean)
*/
public void foundGuaranteedNullDeref(@NonNull
Set<Location> assignedNullLocationSet, @NonNull
Set<Location> derefLocationSet, SortedSet<Location> doomedLocations,
ValueNumberDataflow vna, ValueNumber refValue,
BugAnnotation variableAnnotation, NullValueUnconditionalDeref deref,
boolean npeIfStatementCovered) {
if (refValue.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT))
return;
if (DEBUG) {
System.out.println("Found guaranteed null deref in "
+ method.getName());
for (Location loc : doomedLocations)
System.out.println("Doomed at " + loc);
}
String bugType = "NP_GUARANTEED_DEREF";
int priority = NORMAL_PRIORITY;
if (deref.isMethodReturnValue())
bugType = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE";
else {
if (deref.isAlwaysOnExceptionPath())
bugType += "_ON_EXCEPTION_PATH";
else priority = HIGH_PRIORITY;
if (!npeIfStatementCovered)
priority++;
}
// Add Locations in the set of locations at least one of which
// is guaranteed to be dereferenced
SortedSet<Location> sourceLocations;
if (doomedLocations.isEmpty() || doomedLocations.size() > 3
&& doomedLocations.size() > assignedNullLocationSet.size())
sourceLocations = new TreeSet<Location>(assignedNullLocationSet);
else
sourceLocations = doomedLocations;
if (doomedLocations.isEmpty() || derefLocationSet.isEmpty())
return;
boolean derefOutsideCatchBlock = false;
for (Location loc : derefLocationSet)
if (!inCatchNullBlock(loc)) {
derefOutsideCatchBlock = true;
break;
}
boolean uniqueDereferenceLocations = false;
LineNumberTable table = method.getLineNumberTable();
if (table == null)
uniqueDereferenceLocations = true;
else {
BitSet linesMentionedMultipleTimes = ClassContext.linesMentionedMultipleTimes(method);
for(Location loc : derefLocationSet) {
int lineNumber = table.getSourceLine(loc.getHandle().getPosition());
if (!linesMentionedMultipleTimes.get(lineNumber)) uniqueDereferenceLocations = true;
}
}
if (!derefOutsideCatchBlock) {
if (!uniqueDereferenceLocations || skipIfInsideCatchNull())
return;
priority++;
}
if (!uniqueDereferenceLocations)
priority++;
// Create BugInstance
BitSet knownNull = new BitSet();
SortedSet<SourceLineAnnotation> knownNullLocations = new TreeSet<SourceLineAnnotation>();
for (Location loc : sourceLocations) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation
.fromVisitedInstruction(classContext, method, loc);
if (sourceLineAnnotation == null)
continue;
int startLine = sourceLineAnnotation.getStartLine();
if (startLine == -1)
knownNullLocations.add(sourceLineAnnotation);
else if (!knownNull.get(startLine)) {
knownNull.set(startLine);
knownNullLocations.add(sourceLineAnnotation);
}
}
FieldAnnotation storedField = null;
MethodAnnotation invokedMethod = null;
int parameterNumber = -1;
if (derefLocationSet.size() == 1) {
Location loc = derefLocationSet.iterator().next();
PointerUsageRequiringNonNullValue pu = null;
try {
UsagesRequiringNonNullValues usages = classContext.getUsagesRequiringNonNullValues(method);
pu = usages.get(loc, refValue);
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("Error getting UsagesRequiringNonNullValues for " + method, e);
} catch (CFGBuilderException e) {
AnalysisContext.logError("Error getting UsagesRequiringNonNullValues for " + method, e);
}
if (pu != null) {
if (pu.getReturnFromNonNullMethod()) {
bugType = "NP_NONNULL_RETURN_VIOLATION";
String methodName = method.getName();
String methodSig = method.getSignature();
if (methodName.equals("clone") && methodSig.equals("()Ljava/lang/Object;")) {
bugType = "NP_CLONE_COULD_RETURN_NULL";
priority = NORMAL_PRIORITY;
} else if (methodName.equals("toString") && methodSig.equals("()Ljava/lang/String;")) {
bugType = "NP_TOSTRING_COULD_RETURN_NULL";
priority = NORMAL_PRIORITY;
}
} else {
XField nonNullField = pu.getNonNullField();
if (nonNullField != null) {
storedField = FieldAnnotation.fromXField( nonNullField );
bugType = "NP_STORE_INTO_NONNULL_FIELD";
} else {
XMethodParameter nonNullParameter = pu.getNonNullParameter();
if (nonNullParameter != null) {
XMethodParameter mp = nonNullParameter ;
invokedMethod = MethodAnnotation.fromXMethod(mp.getMethod());
parameterNumber = mp.getParameterNumber();
bugType = "NP_NULL_PARAM_DEREF";
}
}
}
} else if (!deref.isAlwaysOnExceptionPath())
bugType = "NP_NULL_ON_SOME_PATH";
else
bugType = "NP_NULL_ON_SOME_PATH_EXCEPTION";
if (deref.isMethodReturnValue())
bugType = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE";
}
XMethod calledFrom = XFactory.createXMethod(classContext.getJavaClass(), method);
boolean uncallable = !AnalysisContext.currentXFactory().isCalledDirectlyOrIndirectly(calledFrom)
&& !calledFrom.isPublic() && !(calledFrom.isProtected() && classContext.getJavaClass().isPublic());
if (uncallable) priority++;
BugInstance bugInstance = new BugInstance(this, bugType, priority)
.addClassAndMethod(classContext.getJavaClass(), method);
if (invokedMethod != null)
bugInstance.addMethod(invokedMethod).describe("METHOD_CALLED")
.addInt(parameterNumber+1).describe("INT_MAYBE_NULL_ARG");
if (storedField!= null)
bugInstance.addField(storedField).describe("FIELD_STORED");
bugInstance.add(variableAnnotation);
if (variableAnnotation instanceof FieldAnnotation)
bugInstance.describe("FIELD_CONTAINS_VALUE");
for (Location loc : derefLocationSet)
bugInstance.addSourceLine(classContext, method, loc).describe(getDescription(loc, refValue));
for (SourceLineAnnotation sourceLineAnnotation : knownNullLocations)
bugInstance.add(sourceLineAnnotation).describe(
"SOURCE_LINE_KNOWN_NULL");
// If all deref locations are doomed
// (i.e., locations where a normal return is not possible),
// add a warning property indicating such.
// Are all derefs at doomed locations?
boolean allDerefsAtDoomedLocations = true;
for (Location derefLoc : derefLocationSet) {
if (!isDoomed(derefLoc)) {
allDerefsAtDoomedLocations = false;
break;
}
}
WarningPropertySet<WarningProperty> propertySet = new WarningPropertySet<WarningProperty>();
if (allDerefsAtDoomedLocations) {
// Add a WarningProperty
propertySet.addProperty(DoomedCodeWarningProperty.DOOMED_CODE);
}
if (uncallable)
propertySet.addProperty(GeneralWarningProperty.IN_UNCALLABLE_METHOD);
propertySet.decorateBugInstance(bugInstance);
// Report it
bugReporter.reportBug(bugInstance);
}
private boolean isDoomed(Location loc) {
if (!MARK_DOOMED) {
return false;
}
ReturnPathTypeDataflow rptDataflow;
try {
rptDataflow = classContext.getReturnPathTypeDataflow(method);
ReturnPathType rpt = rptDataflow.getFactAtLocation(loc);
return !rpt.canReturnNormally();
} catch (CheckedAnalysisException e) {
AnalysisContext.logError("Error getting return path type", e);
return false;
}
}
String getDescription(Location loc, ValueNumber refValue) {
PointerUsageRequiringNonNullValue pu;
try {
UsagesRequiringNonNullValues usages = classContext.getUsagesRequiringNonNullValues(method);
pu = usages.get(loc, refValue);
if (pu == null) return "SOURCE_LINE_DEREF";
return pu.getDescription();
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("Error getting UsagesRequiringNonNullValues for " + method, e);
return "SOURCE_LINE_DEREF";
} catch (CFGBuilderException e) {
AnalysisContext.logError("Error getting UsagesRequiringNonNullValues for " + method, e);
return "SOURCE_LINE_DEREF";
}
}
boolean inCatchNullBlock(Location loc) {
int pc = loc.getHandle().getPosition();
int catchSize = Util.getSizeOfSurroundingTryBlock(classContext.getJavaClass().getConstantPool(), method.getCode(),
"java/lang/NullPointerException", pc);
if (catchSize < Integer.MAX_VALUE)
return true;
catchSize = Util.getSizeOfSurroundingTryBlock(classContext.getJavaClass().getConstantPool(), method.getCode(),
"java/lang/Exception", pc);
if (catchSize < 5)
return true;
catchSize = Util.getSizeOfSurroundingTryBlock(classContext.getJavaClass().getConstantPool(), method.getCode(),
"java/lang/RuntimeException", pc);
if (catchSize < 5)
return true;
catchSize = Util.getSizeOfSurroundingTryBlock(classContext.getJavaClass().getConstantPool(), method.getCode(),
"java/lang/Throwable", pc);
if (catchSize < 5)
return true;
return false;
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs.detect;
import java.util.*;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.*;
import edu.umd.cs.daveho.ba.*;
import edu.umd.cs.findbugs.*;
/**
* A Detector to find instructions where a NullPointerException
* might be raised. We also look for useless reference comparisons
* involving null and non-null values.
*
* @see IsNullValueAnalysis
* @author David Hovemeyer
*/
public class FindNullDeref implements Detector {
/**
* An instruction recorded as a redundant reference comparison.
* We keep track of the line number, in order to ensure that if
* the branch was duplicated, all duplicates are determined in
* the same way. (If they aren't, then we don't report it.)
*/
private static class RedundantBranch {
public final InstructionHandle handle;
public final int lineNumber;
public RedundantBranch(InstructionHandle handle, int lineNumber) {
this.handle = handle;
this.lineNumber = lineNumber;
}
}
private static final boolean DEBUG = Boolean.getBoolean("fnd.debug");
private BugReporter bugReporter;
private List<RedundantBranch> redundantBranchList;
private BitSet definitelySameBranchSet;
private BitSet definitelyDifferentBranchSet;
private BitSet undeterminedBranchSet;
public FindNullDeref(BugReporter bugReporter) {
this.bugReporter = bugReporter;
this.redundantBranchList = new LinkedList<RedundantBranch>();
this.definitelySameBranchSet = new BitSet();
this.definitelyDifferentBranchSet = new BitSet();
this.undeterminedBranchSet = new BitSet();
}
public void visitClassContext(ClassContext classContext) {
try {
JavaClass jclass = classContext.getJavaClass();
Method[] methodList = jclass.getMethods();
for (int i = 0; i < methodList.length; ++i) {
Method method = methodList[i];
if (method.isAbstract() || method.isNative() || method.getCode() == null)
continue;
analyzeMethod(classContext, method);
}
} catch (DataflowAnalysisException e) {
throw new AnalysisException("FindNullDeref caught exception", e);
} catch (CFGBuilderException e) {
throw new AnalysisException(e.getMessage());
}
}
private void analyzeMethod(ClassContext classContext, Method method)
throws CFGBuilderException, DataflowAnalysisException {
JavaClass jclass = classContext.getJavaClass();
redundantBranchList.clear();
definitelySameBranchSet.clear();
definitelyDifferentBranchSet.clear();
undeterminedBranchSet.clear();
if (DEBUG)
System.out.println(SignatureConverter.convertMethodSignature(classContext.getMethodGen(method)));
// Get the IsNullValueAnalysis for the method from the ClassContext
IsNullValueDataflow invDataflow = classContext.getIsNullValueDataflow(method);
// Look for null check blocks where the reference being checked
// is definitely null, or null on some path
Iterator<BasicBlock> bbIter = invDataflow.getCFG().blockIterator();
while (bbIter.hasNext()) {
BasicBlock basicBlock = bbIter.next();
if (basicBlock.isNullCheck()) {
analyzeNullCheck(classContext, method, invDataflow, basicBlock);
} else if (!basicBlock.isEmpty()) {
// Look for all reference comparisons where
// - both values compared are definitely null, or
// - one value is definitely null and one is definitely not null
// These cases are not null dereferences,
// but they are quite likely to indicate an error, so while we've got
// information about null values, we may as well report them.
InstructionHandle lastHandle = basicBlock.getLastInstruction();
Instruction last = lastHandle.getInstruction();
switch (last.getOpcode()) {
case Constants.IF_ACMPEQ:
case Constants.IF_ACMPNE:
analyzeRefComparisonBranch(method, invDataflow, basicBlock, lastHandle);
break;
case Constants.IFNULL:
case Constants.IFNONNULL:
analyzeIfNullBranch(method, invDataflow, basicBlock, lastHandle);
break;
}
}
}
Iterator<RedundantBranch> i = redundantBranchList.iterator();
while (i.hasNext()) {
RedundantBranch redundantBranch = i.next();
InstructionHandle handle = redundantBranch.handle;
int lineNumber = redundantBranch.lineNumber;
// The source to bytecode compiler may sometimes duplicate blocks of
// code along different control paths. So, to report the bug,
// we check to ensure that the branch is REALLY determined each
// place it is duplicated, and that it is determined in the same way.
if (!undeterminedBranchSet.get(lineNumber) &&
!(definitelySameBranchSet.get(lineNumber) && definitelyDifferentBranchSet.get(lineNumber))) {
reportUselessControlFlow(classContext, method, handle);
}
}
}
private void analyzeNullCheck(ClassContext classContext, Method method, IsNullValueDataflow invDataflow,
BasicBlock basicBlock)
throws DataflowAnalysisException {
// Look for null checks where the value checked is definitely
// null or null on some path.
InstructionHandle exceptionThrowerHandle = basicBlock.getExceptionThrower();
Instruction exceptionThrower = exceptionThrowerHandle.getInstruction();
// Figure out where the reference operand is in the stack frame.
int consumed = exceptionThrower.consumeStack(classContext.getConstantPoolGen());
if (consumed == Constants.UNPREDICTABLE)
throw new DataflowAnalysisException("Unpredictable stack consumption for " + exceptionThrower);
// Get the stack values at entry to the null check.
IsNullValueFrame frame = invDataflow.getStartFact(basicBlock);
// Could the reference be null?
IsNullValue refValue = frame.getValue(frame.getNumSlots() - consumed);
boolean onExceptionPath = refValue.isException();
if (refValue.isDefinitelyNull()) {
String type = onExceptionPath ? "NP_ALWAYS_NULL_EXCEPTION" : "NP_ALWAYS_NULL";
int priority = onExceptionPath ? LOW_PRIORITY : HIGH_PRIORITY;
reportNullDeref(classContext, method, exceptionThrowerHandle, type, priority);
} else if (refValue.isNullOnSomePath()) {
String type = onExceptionPath ? "NP_NULL_ON_SOME_PATH_EXCEPTION" : "NP_NULL_ON_SOME_PATH";
int priority = onExceptionPath ? LOW_PRIORITY : NORMAL_PRIORITY;
reportNullDeref(classContext, method, exceptionThrowerHandle, type, priority);
}
}
private void analyzeRefComparisonBranch(Method method, IsNullValueDataflow invDataflow, BasicBlock basicBlock,
InstructionHandle lastHandle) throws DataflowAnalysisException {
IsNullValueFrame frame = invDataflow.getFactAtLocation(new Location(lastHandle, basicBlock));
if (frame.getStackDepth() < 2)
throw new AnalysisException("Stack underflow at " + lastHandle);
// Find the line number.
int lineNumber = getLineNumber(method, lastHandle);
if (lineNumber < 0)
return;
int numSlots = frame.getNumSlots();
IsNullValue top = frame.getValue(numSlots - 1);
IsNullValue topNext = frame.getValue(numSlots - 2);
boolean definitelySame = top.isDefinitelyNull() && topNext.isDefinitelyNull();
boolean definitelyDifferent =
(top.isDefinitelyNull() && topNext.isDefinitelyNotNull()) ||
(top.isDefinitelyNotNull() && topNext.isDefinitelyNull());
if (definitelySame || definitelyDifferent) {
if (definitelySame) {
if (DEBUG) System.out.println("Line " + lineNumber + " always same");
definitelySameBranchSet.set(lineNumber);
}
if (definitelyDifferent) {
if (DEBUG) System.out.println("Line " + lineNumber + " always different");
definitelyDifferentBranchSet.set(lineNumber);
}
//reportUselessControlFlow(classContext, method, lastHandle);
redundantBranchList.add(new RedundantBranch(lastHandle, lineNumber));
} else {
if (DEBUG) System.out.println("Line " + lineNumber + " undetermined");
undeterminedBranchSet.set(lineNumber);
}
}
private void analyzeIfNullBranch(Method method, IsNullValueDataflow invDataflow, BasicBlock basicBlock,
InstructionHandle lastHandle) throws DataflowAnalysisException {
IsNullValueFrame frame = invDataflow.getFactAtLocation(new Location(lastHandle, basicBlock));
IsNullValue top = frame.getTopValue();
// Find the line number.
int lineNumber = getLineNumber(method, lastHandle);
if (lineNumber < 0)
return;
boolean definitelySame = top.isDefinitelyNull();
boolean definitelyDifferent = top.isDefinitelyNotNull();
if (definitelySame || definitelyDifferent) {
if (definitelySame) {
if (DEBUG) System.out.println("Line " + lineNumber + " always same");
definitelySameBranchSet.set(lineNumber);
}
if (definitelyDifferent) {
if (DEBUG) System.out.println("Line " + lineNumber + " always different");
definitelyDifferentBranchSet.set(lineNumber);
}
//reportUselessControlFlow(classContext, method, lastHandle);
} else {
if (DEBUG) System.out.println("Line " + lineNumber + " undetermined");
undeterminedBranchSet.set(lineNumber);
}
}
private static int getLineNumber(Method method, InstructionHandle handle) {
LineNumberTable table = method.getCode().getLineNumberTable();
if (table == null)
return -1;
return table.getSourceLine(handle.getPosition());
}
private void reportNullDeref(ClassContext classContext, Method method, InstructionHandle exceptionThrowerHandle,
String type, int priority) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
bugReporter.reportBug(new BugInstance(type, priority)
.addClassAndMethod(methodGen, sourceFile)
.addSourceLine(methodGen, sourceFile, exceptionThrowerHandle)
//.addInt(exceptionThrowerHandle.getPosition()).describe("INT_BYTECODE_OFFSET")
);
}
private void reportUselessControlFlow(ClassContext classContext, Method method, InstructionHandle handle) {
String sourceFile = classContext.getJavaClass().getSourceFileName();
MethodGen methodGen = classContext.getMethodGen(method);
bugReporter.reportBug(new BugInstance("UCF_USELESS_NULL_REF_COMPARISON", NORMAL_PRIORITY)
.addClassAndMethod(methodGen, sourceFile)
.addSourceLine(methodGen, sourceFile, handle));
}
public void report() {
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs.detect;
import java.util.BitSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LineNumberTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ATHROW;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.bcel.generic.ReturnInstruction;
import edu.umd.cs.findbugs.BugAnnotation;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.FieldAnnotation;
import edu.umd.cs.findbugs.FindBugsAnalysisFeatures;
import edu.umd.cs.findbugs.LocalVariableAnnotation;
import edu.umd.cs.findbugs.MethodAnnotation;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.DataflowValueChooser;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.Hierarchy;
import edu.umd.cs.findbugs.ba.JavaClassAndMethod;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.MissingClassException;
import edu.umd.cs.findbugs.ba.NullnessAnnotation;
import edu.umd.cs.findbugs.ba.NullnessAnnotationDatabase;
import edu.umd.cs.findbugs.ba.SignatureConverter;
import edu.umd.cs.findbugs.ba.SignatureParser;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.XMethodParameter;
import edu.umd.cs.findbugs.ba.interproc.PropertyDatabase;
import edu.umd.cs.findbugs.ba.npe.IsNullValue;
import edu.umd.cs.findbugs.ba.npe.IsNullValueDataflow;
import edu.umd.cs.findbugs.ba.npe.IsNullValueFrame;
import edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonCollector;
import edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonFinder;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessProperty;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessPropertyDatabase;
import edu.umd.cs.findbugs.ba.npe.PointerUsageRequiringNonNullValue;
import edu.umd.cs.findbugs.ba.npe.RedundantBranch;
import edu.umd.cs.findbugs.ba.npe.ReturnPathType;
import edu.umd.cs.findbugs.ba.npe.ReturnPathTypeDataflow;
import edu.umd.cs.findbugs.ba.npe.UsagesRequiringNonNullValues;
import edu.umd.cs.findbugs.ba.type.TypeDataflow;
import edu.umd.cs.findbugs.ba.type.TypeFrame;
import edu.umd.cs.findbugs.ba.vna.ValueNumber;
import edu.umd.cs.findbugs.ba.vna.ValueNumberDataflow;
import edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.props.GeneralWarningProperty;
import edu.umd.cs.findbugs.props.WarningPropertySet;
import edu.umd.cs.findbugs.props.WarningPropertyUtil;
import edu.umd.cs.findbugs.visitclass.Util;
/**
* A Detector to find instructions where a NullPointerException might be raised.
* We also look for useless reference comparisons involving null and non-null
* values.
*
* @author David Hovemeyer
* @author William Pugh
* @see edu.umd.cs.findbugs.ba.npe.IsNullValueAnalysis
*/
public class FindNullDeref implements Detector,
NullDerefAndRedundantComparisonCollector {
public static final boolean DEBUG = SystemProperties
.getBoolean("fnd.debug");
private static final boolean DEBUG_NULLARG = SystemProperties
.getBoolean("fnd.debug.nullarg");
private static final boolean DEBUG_NULLRETURN = SystemProperties
.getBoolean("fnd.debug.nullreturn");
private static final boolean MARK_DOOMED = SystemProperties
.getBoolean("fnd.markdoomed", true);
private static final boolean REPORT_SAFE_METHOD_TARGETS = true;
private static final String METHOD = SystemProperties
.getProperty("fnd.method");
private static final String CLASS = SystemProperties
.getProperty("fnd.class");
// Fields
private BugReporter bugReporter;
// Cached database stuff
private ParameterNullnessPropertyDatabase unconditionalDerefParamDatabase;
private boolean checkedDatabases = false;
// Transient state
private ClassContext classContext;
private Method method;
private IsNullValueDataflow invDataflow;
private BitSet previouslyDeadBlocks;
private NullnessAnnotation methodAnnotation;
public FindNullDeref(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visitClassContext(ClassContext classContext) {
this.classContext = classContext;
String currentMethod = null;
JavaClass jclass = classContext.getJavaClass();
String className = jclass.getClassName();
if (CLASS != null && !className.equals(CLASS))
return;
Method[] methodList = jclass.getMethods();
for (Method method : methodList) {
try {
if (method.isAbstract() || method.isNative()
|| method.getCode() == null)
continue;
MethodGen mg = classContext.getMethodGen(method);
if (mg == null) {
continue;
}
currentMethod = SignatureConverter.convertMethodSignature(mg);
if (METHOD != null && !method.getName().equals(METHOD))
continue;
if (DEBUG)
System.out.println("Checking for NP in " + currentMethod);
analyzeMethod(classContext, method);
} catch (MissingClassException e) {
bugReporter.reportMissingClass(e.getClassNotFoundException());
} catch (DataflowAnalysisException e) {
bugReporter.logError("While analyzing " + currentMethod
+ ": FindNullDeref caught dae exception", e);
} catch (CFGBuilderException e) {
bugReporter.logError("While analyzing " + currentMethod
+ ": FindNullDeref caught cfgb exception", e);
}
}
}
private void analyzeMethod(ClassContext classContext, Method method)
throws CFGBuilderException, DataflowAnalysisException {
if (DEBUG || DEBUG_NULLARG)
System.out.println("Pre FND ");
MethodGen methodGen = classContext.getMethodGen(method);
if (methodGen == null)
return;
if (!checkedDatabases) {
checkDatabases();
checkedDatabases = true;
}
// UsagesRequiringNonNullValues uses =
// classContext.getUsagesRequiringNonNullValues(method);
this.method = method;
this.methodAnnotation = getMethodNullnessAnnotation();
if (DEBUG || DEBUG_NULLARG)
System.out.println("FND: "
+ SignatureConverter.convertMethodSignature(methodGen));
this.previouslyDeadBlocks = findPreviouslyDeadBlocks();
// Get the IsNullValueDataflow for the method from the ClassContext
invDataflow = classContext.getIsNullValueDataflow(method);
// Create a NullDerefAndRedundantComparisonFinder object to do the
// actual
// work. It will call back to report null derefs and redundant null
// comparisons
// through the NullDerefAndRedundantComparisonCollector interface we
// implement.
NullDerefAndRedundantComparisonFinder worker = new NullDerefAndRedundantComparisonFinder(
classContext, method, this);
worker.execute();
checkCallSitesAndReturnInstructions();
}
/**
* Find set of blocks which were known to be dead before doing the null
* pointer analysis.
*
* @return set of previously dead blocks, indexed by block id
* @throws CFGBuilderException
* @throws DataflowAnalysisException
*/
private BitSet findPreviouslyDeadBlocks() throws DataflowAnalysisException,
CFGBuilderException {
BitSet deadBlocks = new BitSet();
ValueNumberDataflow vnaDataflow = classContext
.getValueNumberDataflow(method);
for (Iterator<BasicBlock> i = vnaDataflow.getCFG().blockIterator(); i
.hasNext();) {
BasicBlock block = i.next();
ValueNumberFrame vnaFrame = vnaDataflow.getStartFact(block);
if (vnaFrame.isTop()) {
deadBlocks.set(block.getId());
}
}
return deadBlocks;
}
/**
* Check whether or not the various interprocedural databases we can use
* exist and are nonempty.
*/
private void checkDatabases() {
AnalysisContext analysisContext = AnalysisContext
.currentAnalysisContext();
unconditionalDerefParamDatabase = analysisContext
.getUnconditionalDerefParamDatabase();
}
private <DatabaseType extends PropertyDatabase<?, ?>> boolean isDatabaseNonEmpty(
DatabaseType database) {
return database != null && !database.isEmpty();
}
/**
* See if the currently-visited method declares a
*
* @NonNull annotation, or overrides a method which declares a
* @NonNull annotation.
*/
private NullnessAnnotation getMethodNullnessAnnotation() {
if (method.getSignature().indexOf(")L") >= 0
|| method.getSignature().indexOf(")[") >= 0) {
if (DEBUG_NULLRETURN) {
System.out.println("Checking return annotation for "
+ SignatureConverter.convertMethodSignature(
classContext.getJavaClass(), method));
}
XMethod m = XFactory.createXMethod(classContext.getJavaClass(),
method);
return AnalysisContext.currentAnalysisContext()
.getNullnessAnnotationDatabase().getResolvedAnnotation(m,
false);
}
return NullnessAnnotation.UNKNOWN_NULLNESS;
}
private void checkCallSitesAndReturnInstructions()
throws CFGBuilderException, DataflowAnalysisException {
ConstantPoolGen cpg = classContext.getConstantPoolGen();
TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
for (Iterator<Location> i = classContext.getCFG(method)
.locationIterator(); i.hasNext();) {
Location location = i.next();
Instruction ins = location.getHandle().getInstruction();
try {
if (ins instanceof InvokeInstruction) {
examineCallSite(location, cpg, typeDataflow);
} else if (methodAnnotation == NullnessAnnotation.NONNULL
&& ins.getOpcode() == Constants.ARETURN) {
examineReturnInstruction(location);
} else if (ins instanceof PUTFIELD) {
examinePutfieldInstruction(location, (PUTFIELD) ins, cpg);
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
}
}
private void examineCallSite(Location location, ConstantPoolGen cpg,
TypeDataflow typeDataflow) throws DataflowAnalysisException,
CFGBuilderException, ClassNotFoundException {
InvokeInstruction invokeInstruction = (InvokeInstruction) location
.getHandle().getInstruction();
String methodName = invokeInstruction.getName(cpg);
String signature = invokeInstruction.getSignature(cpg);
// Don't check equals() calls.
// If an equals() call unconditionally dereferences the parameter,
// it is the fault of the method, not the caller.
if (methodName.equals("equals")
&& signature.equals("(Ljava/lang/Object;)Z"))
return;
int returnTypeStart = signature.indexOf(')');
if (returnTypeStart < 0)
return;
String paramList = signature.substring(0, returnTypeStart + 1);
if (paramList.equals("()")
|| (paramList.indexOf("L") < 0 && paramList.indexOf('[') < 0))
// Method takes no arguments, or takes no reference arguments
return;
// See if any null arguments are passed
IsNullValueFrame frame = classContext.getIsNullValueDataflow(method)
.getFactAtLocation(location);
if (!frame.isValid())
return;
BitSet nullArgSet = frame.getArgumentSet(invokeInstruction, cpg,
new DataflowValueChooser<IsNullValue>() {
public boolean choose(IsNullValue value) {
// Only choose non-exception values.
// Values null on an exception path might be due to
// infeasible control flow.
return value.mightBeNull() && !value.isException()
&& !value.isReturnValue();
}
});
BitSet definitelyNullArgSet = frame.getArgumentSet(invokeInstruction,
cpg, new DataflowValueChooser<IsNullValue>() {
public boolean choose(IsNullValue value) {
return value.isDefinitelyNull();
}
});
nullArgSet.and(definitelyNullArgSet);
if (nullArgSet.isEmpty())
return;
if (DEBUG_NULLARG) {
System.out.println("Null arguments passed: " + nullArgSet);
System.out.println("Frame is: " + frame);
System.out.println("# arguments: "
+ frame.getNumArguments(invokeInstruction, cpg));
XMethod xm = XFactory.createXMethod(invokeInstruction, cpg);
System.out.print("Signature: " + xm.getSignature());
}
if (unconditionalDerefParamDatabase != null) {
checkUnconditionallyDereferencedParam(location, cpg, typeDataflow,
invokeInstruction, nullArgSet, definitelyNullArgSet);
}
if (DEBUG_NULLARG) {
System.out.println("Checking nonnull params");
}
checkNonNullParam(location, cpg, typeDataflow, invokeInstruction,
nullArgSet, definitelyNullArgSet);
}
private void examinePutfieldInstruction(Location location, PUTFIELD ins,
ConstantPoolGen cpg) throws DataflowAnalysisException,
CFGBuilderException {
IsNullValueDataflow invDataflow = classContext
.getIsNullValueDataflow(method);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
if (!frame.isValid())
return;
IsNullValue tos = frame.getTopValue();
if (tos.isDefinitelyNull()) {
XField field = XFactory.createXField(ins, cpg);
NullnessAnnotation annotation = AnalysisContext
.currentAnalysisContext().getNullnessAnnotationDatabase()
.getResolvedAnnotation(field, false);
if (annotation == NullnessAnnotation.NONNULL) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass()
.getSourceFileName();
BugAnnotation variableAnnotation = null;
try {
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
ValueNumber valueNumber = vnaFrame.getTopValue();
variableAnnotation = NullDerefAndRedundantComparisonFinder.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("error", e);
} catch (CFGBuilderException e) {
AnalysisContext.logError("error", e);
}
BugInstance warning = new BugInstance(this,
"NP_STORE_INTO_NONNULL_FIELD",
tos.isDefinitelyNull() ? HIGH_PRIORITY
: NORMAL_PRIORITY).addClassAndMethod(methodGen,
sourceFile).addField(field).addOptionalAnnotation(variableAnnotation).addSourceLine(classContext,
methodGen, sourceFile, location.getHandle());
bugReporter.reportBug(warning);
}
}
}
private void examineReturnInstruction(Location location)
throws DataflowAnalysisException, CFGBuilderException {
if (DEBUG_NULLRETURN) {
System.out.println("Checking null return at " + location);
}
IsNullValueDataflow invDataflow = classContext
.getIsNullValueDataflow(method);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
ValueNumber valueNumber = vnaFrame.getTopValue();
if (!frame.isValid())
return;
IsNullValue tos = frame.getTopValue();
if (tos.isDefinitelyNull()) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugAnnotation variable = NullDerefAndRedundantComparisonFinder.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
String bugPattern = "NP_NONNULL_RETURN_VIOLATION";
int priority = NORMAL_PRIORITY;
if (tos.isDefinitelyNull() && !tos.isException())
priority = HIGH_PRIORITY;
String methodName = method.getName();
if (methodName.equals("clone")) {
bugPattern = "NP_CLONE_COULD_RETURN_NULL";
priority = NORMAL_PRIORITY;
} else if (methodName.equals("toString")) {
bugPattern = "NP_TOSTRING_COULD_RETURN_NULL";
priority = NORMAL_PRIORITY;
}
BugInstance warning = new BugInstance(this, bugPattern, priority)
.addClassAndMethod(methodGen, sourceFile).addOptionalAnnotation(variable).addSourceLine(
classContext, methodGen, sourceFile,
location.getHandle());
bugReporter.reportBug(warning);
}
}
private void checkUnconditionallyDereferencedParam(Location location,
ConstantPoolGen cpg, TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction, BitSet nullArgSet,
BitSet definitelyNullArgSet) throws DataflowAnalysisException,
ClassNotFoundException {
boolean caught = inCatchNullBlock(location);
if (caught && skipIfInsideCatchNull())
return;
// See what methods might be called here
TypeFrame typeFrame = typeDataflow.getFactAtLocation(location);
Set<JavaClassAndMethod> targetMethodSet = Hierarchy
.resolveMethodCallTargets(invokeInstruction, typeFrame, cpg);
if (DEBUG_NULLARG) {
System.out.println("Possibly called methods: " + targetMethodSet);
}
// See if any call targets unconditionally dereference one of the null
// arguments
BitSet unconditionallyDereferencedNullArgSet = new BitSet();
List<JavaClassAndMethod> dangerousCallTargetList = new LinkedList<JavaClassAndMethod>();
List<JavaClassAndMethod> veryDangerousCallTargetList = new LinkedList<JavaClassAndMethod>();
for (JavaClassAndMethod targetMethod : targetMethodSet) {
if (DEBUG_NULLARG) {
System.out.println("For target method " + targetMethod);
}
ParameterNullnessProperty property = unconditionalDerefParamDatabase
.getProperty(targetMethod.toXMethod());
if (property == null)
continue;
if (DEBUG_NULLARG) {
System.out.println("\tUnconditionally dereferenced params: "
+ property);
}
BitSet targetUnconditionallyDereferencedNullArgSet = property
.getViolatedParamSet(nullArgSet);
if (targetUnconditionallyDereferencedNullArgSet.isEmpty())
continue;
dangerousCallTargetList.add(targetMethod);
unconditionallyDereferencedNullArgSet
.or(targetUnconditionallyDereferencedNullArgSet);
if (!property.getViolatedParamSet(definitelyNullArgSet).isEmpty())
veryDangerousCallTargetList.add(targetMethod);
}
if (dangerousCallTargetList.isEmpty())
return;
WarningPropertySet propertySet = new WarningPropertySet();
// See if there are any safe targets
Set<JavaClassAndMethod> safeCallTargetSet = new HashSet<JavaClassAndMethod>();
safeCallTargetSet.addAll(targetMethodSet);
safeCallTargetSet.removeAll(dangerousCallTargetList);
if (safeCallTargetSet.isEmpty()) {
propertySet
.addProperty(NullArgumentWarningProperty.ALL_DANGEROUS_TARGETS);
if (dangerousCallTargetList.size() == 1) {
propertySet
.addProperty(NullArgumentWarningProperty.MONOMORPHIC_CALL_SITE);
}
}
// Call to private method? In theory there should be only one possible
// target.
boolean privateCall = safeCallTargetSet.isEmpty()
&& dangerousCallTargetList.size() == 1
&& dangerousCallTargetList.get(0).getMethod().isPrivate();
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
String bugType;
int priority;
if (privateCall
|| invokeInstruction.getOpcode() == Constants.INVOKESTATIC
|| invokeInstruction.getOpcode() == Constants.INVOKESPECIAL) {
bugType = "NP_NULL_PARAM_DEREF_NONVIRTUAL";
priority = HIGH_PRIORITY;
} else if (safeCallTargetSet.isEmpty()) {
bugType = "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS";
priority = NORMAL_PRIORITY;
} else {
bugType = "NP_NULL_PARAM_DEREF";
priority = LOW_PRIORITY;
}
if (caught)
priority++;
if (dangerousCallTargetList.size() > veryDangerousCallTargetList.size())
priority++;
else
propertySet
.addProperty(NullArgumentWarningProperty.ACTUAL_PARAMETER_GUARANTEED_NULL);
BugInstance warning = new BugInstance(this,bugType, priority)
.addClassAndMethod(methodGen, sourceFile).addMethod(
XFactory.createXMethod(invokeInstruction, cpg))
.describe("METHOD_CALLED").addSourceLine(classContext,
methodGen, sourceFile, location.getHandle());
// Check which params might be null
addParamAnnotations(definitelyNullArgSet,
unconditionallyDereferencedNullArgSet, propertySet, warning);
// Add annotations for dangerous method call targets
for (JavaClassAndMethod dangerousCallTarget : veryDangerousCallTargetList) {
warning.addMethod(dangerousCallTarget).describe(
"METHOD_DANGEROUS_TARGET_ACTUAL_GUARANTEED_NULL");
}
dangerousCallTargetList.removeAll(veryDangerousCallTargetList);
// Add annotations for dangerous method call targets
for (JavaClassAndMethod dangerousCallTarget : dangerousCallTargetList) {
warning.addMethod(dangerousCallTarget).describe(
"METHOD_DANGEROUS_TARGET");
}
// Add safe method call targets.
// This is useful to see which other call targets the analysis
// considered.
for (JavaClassAndMethod safeMethod : safeCallTargetSet) {
warning.addMethod(safeMethod).describe("METHOD_SAFE_TARGET");
}
decorateWarning(location, propertySet, warning);
bugReporter.reportBug(warning);
}
private void decorateWarning(Location location,
WarningPropertySet propertySet, BugInstance warning) {
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertyUtil.addPropertiesForLocation(propertySet,
classContext, method, location);
}
propertySet.decorateBugInstance(warning);
}
private void addParamAnnotations(BitSet definitelyNullArgSet,
BitSet violatedParamSet, WarningPropertySet propertySet,
BugInstance warning) {
for (int i = 0; i < 32; ++i) {
if (violatedParamSet.get(i)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (definitelyNull) {
propertySet
.addProperty(NullArgumentWarningProperty.ARG_DEFINITELY_NULL);
}
// Note: we report params as being indexed starting from 1, not
warning.addInt(i + 1).describe(
definitelyNull ? "INT_NULL_ARG" : "INT_MAYBE_NULL_ARG");
}
}
}
/**
* We have a method invocation in which a possibly or definitely null
* parameter is passed. Check it against the library of nonnull annotations.
*
* @param location
* @param cpg
* @param typeDataflow
* @param invokeInstruction
* @param nullArgSet
* @param definitelyNullArgSet
* @throws ClassNotFoundException
*/
private void checkNonNullParam(Location location, ConstantPoolGen cpg,
TypeDataflow typeDataflow, InvokeInstruction invokeInstruction,
BitSet nullArgSet, BitSet definitelyNullArgSet)
throws ClassNotFoundException {
boolean caught = inCatchNullBlock(location);
if (caught && skipIfInsideCatchNull())
return;
XMethod m = XFactory.createXMethod(invokeInstruction, cpg);
NullnessAnnotationDatabase db = AnalysisContext
.currentAnalysisContext().getNullnessAnnotationDatabase();
SignatureParser sigParser = new SignatureParser(invokeInstruction.getSignature(cpg));
for (int i = nullArgSet.nextSetBit(0); i >= 0; i = nullArgSet
.nextSetBit(i + 1)) {
if (db.parameterMustBeNonNull(m, i)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (DEBUG_NULLARG) {
System.out.println("QQQ2: " + i + " -- " + i + " is null");
System.out.println("QQQ nullArgSet: " + nullArgSet);
System.out.println("QQQ dnullArgSet: "
+ definitelyNullArgSet);
}
BugAnnotation variableAnnotation = null;
try {
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
ValueNumber valueNumber = vnaFrame. getArgument(invokeInstruction, cpg, i, sigParser );
variableAnnotation = NullDerefAndRedundantComparisonFinder.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("error", e);
} catch (CFGBuilderException e) {
AnalysisContext.logError("error", e);
}
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass()
.getSourceFileName();
int priority = definitelyNull ? HIGH_PRIORITY : NORMAL_PRIORITY;
if (caught)
priority++;
BugInstance warning = new BugInstance(this,
"NP_NONNULL_PARAM_VIOLATION", priority)
.addClassAndMethod(methodGen, sourceFile).addMethod(m)
.describe("METHOD_CALLED").addInt(i).describe(
"INT_NONNULL_PARAM").addOptionalAnnotation(variableAnnotation).addSourceLine(
classContext, methodGen, sourceFile,
location.getHandle());
bugReporter.reportBug(warning);
}
}
}
public void report() {
}
public boolean skipIfInsideCatchNull() {
return classContext.getJavaClass().getClassName().indexOf("Test") >= 0
|| method.getName().indexOf("test") >= 0
|| method.getName().indexOf("Test") >= 0;
}
public void foundNullDeref(ClassContext classContext, Location location,
ValueNumber valueNumber, IsNullValue refValue,
ValueNumberFrame vnaFrame) {
WarningPropertySet propertySet = new WarningPropertySet();
if (valueNumber.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT))
return;
boolean onExceptionPath = refValue.isException();
if (onExceptionPath) {
propertySet.addProperty(GeneralWarningProperty.ON_EXCEPTION_PATH);
}
int pc = location.getHandle().getPosition();
BugAnnotation variable = NullDerefAndRedundantComparisonFinder.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
boolean duplicated = false;
try {
CFG cfg = classContext.getCFG(method);
duplicated = cfg.getLocationsContainingInstructionWithOffset(pc)
.size() > 1;
} catch (CFGBuilderException e) {
}
boolean caught = inCatchNullBlock(location);
if (caught && skipIfInsideCatchNull())
return;
if (!duplicated && refValue.isDefinitelyNull()) {
String type = onExceptionPath ? "NP_ALWAYS_NULL_EXCEPTION"
: "NP_ALWAYS_NULL";
int priority = onExceptionPath ? NORMAL_PRIORITY : HIGH_PRIORITY;
if (caught)
priority++;
reportNullDeref(propertySet, classContext, method, location, type,
priority, variable);
} else if (refValue.isNullOnSomePath() || duplicated
&& refValue.isDefinitelyNull()) {
String type = "NP_NULL_ON_SOME_PATH";
int priority = NORMAL_PRIORITY;
if (caught)
priority++;
if (onExceptionPath)
type = "NP_NULL_ON_SOME_PATH_EXCEPTION";
else if (refValue.isReturnValue())
type = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE";
else if (refValue.isParamValue()) {
if (method.getName().equals("equals")
&& method.getSignature()
.equals("(Ljava/lang/Object;)Z")) {
if (caught)
return;
type = "NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT";
} else
type = "NP_ARGUMENT_MIGHT_BE_NULL";
}
if (DEBUG)
System.out.println("Reporting null on some path: value="
+ refValue);
if (type.equals("NP_NULL_ON_SOME_PATH"))
return;
if (type.equals("NP_NULL_ON_SOME_PATH_EXCEPTION"))
return;
reportNullDeref(propertySet, classContext, method, location, type,
priority, variable);
}
}
private void reportNullDeref(WarningPropertySet propertySet,
ClassContext classContext, Method method, Location location,
String type, int priority, BugAnnotation variable) {
MethodGen methodGen = classContext.getMethodGen(method);
String sourceFile = classContext.getJavaClass().getSourceFileName();
BugInstance bugInstance = new BugInstance(this, type, priority)
.addClassAndMethod(methodGen, sourceFile);
if (variable != null)
bugInstance.add(variable);
else
bugInstance.add(new LocalVariableAnnotation("?", -1, -1));
bugInstance.addSourceLine(classContext, methodGen, sourceFile,
location.getHandle()).describe("SOURCE_LINE_DEREF");
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertyUtil.addPropertiesForLocation(propertySet,
classContext, method, location);
}
if (isDoomed(location)) {
// Add a WarningProperty
propertySet.addProperty(DoomedCodeWarningProperty.DOOMED_CODE);
}
propertySet.decorateBugInstance(bugInstance);
bugReporter.reportBug(bugInstance);
}
public static boolean isThrower(BasicBlock target) {
InstructionHandle ins = target.getFirstInstruction();
int maxCount = 7;
while (ins != null) {
if (maxCount
break;
Instruction i = ins.getInstruction();
if (i instanceof ATHROW) {
return true;
}
if (i instanceof InstructionTargeter
|| i instanceof ReturnInstruction)
return false;
ins = ins.getNext();
}
return false;
}
public void foundRedundantNullCheck(Location location,
RedundantBranch redundantBranch) {
String sourceFile = classContext.getJavaClass().getSourceFileName();
MethodGen methodGen = classContext.getMethodGen(method);
boolean isChecked = redundantBranch.firstValue.isChecked();
boolean wouldHaveBeenAKaboom = redundantBranch.firstValue
.wouldHaveBeenAKaboom();
Location locationOfKaBoom = redundantBranch.firstValue
.getLocationOfKaBoom();
boolean createdDeadCode = false;
boolean infeasibleEdgeSimplyThrowsException = false;
Edge infeasibleEdge = redundantBranch.infeasibleEdge;
if (infeasibleEdge != null) {
if (DEBUG)
System.out.println("Check if " + redundantBranch
+ " creates dead code");
BasicBlock target = infeasibleEdge.getTarget();
if (DEBUG)
System.out.println("Target block is "
+ (target.isExceptionThrower() ? " exception thrower"
: " not exception thrower"));
// If the block is empty, it probably doesn't matter that it was
// killed.
// FIXME: really, we should crawl the immediately reachable blocks
// starting at the target block to see if any of them are dead and
// nonempty.
boolean empty = !target.isExceptionThrower()
&& (target.isEmpty() || isGoto(target.getFirstInstruction()
.getInstruction()));
if (!empty) {
try {
if (classContext.getCFG(method).getNumIncomingEdges(target) > 1) {
if (DEBUG)
System.out
.println("Target of infeasible edge has multiple incoming edges");
empty = true;
}
} catch (CFGBuilderException e) {
assert true; // ignore it
}
}
if (DEBUG)
System.out.println("Target block is "
+ (empty ? "empty" : "not empty"));
if (!empty) {
if (isThrower(target))
infeasibleEdgeSimplyThrowsException = true;
}
if (!empty && !previouslyDeadBlocks.get(target.getId())) {
if (DEBUG)
System.out.println("target was alive previously");
// Block was not dead before the null pointer analysis.
// See if it is dead now by inspecting the null value frame.
// If it's TOP, then the block became dead.
IsNullValueFrame invFrame = invDataflow.getStartFact(target);
createdDeadCode = invFrame.isTop();
if (DEBUG)
System.out.println("target is now "
+ (createdDeadCode ? "dead" : "alive"));
}
}
int priority;
boolean valueIsNull = true;
String warning;
if (redundantBranch.secondValue == null) {
if (redundantBranch.firstValue.isDefinitelyNull()) {
warning = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE";
priority = NORMAL_PRIORITY;
} else {
warning = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE";
valueIsNull = false;
priority = isChecked ? NORMAL_PRIORITY : LOW_PRIORITY;
}
} else {
boolean bothNull = redundantBranch.firstValue.isDefinitelyNull()
&& redundantBranch.secondValue.isDefinitelyNull();
if (redundantBranch.secondValue.isChecked())
isChecked = true;
if (redundantBranch.secondValue.wouldHaveBeenAKaboom()) {
wouldHaveBeenAKaboom = true;
locationOfKaBoom = redundantBranch.secondValue
.getLocationOfKaBoom();
}
if (bothNull) {
warning = "RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES";
priority = NORMAL_PRIORITY;
} else {
warning = "RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE";
priority = isChecked ? NORMAL_PRIORITY : LOW_PRIORITY;
}
}
if (wouldHaveBeenAKaboom) {
priority = HIGH_PRIORITY;
warning = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE";
if (locationOfKaBoom == null)
throw new NullPointerException("location of KaBoom is null");
}
if (DEBUG)
System.out.println(createdDeadCode + " "
+ infeasibleEdgeSimplyThrowsException + " " + valueIsNull
+ " " + priority);
if (createdDeadCode && !infeasibleEdgeSimplyThrowsException) {
priority += 0;
} else if (createdDeadCode && infeasibleEdgeSimplyThrowsException) {
// throw clause
if (valueIsNull)
priority += 0;
else
priority += 1;
} else {
// didn't create any dead code
priority += 1;
}
if (DEBUG) {
System.out.println("RCN" + priority + " "
+ redundantBranch.firstValue + " =? "
+ redundantBranch.secondValue + " : " + warning);
if (isChecked)
System.out.println("isChecked");
if (wouldHaveBeenAKaboom)
System.out.println("wouldHaveBeenAKaboom");
if (createdDeadCode)
System.out.println("createdDeadCode");
}
BugAnnotation variableAnnotation = null;
try {
// Get the value number
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(
method).getFactAtLocation(location);
if (vnaFrame.isValid()) {
Instruction ins = location.getHandle().getInstruction();
ValueNumber valueNumber = vnaFrame.getInstance(ins,
classContext.getConstantPoolGen());
if (valueNumber.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT))
return;
variableAnnotation = NullDerefAndRedundantComparisonFinder.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
}
} catch (DataflowAnalysisException e) {
// ignore
} catch (CFGBuilderException e) {
// ignore
}
BugInstance bugInstance = new BugInstance(this, warning, priority)
.addClassAndMethod(methodGen, sourceFile);
if (variableAnnotation != null)
bugInstance.add(variableAnnotation);
else
bugInstance.add(new LocalVariableAnnotation("?", -1, -1));
if (wouldHaveBeenAKaboom)
bugInstance.addSourceLine(classContext, methodGen, sourceFile,
locationOfKaBoom.getHandle());
bugInstance.addSourceLine(classContext, methodGen, sourceFile,
location.getHandle()).describe("SOURCE_REDUNDANT_NULL_CHECK");
if (FindBugsAnalysisFeatures.isRelaxedMode()) {
WarningPropertySet propertySet = new WarningPropertySet();
WarningPropertyUtil.addPropertiesForLocation(propertySet,
classContext, method, location);
if (isChecked)
propertySet.addProperty(NullDerefProperty.CHECKED_VALUE);
if (wouldHaveBeenAKaboom)
propertySet
.addProperty(NullDerefProperty.WOULD_HAVE_BEEN_A_KABOOM);
if (createdDeadCode)
propertySet.addProperty(NullDerefProperty.CREATED_DEAD_CODE);
propertySet.decorateBugInstance(bugInstance);
priority = propertySet.computePriority(NORMAL_PRIORITY);
bugInstance.setPriority(priority);
}
bugReporter.reportBug(bugInstance);
}
// XXX
BugAnnotation getVariableAnnotation(Location location) {
BugAnnotation variableAnnotation = null;
try {
// Get the value number
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(
method).getFactAtLocation(location);
if (vnaFrame.isValid()) {
Instruction ins = location.getHandle().getInstruction();
ValueNumber valueNumber = vnaFrame.getInstance(ins,
classContext.getConstantPoolGen());
if (valueNumber.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT))
return null;
variableAnnotation = NullDerefAndRedundantComparisonFinder.findAnnotationFromValueNumber(method,
location, valueNumber, vnaFrame);
}
} catch (DataflowAnalysisException e) {
// ignore
} catch (CFGBuilderException e) {
// ignore
}
return variableAnnotation;
}
/**
* Determine whether or not given instruction is a goto.
*
* @param instruction
* the instruction
* @return true if the instruction is a goto, false otherwise
*/
private boolean isGoto(Instruction instruction) {
return instruction.getOpcode() == Constants.GOTO
|| instruction.getOpcode() == Constants.GOTO_W;
}
/*
* (non-Javadoc)
*
* @see edu.umd.cs.findbugs.ba.npe.NullDerefAndRedundantComparisonCollector#foundGuaranteedNullDeref(java.util.Set,
* java.util.Set, edu.umd.cs.findbugs.ba.vna.ValueNumber, boolean)
*/
public void foundGuaranteedNullDeref(@NonNull
Set<Location> assignedNullLocationSet, @NonNull
Set<Location> derefLocationSet, SortedSet<Location> doomedLocations,
ValueNumberDataflow vna, ValueNumber refValue,
BugAnnotation variableAnnotation, boolean alwaysOnExceptionPath,
boolean npeIfStatementCovered) {
if (refValue.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT))
return;
if (DEBUG) {
System.out.println("Found guaranteed null deref in "
+ method.getName());
for (Location loc : doomedLocations)
System.out.println("Doomed at " + loc);
}
String bugType = "NP_GUARANTEED_DEREF";
if (alwaysOnExceptionPath)
bugType += "_ON_EXCEPTION_PATH";
int priority = alwaysOnExceptionPath ? NORMAL_PRIORITY : HIGH_PRIORITY;
if (!npeIfStatementCovered)
priority++;
// Add Locations in the set of locations at least one of which
// is guaranteed to be dereferenced
SortedSet<Location> sourceLocations;
if (doomedLocations.isEmpty() || doomedLocations.size() > 3
&& doomedLocations.size() > assignedNullLocationSet.size())
sourceLocations = new TreeSet<Location>(assignedNullLocationSet);
else
sourceLocations = doomedLocations;
if (doomedLocations.isEmpty() || derefLocationSet.isEmpty())
return;
boolean derefOutsideCatchBlock = false;
for (Location loc : derefLocationSet)
if (!inCatchNullBlock(loc)) {
derefOutsideCatchBlock = true;
break;
}
boolean uniqueDereferenceLocations = false;
LineNumberTable table = method.getLineNumberTable();
if (table == null)
uniqueDereferenceLocations = true;
else {
BitSet linesMentionedMultipleTimes = ClassContext.linesMentionedMultipleTimes(method);
for(Location loc : derefLocationSet) {
int lineNumber = table.getSourceLine(loc.getHandle().getPosition());
if (!linesMentionedMultipleTimes.get(lineNumber)) uniqueDereferenceLocations = true;
}
}
if (!derefOutsideCatchBlock) {
if (!uniqueDereferenceLocations || skipIfInsideCatchNull())
return;
priority++;
}
if (!uniqueDereferenceLocations)
priority++;
// Create BugInstance
BitSet knownNull = new BitSet();
SortedSet<SourceLineAnnotation> knownNullLocations = new TreeSet<SourceLineAnnotation>();
for (Location loc : sourceLocations) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation
.fromVisitedInstruction(classContext, classContext
.getMethodGen(method), classContext.getJavaClass()
.getSourceFileName(), loc.getHandle());
if (sourceLineAnnotation == null)
continue;
int startLine = sourceLineAnnotation.getStartLine();
if (startLine == -1)
knownNullLocations.add(sourceLineAnnotation);
else if (!knownNull.get(startLine)) {
knownNull.set(startLine);
knownNullLocations.add(sourceLineAnnotation);
}
}
FieldAnnotation storedField = null;
MethodAnnotation invokedMethod = null;
int parameterNumber = -1;
if (derefLocationSet.size() == 1) {
Location loc = derefLocationSet.iterator().next();
PointerUsageRequiringNonNullValue pu = null;
try {
UsagesRequiringNonNullValues usages = classContext.getUsagesRequiringNonNullValues(method);
pu = usages.get(loc, refValue);
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("Error getting UsagesRequiringNonNullValues for " + method, e);
} catch (CFGBuilderException e) {
AnalysisContext.logError("Error getting UsagesRequiringNonNullValues for " + method, e);
}
if (pu != null && pu.getReturnFromNonNullMethod()) {
bugType = "NP_NONNULL_RETURN_VIOLATION";
String methodName = method.getName();
String methodSig = method.getSignature();
if (methodName.equals("clone") && methodSig.equals("()Ljava/lang/Object;")) {
bugType = "NP_CLONE_COULD_RETURN_NULL";
priority = NORMAL_PRIORITY;
} else if (methodName.equals("toString") && methodSig.equals("()Ljava/lang/String;")) {
bugType = "NP_TOSTRING_COULD_RETURN_NULL";
priority = NORMAL_PRIORITY;
}
} else if (pu != null && pu.getNonNullField() != null) {
storedField = FieldAnnotation.fromXField( pu.getNonNullField() );
bugType = "NP_STORE_INTO_NONNULL_FIELD";
} else if (pu != null && pu.getNonNullParameter() != null) {
XMethodParameter mp = pu.getNonNullParameter() ;
invokedMethod = MethodAnnotation.fromXMethod(mp.getMethod());
parameterNumber = mp.getParameterNumber();
bugType = "NP_NULL_PARAM_DEREF";
} else if (!alwaysOnExceptionPath)
bugType = "NP_NULL_ON_SOME_PATH";
else
bugType = "NP_NULL_ON_SOME_PATH_EXCEPTION";
}
BugInstance bugInstance = new BugInstance(this, bugType, priority)
.addClassAndMethod(classContext.getJavaClass(), method);
if (invokedMethod != null)
bugInstance.addMethod(invokedMethod).describe("METHOD_CALLED").addInt(parameterNumber).describe(
"INT_NONNULL_PARAM");
if (storedField!= null)
bugInstance.addField(storedField);
bugInstance.add(variableAnnotation);
for (Location loc : derefLocationSet)
bugInstance.addSourceLine(classContext, method, loc).describe(getDescription(loc, refValue));
for (SourceLineAnnotation sourceLineAnnotation : knownNullLocations)
bugInstance.add(sourceLineAnnotation).describe(
"SOURCE_LINE_KNOWN_NULL");
// If all deref locations are doomed
// (i.e., locations where a normal return is not possible),
// add a warning property indicating such.
// Are all derefs at doomed locations?
boolean allDerefsAtDoomedLocations = true;
for (Location derefLoc : derefLocationSet) {
if (!isDoomed(derefLoc)) {
allDerefsAtDoomedLocations = false;
break;
}
}
if (allDerefsAtDoomedLocations) {
// Add a WarningProperty
WarningPropertySet propertySet = new WarningPropertySet();
propertySet.addProperty(DoomedCodeWarningProperty.DOOMED_CODE);
propertySet.decorateBugInstance(bugInstance);
}
// Report it
bugReporter.reportBug(bugInstance);
}
private boolean isDoomed(Location loc) {
if (!MARK_DOOMED) return false;
ReturnPathTypeDataflow rptDataflow;
try {
rptDataflow = classContext.getReturnPathTypeDataflow(method);
ReturnPathType rpt = rptDataflow.getFactAtLocation(loc);
return !rpt.canReturnNormally();
} catch (CFGBuilderException e) {
AnalysisContext.logError("Error getting return path type", e);
return false;
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("Error getting return path type", e);
return false;
}
}
String getDescription(Location loc, ValueNumber refValue) {
PointerUsageRequiringNonNullValue pu;
try {
UsagesRequiringNonNullValues usages = classContext.getUsagesRequiringNonNullValues(method);
pu = usages.get(loc, refValue);
if (pu == null) return "SOURCE_LINE_DEREF";
return pu.getDescription();
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("Error getting UsagesRequiringNonNullValues for " + method, e);
return "SOURCE_LINE_DEREF";
} catch (CFGBuilderException e) {
AnalysisContext.logError("Error getting UsagesRequiringNonNullValues for " + method, e);
return "SOURCE_LINE_DEREF";
}
}
boolean inCatchNullBlock(Location loc) {
int pc = loc.getHandle().getPosition();
int catchSize = Util.getSizeOfSurroundingTryBlock(classContext
.getConstantPoolGen().getConstantPool(), method.getCode(),
"java/lang/NullPointerException", pc);
if (catchSize < Integer.MAX_VALUE)
return true;
catchSize = Util.getSizeOfSurroundingTryBlock(classContext
.getConstantPoolGen().getConstantPool(), method.getCode(),
"java/lang/Exception", pc);
if (catchSize < 5)
return true;
catchSize = Util.getSizeOfSurroundingTryBlock(classContext
.getConstantPoolGen().getConstantPool(), method.getCode(),
"java/lang/RuntimeException", pc);
if (catchSize < 5)
return true;
catchSize = Util.getSizeOfSurroundingTryBlock(classContext
.getConstantPoolGen().getConstantPool(), method.getCode(),
"java/lang/Throwable", pc);
if (catchSize < 5)
return true;
return false;
}
}
// vim:ts=4 |
package edu.wustl.catissuecore.util.global;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants
{
//Constants used for authentication module.
public static final String LOGIN = "login";
public static final String USER = "user";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
//DAO Constants.
public static final int HIBERNATE_DAO = 1;
public static final int JDBC_DAO = 2;
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String ADD = "add";
public static final String EDIT = "edit";
public static final String VIEW = "view";
public static final String SEARCH = "search";
public static final String NEWUSERFORM = "newUserForm";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String YOUR_PASSWORD = "Your Password";
public static final String IDENTIFIER = "systemIdentifier";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String OPERATION = "operation";
public static final String ACTIVITY_STATUS = "activityStatus";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENOTYPIC_GENDER_LIST = "genotypicGenderList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String PARTICIPANTLIST = "participantList";
public static final String PARTICIPANTIDLIST = "participantIdList";
public static final String PROTOCOLLIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "SpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "SpecimenEdit.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String[] DEFAULT_TREE_SELECT_COLUMNS = {
Constants.QUERY_RESULTS_PARTICIPANT_ID,
Constants.QUERY_RESULTS_ACCESSION_ID,
Constants.QUERY_RESULTS_SPECIMEN_ID,
Constants.QUERY_RESULTS_SEGMENT_ID,
Constants.QUERY_RESULTS_SAMPLE_ID};
//Frame names in Query Results page.
public static final String DATA_VIEW_FRAME = "myframe1";
public static final String APPLET_VIEW_FRAME = "appletViewFrame";
//NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view).
public static final String DATA_VIEW_ACTION = "/catissuecore/DataView.do?nodeName=";
public static final String VIEW_TYPE = "viewType";
//Constants for type of query results view.
public static final String SPREADSHEET_VIEW = "Spreadsheet View";
public static final String OBJECT_VIEW = "Object View";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier=";
public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier=";
//Individual view Constants in DataViewAction.
public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList";
public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList";
public static final String SELECT_COLUMN_LIST = "selectColumnList";
//Tree Data Action
public static final String TREE_DATA_ACTION = "/catissuecore/Data.do";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {"PARTICIPANT_ID","ACCESSION_ID","SPECIMEN_ID",
"TISSUE_SITE","SPECIMEN_TYPE","SEGMENT_ID",
"SAMPLE_ID","SAMPLE_TYPE"};
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//Identifiers for various Form beans
public static final int USER_FORM_ID = 1;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTEDPROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTIONPROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
//Status message key Constants
public static final String STATUS_MESSAGE_KEY = "statusMessageKey";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_ACTIVE = "Active";
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
public static final String ACTIVITY_STATUS_CLOSED = "Closed";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Query Interface Tree View Constants.
public static final String ROOT = "Root";
//Query Interface Results View Constants
public static final String PAGEOF = "pageOf";
public static final String QUERY = "query";
//Query results view temporary table name.
public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_ACCESSION_ID = "ACCESSION_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SEGMENT_ID = "SEGMENT_ID";
public static final String QUERY_RESULTS_SAMPLE_ID = "SAMPLE_ID";
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "QueryTree.class";
public static final String APPLET_CODEBASE = "Applet";
public static final String [] RECEIVEDMODEARRAY = {
"by hand", "courier", "FedEX", "UPS"
};
public static final String [] GENOTYPIC_GENDER_ARRAY = {
"Male",
"Female"
};
public static final String [] RACEARRAY = {
"Asian",
"American"
};
public static final String [] PROTOCOLARRAY = {
"aaaa",
"bbbb",
"cccc"
};
public static final String [] RECEIVEDBYARRAY = {
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] COLLECTEDBYARRAY = {
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"};
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
public static final String [] STATEARRAY =
{
"Alabama",//Alabama
"Alaska",//Alaska
"Arizona",//Arizona
"Arkansas",//Arkansas
"California",//California
"Colorado",//Colorado
"Connecticut",//Connecticut
"Delaware",//Delaware
"D.C.",
"Florida",//Florida
"Georgia",//Georgia
"Hawaii",//Hawaii
"Idaho",//Idaho
"Illinois",//Illinois
"Indiana",//Indiana
"Iowa",//Iowa
"Kansas",//Kansas
"Kentucky",//Kentucky
"Louisiana",//Louisiana
"Maine",//Maine
"Maryland",//Maryland
"Massachusetts",//Massachusetts
"Michigan",//Michigan
"Minnesota",//Minnesota
"Mississippi",//Mississippi
"Missouri",//Missouri
"Montana",//Montana
"Nebraska",//Nebraska
"Nevada",//Nevada
"New Hampshire",//New Hampshire
"New Jersey",//New Jersey
"New Mexico",//New Mexico
"New York",//New York
"North Carolina",//North Carolina
"North Dakota",//North Dakota
"Ohio",//Ohio
"Oklahoma",//Oklahoma
"Oregon",//Oregon
"Pennsylvania",//Pennsylvania
"Rhode Island",//Rhode Island
"South Carolina",//South Carolina
"South Dakota",//South Dakota
"Tennessee",//Tennessee
"Texas",//Texas
"Utah",//Utah
"Vermont",//Vermont
"Virginia",//Virginia
"Washington",//Washington
"West Virginia",//West Virginia
"Wisconsin",//Wisconsin
"Wyoming",//Wyoming
"Other",//Other
};
public static final String [] COUNTRYARRAY =
{
"United States",
"Canada",
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Bouvet Island",
"Brazil",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",//Cameroon
"Cape Verde",//Cape Verde
"Cayman Islands",//Cayman Islands
"Central African Republic",//Central African Republic
"Chad",//Chad
"Chile",//Chile
"China",//China
"Christmas Island",//Christmas Island
"Cocos Islands",//Cocos Islands
"Colombia",//Colombia
"Comoros",//Comoros
"Congo",//Congo
"Cook Islands",//Cook Islands
"Costa Rica",//Costa Rica
"Cote D ivoire",//Cote D ivoire
"Croatia",//Croatia
"Cyprus",//Cyprus
"Czech Republic",//Czech Republic
"Denmark",//Denmark
"Djibouti",//Djibouti
"Dominica",//Dominica
"Dominican Republic",//Dominican Republic
"East Timor",//East Timor
"Ecuador",//Ecuador
"Egypt",//Egypt
"El Salvador",//El Salvador
"Equatorial Guinea",//Equatorial Guinea
"Eritrea",//Eritrea
"Estonia",//Estonia
"Ethiopia",//Ethiopia
"Falkland Islands",//Falkland Islands
"Faroe Islands",//Faroe Islands
"Fiji",//Fiji
"Finland",//Finland
"France",//France
"French Guiana",//French Guiana
"French Polynesia",//French Polynesia
"French S. Territories",//French S. Territories
"Gabon",//Gabon
"Gambia",//Gambia
"Georgia",//Georgia
"Germany",//Germany
"Ghana",//Ghana
"Gibraltar",//Gibraltar
"Greece",//Greece
"Greenland",//Greenland
"Grenada",//Grenada
"Guadeloupe",//Guadeloupe
"Guam",//Guam
"Guatemala",//Guatemala
"Guinea",//Guinea
"Guinea-Bissau",//Guinea-Bissau
"Guyana",//Guyana
"Haiti",//Haiti
"Honduras",//Honduras
"Hong Kong",//Hong Kong
"Hungary",//Hungary
"Iceland",//Iceland
"India",//India
"Indonesia",//Indonesia
"Iran",//Iran
"Iraq",//Iraq
"Ireland",//Ireland
"Israel",//Israel
"Italy",//Italy
"Jamaica",//Jamaica
"Japan",//Japan
"Jordan",//Jordan
"Kazakhstan",//Kazakhstan
"Kenya",//Kenya
"Kiribati",//Kiribati
"Korea",//Korea
"Kuwait",//Kuwait
"Kyrgyzstan",//Kyrgyzstan
"Laos",//Laos
"Latvia",//Latvia
"Lebanon",//Lebanon
"Lesotho",//Lesotho
"Liberia",//Liberia
"Liechtenstein",//Liechtenstein
"Lithuania",//Lithuania
"Luxembourg",//Luxembourg
"Macau",//Macau
"Macedonia",//Macedonia
"Madagascar",//Madagascar
"Malawi",//Malawi
"Malaysia",//Malaysia
"Maldives",//Maldives
"Mali",//Mali
"Malta",//Malta
"Marshall Islands",//Marshall Islands
"Martinique",//Martinique
"Mauritania",//Mauritania
"Mauritius",//Mauritius
"Mayotte",//Mayotte
"Mexico",//Mexico
"Micronesia",//Micronesia
"Moldova",//Moldova
"Monaco",//Monaco
"Mongolia",//Mongolia
"Montserrat",//Montserrat
"Morocco",//Morocco
"Mozambique",//Mozambique
"Myanmar",//Myanmar
"Namibia",//Namibia
"Nauru",//Nauru
"Nepal",//Nepal
"Netherlands",//Netherlands
"Netherlands Antilles",//Netherlands Antilles
"New Caledonia",//New Caledonia
"New Zealand",//New Zealand
"Nicaragua",//Nicaragua
"Niger",//Niger
"Nigeria",//Nigeria
"Niue",//Niue
"Norfolk Island",//Norfolk Island
"Norway",//Norway
"Oman",//Oman
"Pakistan",//Pakistan
"Palau",//Palau
"Panama",//Panama
"Papua New Guinea",//Papua New Guinea
"Paraguay",//Paraguay
"Peru",//Peru
"Philippines",//Philippines
"Pitcairn",//Pitcairn
"Poland",//Poland
"Portugal",//Portugal
"Puerto Rico",//Puerto Rico
"Qatar",//Qatar
"Reunion",//Reunion
"Romania",//Romania
"Russian Federation",//Russian Federation
"Rwanda",//Rwanda
"Saint Helena",//Saint Helena
"Saint Kitts and Nevis",//Saint Kitts and Nevis
"Saint Lucia",//Saint Lucia
"Saint Pierre",//Saint Pierre
"Saint Vincent",//Saint Vincent
"Samoa",//Samoa
"San Marino",//San Marino
"Sao Tome and Principe",//Sao Tome and Principe
"Saudi Arabia",//Saudi Arabia
"Senegal",//Senegal
"Seychelles",//Seychelles
"Sierra Leone",//Sierra Leone
"Singapore",//Singapore
"Slovakia",//Slovakia
"Slovenia",//Slovenia
"Solomon Islands",//Solomon Islands
"Somalia",//Somalia
"South Africa",//South Africa
"Spain",//Spain
"Sri Lanka",//Sri Lanka
"Sudan",//Sudan
"Suriname",//Suriname
"Swaziland",//Swaziland
"Sweden",//Sweden
"Switzerland",//Switzerland
"Syrian Arab Republic",//Syrian Arab Republic
"Taiwan",//Taiwan
"Tajikistan",//Tajikistan
"Tanzania",//Tanzania
"Thailand",//Thailand
"Togo",//Togo
"Tokelau",//Tokelau
"Tonga",//Tonga
"Trinidad and Tobago",//Trinidad and Tobago
"Tunisia",//Tunisia
"Turkey",//Turkey
"Turkmenistan",//Turkmenistan
"Turks and Caicos Islands",//Turks and Caicos Islands
"Tuvalu",//Tuvalu
"Uganda",//Uganda
"Ukraine",//Ukraine
"United Arab Emirates",//United Arab Emirates
"United Kingdom",//United Kingdom
"Uruguay",//Uruguay
"Uzbekistan",//Uzbekistan
"Vanuatu",//Vanuatu
"Vatican City State",//Vatican City State
"Venezuela",//Venezuela
"Vietnam",//Vietnam
"Virgin Islands",//Virgin Islands
"Wallis And Futuna Islands",//Wallis And Futuna Islands
"Western Sahara",//Western Sahara
"Yemen",//Yemen
"Yugoslavia",//Yugoslavia
"Zaire",//Zaire
"Zambia",//Zambia
"Zimbabwe",//Zimbabwe
};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] CANCER_RESEARCH_GROUP_VALUES = {
"Siteman Cancer Center",
"Washington University"
};
public static final String [] ACTIVITY_STATUS_VALUES = {
"Active",
"Disabled",
"Closed",
"New",
"Reject",
"Pending"
};
//Only for showing UI.
public static final String [] ROLE_VALUES = {
"Administrator",
"Clinician",
"Technician",
"Scientist",
"Public",
"Collector"
};
public static final String [] INSTITUTE_VALUES = {
"Washington University"
};
public static final String [] DEPARTMENT_VALUES = {
"Cardiology",
"Pathology"
};
public static final String [] SPECIMEN_TYPE_VALUES = {
"Tissue",
"Fluid",
"Cell",
"Molecular"
};
public static final String [] SPECIMEN_SUB_TYPE_VALUES = {
"Blood",
"Serum",
"Plasma",
};
public static final String [] TISSUE_SITE_VALUES = {
"Adrenal-Cortex",
"Adrenal-Medulla",
"Adrenal-NOS"
};
public static final String [] TISSUE_SIDE_VALUES = {
"Lavage",
"Metastatic Lesion",
};
public static final String [] PATHOLOGICAL_STATUS_VALUES = {
"Primary Tumor",
"Metastatic Node",
"Non-Maglignant Tissue",
};
public static final String [] BIOHAZARD_NAME_VALUES = {
""
};
public static final String [] BIOHAZARD_TYPE_VALUES = {
"Radioactive"
};
public static final String [] ETHNICITY_VALUES = {
"-- Select --"
};
public static final String [] PARTICIPANT_MEDICAL_RECORD_SOURCE_VALUES = {
"-- Select --"
};
public static final String [] PROTOCOL_TITLE_ARRAY = {
"Protocol-1"
};
public static final String [] PARTICIPANT_NAME_ARRAY = {
"LastName,FirstName"
};
public static final String [] PROTOCOL_PARTICIPANT_NUMBER_ARRAY = {
"1","2","3","4"
};
public static final String [] STUDY_CALENDAR_EVENT_POINT_ARRAY = {
"30","60","90"
};
public static final String [] CLINICAL_STATUS_ARRAY = {
"Pre-Opt",
"Post-Opt"
};
public static final String [] SITE_TYPE_ARRAY = {
"Collection",
"Laboratory",
"Repository"
};
} |
package io.cloudevents.v03;
import static java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME;
import java.net.URI;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.Optional;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.cloudevents.Attributes;
import io.cloudevents.fun.AttributeUnmarshaller;
import io.cloudevents.json.ZonedDateTimeDeserializer;
/**
* The event attributes implementation for v0.2
*
* @author fabiojose
*
*/
@JsonInclude(value = Include.NON_ABSENT)
public class AttributesImpl implements Attributes {
@NotBlank
private final String id;
@NotNull
private final URI source;
@NotBlank
@Pattern(regexp = "0\\.3")
private final String specversion;
@NotBlank
private final String type;
@JsonDeserialize(using = ZonedDateTimeDeserializer.class)
private final ZonedDateTime time;
private final URI schemaurl;
@Pattern(regexp = "base64")
private final String datacontentencoding;
private final String datacontenttype;
@Size(min = 1)
private final String subject;
AttributesImpl(String id, URI source, String specversion, String type,
ZonedDateTime time, URI schemaurl, String datacontentencoding,
String datacontenttype, String subject) {
this.id = id;
this.source = source;
this.specversion = specversion;
this.type = type;
this.time = time;
this.schemaurl = schemaurl;
this.datacontentencoding = datacontentencoding;
this.datacontenttype = datacontenttype;
this.subject = subject;
}
public String getId() {
return id;
}
public URI getSource() {
return source;
}
public String getSpecversion() {
return specversion;
}
public String getType() {
return type;
}
public Optional<ZonedDateTime> getTime() {
return Optional.ofNullable(time);
}
public Optional<URI> getSchemaurl() {
return Optional.ofNullable(schemaurl);
}
public Optional<String> getDatacontentencoding() {
return Optional.ofNullable(datacontentencoding);
}
public Optional<String> getDatacontenttype() {
return Optional.ofNullable(datacontenttype);
}
public Optional<String> getSubject() {
return Optional.ofNullable(subject);
}
@Override
public String toString() {
return "AttributesImpl [id=" + id + ", source=" + source
+ ", specversion=" + specversion + ", type=" + type
+ ", time=" + time + ", schemaurl=" + schemaurl
+ ", datacontentencoding=" + datacontentencoding
+ ", datacontenttype=" + datacontenttype + ", subject="
+ subject + "]";
}
/**
* Used by the Jackson framework to unmarshall.
*/
@JsonCreator
public static AttributesImpl build(
@JsonProperty("id") String id,
@JsonProperty("source") URI source,
@JsonProperty("specversion") String specversion,
@JsonProperty("type") String type,
@JsonProperty("time") ZonedDateTime time,
@JsonProperty("schemaurl") URI schemaurl,
@JsonProperty("datacontentenconding") String datacontentencoding,
@JsonProperty("datacontenttype") String datacontenttype,
@JsonProperty("subject") String subject) {
return new AttributesImpl(id, source, specversion, type, time,
schemaurl, datacontentencoding, datacontenttype, subject);
}
/**
* The attribute unmarshaller for the binary format, that receives a
* {@code Map} with attributes names as String and value as String.
*/
public static AttributeUnmarshaller<AttributesImpl> unmarshaller() {
return new AttributeUnmarshaller<AttributesImpl>() {
@Override
public AttributesImpl unmarshall(Map<String, String> attributes) {
String type = attributes.get("type");
ZonedDateTime time =
Optional.ofNullable(attributes.get("time"))
.map((t) -> ZonedDateTime.parse(t,
ISO_ZONED_DATE_TIME))
.orElse(null);
String specversion = attributes.get("specversion");
URI source = URI.create(attributes.get("source"));
URI schemaurl =
Optional.ofNullable(attributes.get("schemaurl"))
.map(schema -> URI.create(schema))
.orElse(null);
String id = attributes.get("id");
String datacontenttype =
attributes.get("datacontenttype");
String datacontentencoding =
attributes.get("datacontentencoding");
String subject = attributes.get("subject");
return AttributesImpl.build(id, source, specversion, type,
time, schemaurl, datacontentencoding,
datacontenttype, subject);
}
};
}
} |
package org.jfree.chart.axis.junit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.axis.CategoryAxis3D;
/**
* Tests for the {@link CategoryAxis3D} class.
*/
public class CategoryAxis3DTests extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(CategoryAxis3DTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public CategoryAxis3DTests(String name) {
super(name);
}
/**
* Confirm that cloning works.
*/
public void testCloning() {
CategoryAxis3D a1 = new CategoryAxis3D("Test");
CategoryAxis3D a2 = null;
try {
a2 = (CategoryAxis3D) a1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(a1 != a2);
assertTrue(a1.getClass() == a2.getClass());
assertTrue(a1.equals(a2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
CategoryAxis3D a1 = new CategoryAxis3D("Test Axis");
CategoryAxis3D a2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(a1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
a2 = (CategoryAxis3D) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(a1, a2);
}
} |
package org.jboss.as.cli;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.UnknownHostException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.Security;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.RealmCallback;
import javax.security.sasl.RealmChoiceCallback;
import org.jboss.as.cli.batch.Batch;
import org.jboss.as.cli.batch.BatchManager;
import org.jboss.as.cli.batch.BatchedCommand;
import org.jboss.as.cli.batch.impl.DefaultBatchManager;
import org.jboss.as.cli.batch.impl.DefaultBatchedCommand;
import org.jboss.as.cli.handlers.ClearScreenHandler;
import org.jboss.as.cli.handlers.CommandCommandHandler;
import org.jboss.as.cli.handlers.ConnectHandler;
import org.jboss.as.cli.handlers.DeployHandler;
import org.jboss.as.cli.handlers.GenericTypeOperationHandler;
import org.jboss.as.cli.handlers.HelpHandler;
import org.jboss.as.cli.handlers.HistoryHandler;
import org.jboss.as.cli.handlers.LsHandler;
import org.jboss.as.cli.handlers.OperationRequestHandler;
import org.jboss.as.cli.handlers.PrefixHandler;
import org.jboss.as.cli.handlers.PrintWorkingNodeHandler;
import org.jboss.as.cli.handlers.QuitHandler;
import org.jboss.as.cli.handlers.UndeployHandler;
import org.jboss.as.cli.handlers.VersionHandler;
import org.jboss.as.cli.handlers.batch.BatchClearHandler;
import org.jboss.as.cli.handlers.batch.BatchDiscardHandler;
import org.jboss.as.cli.handlers.batch.BatchEditLineHandler;
import org.jboss.as.cli.handlers.batch.BatchHandler;
import org.jboss.as.cli.handlers.batch.BatchHoldbackHandler;
import org.jboss.as.cli.handlers.batch.BatchListHandler;
import org.jboss.as.cli.handlers.batch.BatchMoveLineHandler;
import org.jboss.as.cli.handlers.batch.BatchRemoveLineHandler;
import org.jboss.as.cli.handlers.batch.BatchRunHandler;
import org.jboss.as.cli.handlers.jca.DataSourceAddHandler;
import org.jboss.as.cli.handlers.jca.DataSourceModifyHandler;
import org.jboss.as.cli.handlers.jca.DataSourceRemoveHandler;
import org.jboss.as.cli.handlers.jca.XADataSourceAddHandler;
import org.jboss.as.cli.handlers.jca.XADataSourceModifyHandler;
import org.jboss.as.cli.handlers.jca.XADataSourceRemoveHandler;
import org.jboss.as.cli.handlers.jms.CreateJmsResourceHandler;
import org.jboss.as.cli.handlers.jms.DeleteJmsResourceHandler;
import org.jboss.as.cli.handlers.jms.JmsCFAddHandler;
import org.jboss.as.cli.handlers.jms.JmsCFRemoveHandler;
import org.jboss.as.cli.handlers.jms.JmsQueueAddHandler;
import org.jboss.as.cli.handlers.jms.JmsQueueRemoveHandler;
import org.jboss.as.cli.handlers.jms.JmsTopicAddHandler;
import org.jboss.as.cli.handlers.jms.JmsTopicRemoveHandler;
import org.jboss.as.cli.operation.OperationCandidatesProvider;
import org.jboss.as.cli.operation.OperationFormatException;
import org.jboss.as.cli.operation.OperationRequestAddress;
import org.jboss.as.cli.operation.CommandLineParser;
import org.jboss.as.cli.operation.ParsedCommandLine;
import org.jboss.as.cli.operation.PrefixFormatter;
import org.jboss.as.cli.operation.impl.DefaultCallbackHandler;
import org.jboss.as.cli.operation.impl.DefaultOperationCandidatesProvider;
import org.jboss.as.cli.operation.impl.DefaultOperationRequestAddress;
import org.jboss.as.cli.operation.impl.DefaultOperationRequestParser;
import org.jboss.as.cli.operation.impl.DefaultPrefixFormatter;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.protocol.StreamUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.sasl.JBossSaslProvider;
/**
*
* @author Alexey Loubyansky
*/
public class CommandLineMain {
private static final CommandRegistry cmdRegistry = new CommandRegistry();
static {
cmdRegistry.registerHandler(new HelpHandler(), "help", "h");
cmdRegistry.registerHandler(new QuitHandler(), "quit", "q", "exit");
cmdRegistry.registerHandler(new ConnectHandler(), "connect");
cmdRegistry.registerHandler(new PrefixHandler(), "cd", "cn");
cmdRegistry.registerHandler(new ClearScreenHandler(), "clear", "cls");
cmdRegistry.registerHandler(new LsHandler(), "ls");
cmdRegistry.registerHandler(new HistoryHandler(), "history");
cmdRegistry.registerHandler(new DeployHandler(), "deploy");
cmdRegistry.registerHandler(new UndeployHandler(), "undeploy");
cmdRegistry.registerHandler(new PrintWorkingNodeHandler(), "pwd", "pwn");
cmdRegistry.registerHandler(new JmsQueueAddHandler(), "add-jms-queue");
cmdRegistry.registerHandler(new JmsQueueRemoveHandler(), "remove-jms-queue");
cmdRegistry.registerHandler(new JmsTopicAddHandler(), "add-jms-topic");
cmdRegistry.registerHandler(new JmsTopicRemoveHandler(), "remove-jms-topic");
cmdRegistry.registerHandler(new JmsCFAddHandler(), "add-jms-cf");
cmdRegistry.registerHandler(new JmsCFRemoveHandler(), "remove-jms-cf");
cmdRegistry.registerHandler(new CreateJmsResourceHandler(), false, "create-jms-resource");
cmdRegistry.registerHandler(new DeleteJmsResourceHandler(), false, "delete-jms-resource");
cmdRegistry.registerHandler(new BatchHandler(), "batch");
cmdRegistry.registerHandler(new BatchDiscardHandler(), "discard-batch");
cmdRegistry.registerHandler(new BatchListHandler(), "list-batch");
cmdRegistry.registerHandler(new BatchHoldbackHandler(), "holdback-batch");
cmdRegistry.registerHandler(new BatchRunHandler(), "run-batch");
cmdRegistry.registerHandler(new BatchClearHandler(), "clear-batch");
cmdRegistry.registerHandler(new BatchRemoveLineHandler(), "remove-batch-line");
cmdRegistry.registerHandler(new BatchMoveLineHandler(), "move-batch-line");
cmdRegistry.registerHandler(new BatchEditLineHandler(), "edit-batch-line");
cmdRegistry.registerHandler(new VersionHandler(), "version");
cmdRegistry.registerHandler(new DataSourceAddHandler(), false, "add-data-source");
cmdRegistry.registerHandler(new DataSourceModifyHandler(), false, "modify-data-source");
cmdRegistry.registerHandler(new DataSourceRemoveHandler(), false, "remove-data-source");
cmdRegistry.registerHandler(new XADataSourceAddHandler(), false, "add-xa-data-source");
cmdRegistry.registerHandler(new XADataSourceRemoveHandler(), false, "remove-xa-data-source");
cmdRegistry.registerHandler(new XADataSourceModifyHandler(), false, "modify-xa-data-source");
cmdRegistry.registerHandler(new CommandCommandHandler(cmdRegistry), "command");
// data-source
cmdRegistry.registerHandler(new GenericTypeOperationHandler("/subsystem=datasources/data-source", "jndi-name"), "data-source");
cmdRegistry.registerHandler(new GenericTypeOperationHandler("/subsystem=datasources/xa-data-source", "jndi-name"), "xa-data-source");
}
public static void main(String[] args) throws Exception {
try {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return Security.insertProviderAt(new JBossSaslProvider(), 1);
}
});
String argError = null;
String[] commands = null;
File file = null;
boolean connect = false;
String defaultControllerHost = null;
int defaultControllerPort = -1;
boolean version = false;
String username = null;
char[] password = null;
for(String arg : args) {
if(arg.startsWith("--controller=") || arg.startsWith("controller=")) {
final String value;
if(arg.startsWith("
value = arg.substring(13);
} else {
value = arg.substring(11);
}
String portStr = null;
int colonIndex = value.indexOf(':');
if(colonIndex < 0) {
// default port
defaultControllerHost = value;
} else if(colonIndex == 0) {
// default host
portStr = value.substring(1);
} else {
defaultControllerHost = value.substring(0, colonIndex);
portStr = value.substring(colonIndex + 1);
}
if(portStr != null) {
int port = -1;
try {
port = Integer.parseInt(portStr);
if(port < 0) {
argError = "The port must be a valid non-negative integer: '" + args + "'";
} else {
defaultControllerPort = port;
}
} catch(NumberFormatException e) {
argError = "The port must be a valid non-negative integer: '" + arg + "'";
}
}
} else if("--connect".equals(arg) || "-c".equals(arg)) {
connect = true;
} else if("--version".equals(arg)) {
version = true;
} else if(arg.startsWith("--file=") || arg.startsWith("file=")) {
if(file != null) {
argError = "Duplicate argument '--file'.";
break;
}
if(commands != null) {
argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
break;
}
final String fileName = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
if(!fileName.isEmpty()) {
file = new File(fileName);
if(!file.exists()) {
argError = "File " + file.getAbsolutePath() + " doesn't exist.";
break;
}
} else {
argError = "Argument '--file' is missing value.";
break;
}
} else if(arg.startsWith("--commands=") || arg.startsWith("commands=")) {
if(file != null) {
argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
break;
}
if(commands != null) {
argError = "Duplicate argument '--command'/'--commands'.";
break;
}
final String value = arg.startsWith("--") ? arg.substring(11) : arg.substring(9);
commands = value.split(",+");
} else if(arg.startsWith("--command=") || arg.startsWith("command=")) {
if(file != null) {
argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
break;
}
if(commands != null) {
argError = "Duplicate argument '--command'/'--commands'.";
break;
}
final String value = arg.startsWith("--") ? arg.substring(10) : arg.substring(8);
commands = new String[]{value};
} else if (arg.startsWith("--user=") || arg.startsWith("user=")) {
username = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
} else if (arg.startsWith("--password=") || arg.startsWith("password=")) {
password = (arg.startsWith("--") ? arg.substring(11) : arg.substring(9)).toCharArray();
} else if (arg.equals("--help") || arg.equals("-h")) {
commands = new String[]{"help"};
} else {
// assume it's commands
if(file != null) {
argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
break;
}
if(commands != null) {
argError = "Duplicate argument '--command'/'--commands'.";
break;
}
commands = arg.split(",+");
}
}
if(argError != null) {
System.err.println(argError);
return;
}
if(version) {
final CommandContextImpl cmdCtx = new CommandContextImpl();
VersionHandler.INSTANCE.handle(cmdCtx);
return;
}
if(file != null) {
processFile(file, defaultControllerHost, defaultControllerPort, connect, username, password);
return;
}
if(commands != null) {
processCommands(commands, defaultControllerHost, defaultControllerPort, connect, username, password);
return;
}
// Interactive mode
final jline.ConsoleReader console = initConsoleReader();
final CommandContextImpl cmdCtx = new CommandContextImpl(console);
SecurityActions.addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
cmdCtx.disconnectController();
}
}));
console.addCompletor(cmdCtx.cmdCompleter);
cmdCtx.username = username;
cmdCtx.password = password;
if(defaultControllerHost != null) {
cmdCtx.defaultControllerHost = defaultControllerHost;
}
if(defaultControllerPort != -1) {
cmdCtx.defaultControllerPort = defaultControllerPort;
}
if(connect) {
cmdCtx.connectController(null, -1);
} else {
cmdCtx.printLine("You are disconnected at the moment." +
" Type 'connect' to connect to the server or" +
" 'help' for the list of supported commands.");
}
try {
while (!cmdCtx.terminate) {
final String line = console.readLine(cmdCtx.getPrompt());
if(line == null) {
cmdCtx.terminateSession();
} else {
processLine(cmdCtx, line.trim());
}
}
} catch(Throwable t) {
t.printStackTrace();
} finally {
cmdCtx.disconnectController();
}
} finally {
System.exit(0);
}
System.exit(0);
}
private static void processCommands(String[] commands, String defaultControllerHost, int defaultControllerPort, final boolean connect, final String username, final char[] password) {
final CommandContextImpl cmdCtx = new CommandContextImpl();
SecurityActions.addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
cmdCtx.disconnectController(!connect);
}
}));
cmdCtx.username = username;
cmdCtx.password = password;
if (defaultControllerHost != null) {
cmdCtx.defaultControllerHost = defaultControllerHost;
}
if(defaultControllerPort != -1) {
cmdCtx.defaultControllerPort = defaultControllerPort;
}
if(connect) {
cmdCtx.connectController(null, -1, false);
}
try {
for (int i = 0; i < commands.length && !cmdCtx.terminate; ++i) {
processLine(cmdCtx, commands[i]);
}
} catch(Throwable t) {
t.printStackTrace();
} finally {
if (!cmdCtx.terminate) {
cmdCtx.terminateSession();
}
cmdCtx.disconnectController(!connect);
}
}
private static void processFile(File file, String defaultControllerHost, int defaultControllerPort, final boolean connect, final String username, final char[] password) {
final CommandContextImpl cmdCtx = new CommandContextImpl();
SecurityActions.addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
cmdCtx.disconnectController(!connect);
}
}));
cmdCtx.username = username;
cmdCtx.password = password;
if (defaultControllerHost != null) {
cmdCtx.defaultControllerHost = defaultControllerHost;
}
if(defaultControllerPort != -1) {
cmdCtx.defaultControllerPort = defaultControllerPort;
}
if(connect) {
cmdCtx.connectController(null, -1, false);
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while (!cmdCtx.terminate && line != null) {
processLine(cmdCtx, line.trim());
line = reader.readLine();
}
} catch (Throwable e) {
cmdCtx.printLine("Failed to process file '" + file.getAbsolutePath() + "'");
e.printStackTrace();
} finally {
StreamUtils.safeClose(reader);
if (!cmdCtx.terminate) {
cmdCtx.terminateSession();
}
cmdCtx.disconnectController(!connect);
}
}
protected static void processLine(final CommandContextImpl cmdCtx, String line) {
if (line.isEmpty()) {
return;
}
if (line.charAt(0) == '
return; // ignore comments
}
if(isOperation(line)) {
ModelNode request;
try {
cmdCtx.resetArgs(line);
request = cmdCtx.parsedCmd.toOperationRequest();
} catch (CommandFormatException e) {
cmdCtx.printLine(e.getLocalizedMessage());
return;
}
if(cmdCtx.isBatchMode()) {
StringBuilder op = new StringBuilder();
op.append(cmdCtx.getPrefixFormatter().format(cmdCtx.parsedCmd.getAddress()));
op.append(line.substring(line.indexOf(':')));
DefaultBatchedCommand batchedCmd = new DefaultBatchedCommand(op.toString(), request);
Batch batch = cmdCtx.getBatchManager().getActiveBatch();
batch.add(batchedCmd);
cmdCtx.printLine("#" + batch.size() + " " + batchedCmd.getCommand());
} else {
cmdCtx.set("OP_REQ", request);
try {
cmdCtx.operationHandler.handle(cmdCtx);
} finally {
cmdCtx.set("OP_REQ", null);
}
}
} else {
try {
cmdCtx.resetArgs(line);
} catch (CommandFormatException e1) {
cmdCtx.printLine(e1.getLocalizedMessage());
return;
}
final String cmdName = cmdCtx.parsedCmd.getOperationName();
CommandHandler handler = cmdRegistry.getCommandHandler(cmdName.toLowerCase());
if(handler != null) {
if(cmdCtx.isBatchMode() && handler.isBatchMode()) {
if(!(handler instanceof OperationCommand)) {
cmdCtx.printLine("The command is not allowed in a batch.");
} else {
try {
ModelNode request = ((OperationCommand)handler).buildRequest(cmdCtx);
BatchedCommand batchedCmd = new DefaultBatchedCommand(line, request);
Batch batch = cmdCtx.getBatchManager().getActiveBatch();
batch.add(batchedCmd);
cmdCtx.printLine("#" + batch.size() + " " + batchedCmd.getCommand());
} catch (CommandFormatException e) {
cmdCtx.printLine("Failed to add to batch: " + e.getLocalizedMessage());
}
}
} else {
try {
handler.handle(cmdCtx);
} catch (CommandFormatException e) {
cmdCtx.printLine(e.getLocalizedMessage());
}
}
// TODO this doesn't make sense
try {
cmdCtx.resetArgs(null);
} catch (CommandFormatException e) {
}
} else {
cmdCtx.printLine("Unexpected command '" + line
+ "'. Type 'help' for the list of supported commands.");
}
}
}
protected static jline.ConsoleReader initConsoleReader() {
final String bindingsName;
final String osName = SecurityActions.getSystemProperty("os.name").toLowerCase();
if(osName.indexOf("windows") >= 0) {
bindingsName = "keybindings/jline-windows-bindings.properties";
} else if(osName.startsWith("mac")) {
bindingsName = "keybindings/jline-mac-bindings.properties";
} else {
bindingsName = "keybindings/jline-default-bindings.properties";
}
ClassLoader cl = SecurityActions.getClassLoader(CommandLineMain.class);
InputStream bindingsIs = cl.getResourceAsStream(bindingsName);
if(bindingsIs == null) {
System.err.println("Failed to locate key bindings for OS '" + osName +"': " + bindingsName);
try {
return new jline.ConsoleReader();
} catch (IOException e) {
throw new IllegalStateException("Failed to initialize console reader", e);
}
} else {
try {
final InputStream in = new FileInputStream(FileDescriptor.in);
String encoding = SecurityActions.getSystemProperty("jline.WindowsTerminal.output.encoding");
if(encoding == null) {
encoding = SecurityActions.getSystemProperty("file.encoding");
}
final Writer out = new PrintWriter(new OutputStreamWriter(System.out, encoding));
return new jline.ConsoleReader(in, out, bindingsIs);
} catch(Exception e) {
throw new IllegalStateException("Failed to initialize console reader", e);
} finally {
StreamUtils.safeClose(bindingsIs);
}
}
}
private static boolean isOperation(String line) {
char firstChar = line.charAt(0);
return firstChar == '.' || firstChar == ':' || firstChar == '/' || line.startsWith("..") || line.startsWith(".type");
}
static class CommandContextImpl implements CommandContext {
private jline.ConsoleReader console;
private final CommandHistory history;
/** whether the session should be terminated*/
private boolean terminate;
/** current command line */
private String cmdLine;
/** parsed command arguments */
private DefaultCallbackHandler parsedCmd = new DefaultCallbackHandler();
/** domain or standalone mode*/
private boolean domainMode;
/** the controller client */
private ModelControllerClient client;
/** the default controller host */
private String defaultControllerHost = "localhost";
/** the default controller port */
private int defaultControllerPort = 9999;
/** the host of the controller */
private String controllerHost;
/** the port of the controller */
private int controllerPort = -1;
/** the command line specified username */
private String username;
/** the command line specified password */
private char[] password;
/** various key/value pairs */
private Map<String, Object> map = new HashMap<String, Object>();
/** operation request address prefix */
private final OperationRequestAddress prefix = new DefaultOperationRequestAddress();
/** the prefix formatter */
private final PrefixFormatter prefixFormatter = new DefaultPrefixFormatter();
/** provider of operation request candidates for tab-completion */
private final OperationCandidatesProvider operationCandidatesProvider;
/** operation request handler */
private final OperationRequestHandler operationHandler;
/** batches */
private BatchManager batchManager = new DefaultBatchManager();
/** the default command completer */
private final CommandCompleter cmdCompleter;
/** output target */
private BufferedWriter outputTarget;
/**
* Non-interactive mode
*/
private CommandContextImpl() {
this.console = null;
this.history = null;
this.operationCandidatesProvider = null;
this.cmdCompleter = null;
operationHandler = new OperationRequestHandler();
}
/**
* Interactive mode
*/
private CommandContextImpl(jline.ConsoleReader console) {
this.console = console;
console.setUseHistory(true);
String userHome = SecurityActions.getSystemProperty("user.home");
File historyFile = new File(userHome, ".jboss-cli-history");
try {
console.getHistory().setHistoryFile(historyFile);
} catch (IOException e) {
System.err.println("Failed to setup the history file " + historyFile.getAbsolutePath() + ": " + e.getLocalizedMessage());
}
this.history = new HistoryImpl();
operationCandidatesProvider = new DefaultOperationCandidatesProvider();
operationHandler = new OperationRequestHandler();
cmdCompleter = new CommandCompleter(cmdRegistry, this);
}
@Override
public String getArgumentsString() {
if(cmdLine != null && parsedCmd.getOperationName() != null) {
int cmdNameLength = parsedCmd.getOperationName().length();
if(cmdLine.length() == cmdNameLength) {
return null;
} else {
return cmdLine.substring(cmdNameLength + 1);
}
}
return null;
}
@Override
public void terminateSession() {
terminate = true;
}
@Override
public void printLine(String message) {
if(outputTarget != null) {
try {
outputTarget.append(message);
outputTarget.newLine();
outputTarget.flush();
} catch (IOException e) {
System.err.println("Failed to print '" + message + "' to the output target: " + e.getLocalizedMessage());
}
return;
}
if (console != null) {
try {
console.printString(message);
console.printNewline();
} catch (IOException e) {
System.err.println("Failed to print '" + message + "' to the console: " + e.getLocalizedMessage());
}
} else { // non-interactive mode
System.out.println(message);
}
}
private String readLine(String prompt, boolean password, boolean disableHistory) throws IOException {
if (console == null) {
console = initConsoleReader();
}
boolean useHistory = console.getUseHistory();
if (useHistory && disableHistory) {
console.setUseHistory(false);
}
try {
if (password) {
return console.readLine(prompt, '*');
} else {
return console.readLine(prompt);
}
} finally {
if (disableHistory && useHistory) {
console.setUseHistory(true);
}
}
}
@Override
public void printColumns(Collection<String> col) {
if(outputTarget != null) {
try {
for(String item : col) {
outputTarget.append(item);
outputTarget.newLine();
}
} catch (IOException e) {
System.err.println("Failed to print columns '" + col + "' to the console: " + e.getLocalizedMessage());
}
return;
}
if (console != null) {
try {
console.printColumns(col);
} catch (IOException e) {
System.err.println("Failed to print columns '" + col + "' to the console: " + e.getLocalizedMessage());
}
} else { // non interactive mode
for(String item : col) {
System.out.println(item);
}
}
}
@Override
public void set(String key, Object value) {
map.put(key, value);
}
@Override
public Object get(String key) {
return map.get(key);
}
@Override
public ModelControllerClient getModelControllerClient() {
return client;
}
@Override
public CommandLineParser getCommandLineParser() {
return DefaultOperationRequestParser.INSTANCE;
}
@Override
public OperationRequestAddress getPrefix() {
return prefix;
}
@Override
public PrefixFormatter getPrefixFormatter() {
return prefixFormatter;
}
@Override
public OperationCandidatesProvider getOperationCandidatesProvider() {
return operationCandidatesProvider;
}
private void connectController(String host, int port, boolean loggingEnabled) {
if(host == null) {
host = defaultControllerHost;
}
if(port < 0) {
port = defaultControllerPort;
}
try {
CallbackHandler cbh = new AuthenticationCallbackHandler();
ModelControllerClient newClient = ModelControllerClient.Factory.create(host, port, cbh);
if(this.client != null) {
disconnectController();
}
client = newClient;
this.controllerHost = host;
this.controllerPort = port;
List<String> nodeTypes = Util.getNodeTypes(newClient, new DefaultOperationRequestAddress());
if (!nodeTypes.isEmpty()) {
domainMode = nodeTypes.contains("server-group");
printLine("Connected to "
+ (domainMode ? "domain controller at " : "standalone controller at ")
+ host + ":" + port);
} else {
printLine("The controller is not available at " + host + ":" + port);
disconnectController(false);
}
} catch (UnknownHostException e) {
printLine("Failed to resolve host '" + host + "': " + e.getLocalizedMessage());
}
}
@Override
public void connectController(String host, int port) {
connectController(host, port, true);
}
private void disconnectController(boolean loggingEnabled) {
if(this.client != null) {
StreamUtils.safeClose(client);
if(loggingEnabled) {
printLine("Closed connection to " + this.controllerHost + ':' + this.controllerPort);
}
client = null;
this.controllerHost = null;
this.controllerPort = -1;
domainMode = false;
}
promptConnectPart = null;
}
@Override
public void disconnectController() {
disconnectController(true);
}
@Override
public String getControllerHost() {
return controllerHost;
}
@Override
public int getControllerPort() {
return controllerPort;
}
@Override
public void clearScreen() {
try {
console.setDefaultPrompt("");// it has to be reset apparently because otherwise it'll be printed twice
console.clearScreen();
} catch (IOException e) {
printLine(e.getLocalizedMessage());
}
}
String promptConnectPart;
String getPrompt() {
StringBuilder buffer = new StringBuilder();
if(promptConnectPart == null) {
buffer.append('[');
if (controllerHost != null) {
if (domainMode) {
buffer.append("domain@");
} else {
buffer.append("standalone@");
}
buffer.append(controllerHost).append(':').append(controllerPort).append(' ');
promptConnectPart = buffer.toString();
} else {
buffer.append("disconnected ");
}
} else {
buffer.append(promptConnectPart);
}
if (prefix.isEmpty()) {
buffer.append('/');
} else {
buffer.append(prefix.getNodeType());
final String nodeName = prefix.getNodeName();
if (nodeName != null) {
buffer.append('=').append(nodeName);
}
}
if (isBatchMode()) {
buffer.append("
}
buffer.append("] ");
return buffer.toString();
}
@Override
public CommandHistory getHistory() {
return history;
}
@Override
public String getDefaultControllerHost() {
return defaultControllerHost;
}
@Override
public int getDefaultControllerPort() {
return defaultControllerPort;
}
private void resetArgs(String cmdLine) throws CommandFormatException {
if(cmdLine != null) {
parsedCmd.parse(prefix, cmdLine);
setOutputTarget(parsedCmd.getOutputTarget());
}
this.cmdLine = cmdLine;
}
@Override
public boolean isBatchMode() {
return batchManager.isBatchActive();
}
@Override
public BatchManager getBatchManager() {
return batchManager;
}
private final DefaultCallbackHandler tmpBatched = new DefaultCallbackHandler();
@Override
public BatchedCommand toBatchedCommand(String line) throws CommandFormatException {
if (line.isEmpty()) {
throw new IllegalArgumentException("Null command line.");
}
final DefaultCallbackHandler originalParsedArguments = this.parsedCmd;
try {
this.parsedCmd = tmpBatched;
resetArgs(line);
} catch(CommandFormatException e) {
this.parsedCmd = originalParsedArguments;
throw e;
}
if(isOperation(line)) {
try {
ModelNode request = this.parsedCmd.toOperationRequest();
StringBuilder op = new StringBuilder();
op.append(prefixFormatter.format(parsedCmd.getAddress()));
op.append(line.substring(line.indexOf(':')));
return new DefaultBatchedCommand(op.toString(), request);
} finally {
this.parsedCmd = originalParsedArguments;
}
}
CommandHandler handler = cmdRegistry.getCommandHandler(parsedCmd.getOperationName());
if(handler == null) {
throw new OperationFormatException("No command handler for '" + parsedCmd.getOperationName() + "'.");
}
if(!(handler instanceof OperationCommand)) {
throw new OperationFormatException("The command is not allowed in a batch.");
}
try {
ModelNode request = ((OperationCommand)handler).buildRequest(this);
return new DefaultBatchedCommand(line, request);
} finally {
this.parsedCmd = originalParsedArguments;
}
}
@Override
public CommandLineCompleter getDefaultCommandCompleter() {
return cmdCompleter;
}
@Override
public ParsedCommandLine getParsedCommandLine() {
return parsedCmd;
}
@Override
public boolean isDomainMode() {
return domainMode;
}
protected void setOutputTarget(String filePath) {
if(filePath == null) {
this.outputTarget = null;
return;
}
FileWriter writer;
try {
writer = new FileWriter(filePath, false);
} catch (IOException e) {
printLine(e.getLocalizedMessage());
return;
}
this.outputTarget = new BufferedWriter(writer);
}
private class AuthenticationCallbackHandler implements CallbackHandler {
// After the CLI has connected the physical connection may be re-established numerous times.
// for this reason we cache the entered values to allow for re-use without pestering the end
// user.
private String realm = null;
private boolean realmShown = false;
private String username;
private char[] password;
private AuthenticationCallbackHandler() {
// A local cache is used for scenarios where no values are specified on the command line
// and the user wishes to use the connect command to establish a new connection.
username = CommandContextImpl.this.username;
password = CommandContextImpl.this.password;
}
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
// Special case for anonymous authentication to avoid prompting user for their name.
if (callbacks.length == 1 && callbacks[0] instanceof NameCallback) {
((NameCallback) callbacks[0]).setName("anonymous CLI user");
return;
}
for (Callback current : callbacks) {
if (current instanceof RealmCallback) {
RealmCallback rcb = (RealmCallback) current;
String defaultText = rcb.getDefaultText();
realm = defaultText;
rcb.setText(defaultText); // For now just use the realm suggested.
} else if (current instanceof RealmChoiceCallback) {
throw new UnsupportedCallbackException(current, "Realm choice not currently supported.");
} else if (current instanceof NameCallback) {
NameCallback ncb = (NameCallback) current;
if (username == null) {
showRealm();
username = readLine("Username:", false, true);
}
ncb.setName(username);
} else if (current instanceof PasswordCallback) {
PasswordCallback pcb = (PasswordCallback) current;
if (password == null) {
showRealm();
String temp = readLine("Password:", true, false);
if (temp != null) {
password = temp.toCharArray();
}
}
pcb.setPassword(password);
} else {
printLine("Unexpected Callback " + current.getClass().getName());
throw new UnsupportedCallbackException(current);
}
}
}
private void showRealm() {
if (realmShown == false && realm != null) {
realmShown = true;
printLine("Authenticating against security realm: " + realm);
}
}
}
private class HistoryImpl implements CommandHistory {
@SuppressWarnings("unchecked")
@Override
public List<String> asList() {
return console.getHistory().getHistoryList();
}
@Override
public boolean isUseHistory() {
return console.getUseHistory();
}
@Override
public void setUseHistory(boolean useHistory) {
console.setUseHistory(useHistory);
}
@Override
public void clear() {
console.getHistory().clear();
}
}
}
} |
//package org.genericsystem.remote;
//import javafx.collections.ListChangeListener;
//import javafx.collections.ListChangeListener.Change;
//import javafx.collections.ObservableList;
//import javafx.collections.ObservableListBase;
//public class TestClass<T> extends ObservableListBase<T> {
// private ObservableList<T> list;
// public TestClass(ObservableList<T> list) {
// this.list = list;
// list.addListener((ListChangeListener<? super T>) (onChange -> {
// sourceChanged(onChange);
// protected void sourceChanged(Change<? extends T> c) {
// beginChange();
// while (c.next()) {
// if (c.wasPermutated()) {
// throw new UnsupportedOperationException();
// } else if (c.wasUpdated()) {
// throw new UnsupportedOperationException();
// } else {
// endChange();
// private void addRemove(Change<? extends T> c) {
// if (c.wasPermutated()) {
// throw new UnsupportedOperationException();
// } else {
// if (c.wasRemoved()) {
// nextRemove(c.getFrom(), c.getRemoved());
// if (c.wasAdded()) {
// nextAdd(c.getFrom(), c.getFrom() + c.getAddedSubList().size());
// @Override
// public int size() {
// return list.size();
// @Override
// public T get(int index) {
// return list.get(index); |
package ol.source;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
/**
* params for MapGuide-requests.
* @author tlochmann
*/
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
public class ImageMapGuideParams {
/**
* @param mapDefinition
* MapGuide mapDefinition e.g. "Library://Samples/Sheboygan/Maps/Sheboygan.MapDefinition"
*/
@JsProperty
public native void setMapDefinition(String mapDefinition);
/**
* @param format
* MapGuide image format
*
*/
@JsProperty
public native void setFormat(String format);
} |
package org.jetel.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.jetel.exception.CompoundException;
import org.jetel.exception.JetelRuntimeException;
import org.jetel.exception.StackTraceWrapperException;
import org.jetel.util.string.StringUtils;
public class ExceptionUtils {
/**
* Converts stack trace of a given throwable to a string.
*
* @param throwable a throwable
*
* @return stack trace of the given throwable as a string
*/
public static String stackTraceToString(Throwable throwable) {
if (throwable == null) {
return null;
} else {
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter));
//let's look at the last exception in the chain
while (throwable.getCause() != null && throwable.getCause() != throwable) {
throwable = throwable.getCause();
}
//if the last exception is CompoundException, we have to print out stack traces even of these exceptions
if (throwable instanceof CompoundException) {
for (Throwable innerThrowable : ((CompoundException) throwable).getCauses()) {
stringWriter.append("\n");
stringWriter.append(stackTraceToString(innerThrowable));
}
}
//StackTraceWrapperException has to be handled in special way - stacktrace of a cause is stored in local attribute
if (throwable instanceof StackTraceWrapperException) {
String causeStackTrace = ((StackTraceWrapperException) throwable).getCauseStackTrace();
if (causeStackTrace != null) {
stringWriter.append("Caused by: " + causeStackTrace);
}
}
return stringWriter.toString();
}
}
/**
* Extract message from the given exception chain. All messages from all exceptions are concatenated
* to the resulted string.
* @param exception converted exception
* @return resulted overall message
*/
public static String getMessage(Throwable exception) {
return getMessage(null, exception);
}
/**
* Extract message from the given exception chain. All messages from all exceptions are concatenated
* to the resulted string.
* @param message prefixed message text which will be in the start of resulted string
* @param exception converted exception
* @return resulted overall message
*/
public static String getMessage(String message, Throwable exception) {
List<ErrorMessage> errMessages = getMessages(new JetelRuntimeException(message, exception), 0);
StringBuilder result = new StringBuilder();
for (ErrorMessage errMessage : errMessages) {
appendMessage(result, errMessage.message, errMessage.depth);
}
return result.toString();
}
private static class ErrorMessage {
int depth;
String message;
public ErrorMessage(int depth, String message) {
this.depth = depth;
this.message = message;
}
}
/**
* Extract message from the given exception chain. All messages from all exceptions are concatenated
* to the resulted string.
* @param message prefixed message text which will be in the start of resulted string
* @param exception converted exception
* @return resulted overall message
*/
private static List<ErrorMessage> getMessages(Throwable exception, int depth) {
List<ErrorMessage> result = new ArrayList<ErrorMessage>();
Throwable exceptionIterator = exception;
String lastMessage = "";
while (true) {
//extract message from current exception
String newMessage = getMessageNonRecurisve(exceptionIterator, lastMessage);
if (newMessage != null) {
result.add(new ErrorMessage(depth, newMessage));
depth++;
lastMessage = newMessage;
}
//CompoundException needs special handling
if (exceptionIterator instanceof CompoundException) {
for (Throwable t : ((CompoundException) exceptionIterator).getCauses()) {
result.addAll(getMessages(t, depth));
}
break;
}
if (exceptionIterator.getCause() == null || exceptionIterator.getCause() == exceptionIterator) {
break;
} else {
exceptionIterator = exceptionIterator.getCause();
}
}
return result;
}
private static String getMessageNonRecurisve(Throwable t, String lastMessage) {
String message = null;
//NPE is handled in special way
if (t instanceof NullPointerException
&& (StringUtils.isEmpty(t.getMessage()) || t.getMessage().equalsIgnoreCase("null"))) {
//in case the NPE has no reasonable message, we append more descriptive error message
message = "Unexpected null value.";
} else if (!StringUtils.isEmpty(t.getMessage())) {
//only non-empty messages are considered
message = t.getMessage();
}
//do not report exception message that is mentioned already in parent exception message
if (message != null && lastMessage != null && lastMessage.contains(message)) {
message = null;
}
//in case the exception was created with "new Throwable(Throwable cause)" constructor
//generic message of this exception is useless, since all necessary information are in cause
//and this is attempt to detect it and skip it in the message stack
Throwable cause = t.getCause();
if (message != null && cause != null
&&
(message.equals(cause.getClass().getName())
|| message.equals(cause.getClass().getName() + ": " + cause.getMessage()))) {
message = null;
}
return message;
}
private static void appendMessage(StringBuilder result, String message, int depth) {
String[] messageLines = message.split("\\n");
for (String messageLine : messageLines) {
if (!StringUtils.isEmpty(result)) {
result.append("\n");
}
for (int i = 0; i < depth; i++) {
result.append(" ");
}
result.append(messageLine);
}
}
/**
* Print out the given exception in preferred form into the given logger.
* @param logger
* @param message
* @param t
*/
public static void logException(Logger logger, String message, Throwable t) {
logger.error(ExceptionUtils.getMessage(message, t));
logger.error("Error details:\n" + ExceptionUtils.stackTraceToString(t));
}
/**
* Check whether the given exception or one of its children is instance of a given class.
* @param t exception to be searched
* @param exceptionClass searched exception type
* @return true if the given exception or some of its children is instance of a given class.
*/
public static boolean instanceOf(Throwable t, Class<? extends Throwable> exceptionClass) {
while (t != null) {
if (exceptionClass.isInstance(t)) {
return true;
}
if (t instanceof CompoundException) {
for (Throwable cause : ((CompoundException) t).getCauses()) {
if (instanceOf(cause, exceptionClass)) {
return true;
}
}
return false;
}
if (t != t.getCause()) {
t = t.getCause();
} else {
t = null;
}
}
return false;
}
/**
* Returns list of all exceptions of a given type in the given exception chain.
* @param t root of searched exception chain
* @param exceptionClass searched exception type
* @return list of exceptions with a given type in the given exception chain
*/
public static <T extends Throwable> List<T> getAllExceptions(Throwable t, Class<T> exceptionClass) {
List<T> result = new ArrayList<T>();
while (t != null) {
if (exceptionClass.isInstance(t)) {
result.add(exceptionClass.cast(t));
}
if (t instanceof CompoundException) {
for (Throwable cause : ((CompoundException) t).getCauses()) {
result.addAll(getAllExceptions(cause, exceptionClass));
}
return result;
}
if (t != t.getCause()) {
t = t.getCause();
} else {
t = null;
}
}
return result;
}
/**
* Print given message to logger. The message is surrounded in an ascii-art frame.
* @param message printed message
*/
public static void logHighlightedMessage(Logger logger, String message) {
final String LEFT_BORDER = " ";
final String RIGHT_BORDER = "";
final char TOP_BORDER = '-';
final String TOP_BORDER_LABEL = " Error details ";
final char BOTTOM_BORDER = '-';
int TOP_BORDER_LABEL_LOCATION = 3;
if (!StringUtils.isEmpty(message)) {
StringBuilder sb = new StringBuilder("\n");
//split message to separate lines
String[] messageLines = message.split("\n");
//find the longest message line
int maxLength = 80;
for (String messageLine : messageLines) {
if (messageLine.length() > maxLength) {
maxLength = messageLine.length();
}
}
TOP_BORDER_LABEL_LOCATION = (maxLength / 2) - (TOP_BORDER_LABEL.length() / 2);
//create header line of error message
for (int i = 0; i < maxLength + LEFT_BORDER.length() + RIGHT_BORDER.length(); i++) {
if (i >= TOP_BORDER_LABEL_LOCATION && i < TOP_BORDER_LABEL.length() + TOP_BORDER_LABEL_LOCATION) {
sb.append(TOP_BORDER_LABEL.charAt(i - TOP_BORDER_LABEL_LOCATION));
} else {
sb.append(TOP_BORDER);
}
}
sb.append('\n');
//append error message lines
for (String messageLine : messageLines) {
sb.append(LEFT_BORDER);
sb.append(messageLine);
if (RIGHT_BORDER.length() > 0) {
for (int i = messageLine.length(); i < maxLength; i++) {
sb.append(' ');
}
sb.append(RIGHT_BORDER);
}
sb.append('\n');
}
//append footer line of error message
for (int i = 0; i < maxLength + LEFT_BORDER.length() + RIGHT_BORDER.length(); i++) {
sb.append(BOTTOM_BORDER);
}
logger.error(sb.toString());
}
}
/**
* Print out error message of the given exception. The message is surrounded in an ascii-art frame.
* @param logger
* @param message
* @param exception
*/
public static void logHighlightedException(Logger logger, String message, Throwable exception) {
logHighlightedMessage(logger, getMessage(message, exception));
}
} |
package anubhav.calculatorapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.fathzer.soft.javaluator.DoubleEvaluator;
public class StandardCal extends AppCompatActivity {
EditText e1,e2;
private int count=0;
private String expression="";
private int len=0;
String text="";
Double result=0.0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_standard_cal);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.num0:
e2.setText(e2.getText()+"0");
break;
case R.id.num1:
e2.setText(e2.getText()+"1");
break;
case R.id.num2:
e2.setText(e2.getText()+"2");
break;
case R.id.num3:
e2.setText(e2.getText()+"3");
break;
case R.id.num4:
e2.setText(e2.getText()+"4");
break;
case R.id.num5:
e2.setText(e2.getText()+"5");
break;
case R.id.num6:
e2.setText(e2.getText()+"6");
break;
case R.id.num7:
e2.setText(e2.getText()+"7");
break;
case R.id.num8:
e2.setText(e2.getText()+"8");
break;
case R.id.num9:
e2.setText(e2.getText()+"9");
break;
case R.id.dot:
if(count==0 && e2.length()!=0)
{
e2.setText(e2.getText()+".");
count++;
}
break;
case R.id.clear:
e1.setText("");
e2.setText("");
count=0;
expression="";
break;
case R.id.backSpace:
text=e2.getText().toString();
if(text.endsWith("."))
{
count=0;
}
if(text.length()>0)
{
String newText=text.substring(0,text.length()-1);
//if e2 edit text contains only sqr or root or - sign then clear the edit text e2
if(!(newText.contains("0") || newText.contains("1") || newText.contains("2")|| newText.contains("3")
|| newText.contains("4")|| newText.contains("5")|| newText.contains("6")|| newText.contains("7")
|| newText.contains("8")|| newText.contains("9")))
{
newText="";
expression=expression.substring(0,len);
}
e2.setText(newText);
}
break;
case R.id.plus:
operationClicked("+");
break;
case R.id.minus:
operationClicked("-");
break;
case R.id.divide:
operationClicked("/");
break;
case R.id.multiply:
operationClicked("x");
break;
case R.id.sqrt:
if(e2.length()!=0)
{
text=e2.getText().toString();
len=expression.length();
expression+="sqrt("+text+")";
e2.setText("sqrt(" + text + ")");
}
break;
case R.id.square:
if(e2.length()!=0)
{
text=e2.getText().toString();
len=expression.length();
expression+="("+text+")^2";
e2.setText("("+text+")^2");
}
break;
case R.id.posneg:
if(e2.length()!=0)
{
String s=e2.getText().toString();
char arr[]=s.toCharArray();
if(arr[0]=='-')
e2.setText(s.substring(1,s.length()));
else
e2.setText("-"+s);
}
break;
case R.id.equal:
http://javaluator.sourceforge.net/en/home/*/ |
package gui.trace;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
/**
* This is a class designed to make it easier to send alerts and control them in
* a specific way without everyone climbing over each other to get print
* statements out there. It does this by requiring every message to have a tag
* associated with it. The default are ERROR, WARNING, or INFO, but you can add
* any you want. The nice part is that you can control which tags actually get
* printed to the console and which simply get put on to a list.
*
* @author Keith DeRuiter
* @version 2.0
*
* @see Alert
* @see AlertListener
* @see AlertLevel
*/
public class AlertLog {
/** Holds the single AlertLog instance. */
private static AlertLog instance = new AlertLog();
/** List of all {@link AlertListeners} that should be notified when an alert occurs. */
private List<AlertListener> registeredAlertListeners;
/**
* The list of {@link AlertLevel} that will print to the System.out/err console when added to the Log.
* Defaults to every level printing.
*/
private Set<AlertLevel> printedAlertLevels = Collections.synchronizedSet(EnumSet.allOf(AlertLevel.class));
/** The list of all the Alerts. */
private List<Alert> alerts = Collections.synchronizedList(new ArrayList<Alert>());
/**
* Private constructor to make AlertLog a singleton, creates a list to hold all alert listeners.
* Also sets the default printed types to be errors, warnings, and messages.
*/
private AlertLog() {
this.registeredAlertListeners = Collections.synchronizedList(new ArrayList<AlertListener>());
}
/**
* Gets the one instance of the AlertLog singleton.
* @return The one singleton instance of AlertLog.
*/
public static AlertLog getInstance() {
return AlertLog.instance;
}
/**
* Logs an error using {@link #sendAlert}.
* @param tag the {@link AlertTag} saying what group type this alert is tagged as.
* @param name The name of the thing sending this alert.
* @param message The message of this alert.
*/
public void logError(AlertTag tag, String name, String message) {
this.sendAlert(AlertLevel.ERROR, tag, name, message);
}
/**
* Logs a warning using {@link #sendAlert}.
* @param tag the {@link AlertTag} saying what group type this alert is tagged as.
* @param name The name of the thing sending this alert.
* @param message The message of this alert.
*/
public void logWarning(AlertTag tag, String name, String message) {
this.sendAlert(AlertLevel.WARNING, tag, name, message);
}
/**
* Logs info using {@link #sendAlert}.
* @param tag the {@link AlertTag} saying what group type this alert is tagged as.
* @param name The name of the thing sending this alert.
* @param message The message of this alert.
*/
public void logInfo(AlertTag tag, String name, String message) {
this.sendAlert(AlertLevel.INFO, tag, name, message);
}
/**
* Logs a message using {@link #sendAlert}.
* @param tag the {@link AlertTag} saying what group type this alert is tagged as.
* @param name The name of the thing sending this alert.
* @param message The message of this alert.
*/
public void logMessage(AlertTag tag, String name, String message) {
this.sendAlert(AlertLevel.MESSAGE, tag, name, message);
}
/**
* Logs a debug alert using {@link #sendAlert}.
* @param tag the {@link AlertTag} saying what group type this alert is tagged as.
* @param name The name of the thing sending this alert.
* @param message The message of this alert.
*/
public void logDebug(AlertTag tag, String name, String message) {
this.sendAlert(AlertLevel.DEBUG, tag, name, message);
}
/**
* Send an alert to the log.
*
* @param level The {@link AlertLevel} to log this message with.
* @param tag the {@link AlertTag} saying what group type this alert is tagged as.
* @param name The name of the thing sending this alert
* @param message The message to be logged.
*/
public void sendAlert(AlertLevel level, AlertTag tag, String name, String message) {
// StackTraceElement[] s = new RuntimeException().getStackTrace();
// String className = s[1].getClassName();
// String senderClassName = new Throwable().getStackTrace()[1].getClassName();
Date date = new Date(); //Timestamp
//Make the alert. Also prints to std out/err.
Alert alert = new Alert(level, tag, name, message, date);
if (this.printedAlertLevels.contains(level)) {
if (level == AlertLevel.ERROR) {
System.err.println(alert);
} else {
// System.out.println(alert);
}
}
this.alerts.add(alert);
//Notify all people who have told me they want to listen for alerts.
for(AlertListener al:this.registeredAlertListeners) {
al.alertOccurred(alert);
}
}
/**
* Enable an AlertLevel to the list of types that are printed to the console when an alert is made.
* If it is already on the list nothing will change. <br><br>
* NOTE: This only controls printing to the
* standard console at the time an alert is generated.
*
* @param type
*/
public void enableAlertLevel(AlertLevel type) {
this.printedAlertLevels.add(type);
}
/**
* Disable an AlertType from the list of types that are printed to the console when an alert is made.
* If it is not on the list nothing will change. <br><br>
* NOTE: This only controls printing to the
* standard System.out/System.err console at the time an alert is generated.
*
* @param type
*/
public void disableAlertLevel(AlertLevel type) {
this.printedAlertLevels.remove(type);
}
/**
* Get a copy of the list of all the alerts the AlertLog has collected.
*
* @return The list of all {@link Alert}s.
*/
public List<Alert> getAlerts() {
return new ArrayList<Alert>(this.alerts);
}
/**
* Registers someone to be notified when an alert is added.
* @param alertListener the listener to register.
*/
public void addAlertListener(AlertListener alertListener) {
if(registeredAlertListeners.contains(alertListener)) {
return;
}
registeredAlertListeners.add(alertListener);
}
} |
package com.gh4a.widget;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.IdRes;
import android.support.annotation.StringRes;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.gh4a.ProgressDialogTask;
import com.gh4a.R;
import com.gh4a.utils.UiUtils;
import org.eclipse.egit.github.core.User;
import java.io.IOException;
import java.util.Set;
public class EditorBottomSheet extends FrameLayout implements View.OnClickListener,
View.OnTouchListener, AppBarLayout.OnOffsetChangedListener {
public interface Callback {
@StringRes int getCommentEditorHintResId();
void onSendCommentInBackground(String comment) throws IOException;
void onCommentSent();
FragmentActivity getActivity();
CoordinatorLayout getRootLayout();
}
public interface OnToggleAdvancedModeListener {
void onToggleAdvancedMode(boolean advancedMode);
}
private TabLayout mTabs;
private ToggleableBottomSheetBehavior mBehavior;
private View mAdvancedEditorContainer;
private CommentEditor mBasicEditor;
private CommentEditor mAdvancedEditor;
private MarkdownButtonsBar mMarkdownButtons;
private MarkdownPreviewWebView mPreviewWebView;
private ImageView mAdvancedEditorToggle;
private OnToggleAdvancedModeListener mOnToggleAdvancedMode;
private Callback mCallback;
private View mResizingView;
private @ColorInt int mHighlightColor = Color.TRANSPARENT;
private int mBasicPeekHeight;
private int mAdvancedPeekHeight;
private int mLatestOffset;
private int mTopShadowHeight;
public EditorBottomSheet(Context context) {
super(context);
initialize();
}
public EditorBottomSheet(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public EditorBottomSheet(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}
private void initialize() {
final Resources res = getResources();
mBasicPeekHeight = res.getDimensionPixelSize(R.dimen.comment_editor_peek_height);
mAdvancedPeekHeight = res.getDimensionPixelSize(R.dimen.comment_advanced_editor_peek_height);
mTopShadowHeight = res.getDimensionPixelSize(R.dimen.bottom_sheet_top_shadow_height);
View view = View.inflate(getContext(), R.layout.editor_bottom_sheet, this);
mAdvancedEditorToggle = (ImageView) view.findViewById(R.id.iv_advanced_editor_toggle);
mAdvancedEditorToggle.setOnClickListener(this);
View sendButton = view.findViewById(R.id.send_button);
sendButton.setOnClickListener(this);
mBasicEditor = (CommentEditor) view.findViewById(R.id.et_basic_editor);
mBasicEditor.addTextChangedListener(
new UiUtils.ButtonEnableTextWatcher(mBasicEditor, sendButton));
}
public void setOnToggleAdvancedModeListener(OnToggleAdvancedModeListener listener) {
this.mOnToggleAdvancedMode = listener;
}
public void setCallback(Callback callback) {
mCallback = callback;
mBasicEditor.setCommentEditorHintResId(mCallback.getCommentEditorHintResId());
if (mAdvancedEditor != null) {
mAdvancedEditor.setCommentEditorHintResId(mCallback.getCommentEditorHintResId());
}
}
public void setLocked(boolean locked) {
mBasicEditor.setLocked(locked);
if (mAdvancedEditor != null) {
mAdvancedEditor.setLocked(locked);
}
}
public void setMentionUsers(Set<User> users) {
mBasicEditor.setMentionUsers(users);
if (mAdvancedEditor != null) {
mAdvancedEditor.setMentionUsers(users);
}
}
public void setHighlightColor(@AttrRes int colorAttrId) {
mHighlightColor = UiUtils.resolveColor(getContext(), colorAttrId);
if (mMarkdownButtons != null) {
mMarkdownButtons.setBackgroundColor(mHighlightColor);
}
}
public void addQuote(CharSequence text) {
if (isInAdvancedMode()) {
mAdvancedEditor.addQuote(text);
}
mBasicEditor.addQuote(text);
}
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
getBehavior().setEnabled(false);
break;
case MotionEvent.ACTION_UP:
getBehavior().setEnabled(true);
break;
}
return false;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_advanced_editor_toggle:
setAdvancedMode(!isInAdvancedMode());
break;
case R.id.send_button:
new CommentTask(getCommentText().toString()).schedule();
UiUtils.hideImeForView(mCallback.getActivity().getCurrentFocus());
break;
}
}
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
mLatestOffset = appBarLayout.getTotalScrollRange() + verticalOffset;
if (mLatestOffset >= 0) {
// Set the bottom padding to make the bottom appear as not moving while the
// AppBarLayout pushes it down or up.
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), mLatestOffset);
// Update peek height to keep the bottom sheet at unchanged position
updatePeekHeight(isInAdvancedMode());
}
}
public void setResizingView(View view) {
mResizingView = view;
}
public boolean isExpanded() {
return getBehavior().getState() == BottomSheetBehavior.STATE_EXPANDED
&& getBehavior().getPeekHeight() != getHeight();
}
private void updatePeekHeight(boolean isInAdvancedMode) {
final int peekHeight = isInAdvancedMode ? mAdvancedPeekHeight : mBasicPeekHeight;
if (mResizingView != null) {
mResizingView.setPadding(mResizingView.getPaddingLeft(), mResizingView.getPaddingTop(),
mResizingView.getPaddingRight(), peekHeight + mLatestOffset - mTopShadowHeight);
}
getBehavior().setPeekHeight(peekHeight + mLatestOffset);
}
public void setAdvancedMode(final boolean visible) {
if (visible) {
setAdvancedEditorVisible(true);
} else {
// When leaving advanced mode delay hiding it so the bottom sheet can finish collapse
// animation
postDelayed(new Runnable() {
@Override
public void run() {
setAdvancedEditorVisible(false);
}
}, 250);
}
// Expand bottom sheet through message queue so the animation can play.
post(new Runnable() {
@Override
public void run() {
updatePeekHeight(visible);
getBehavior().setState(visible
? BottomSheetBehavior.STATE_EXPANDED : BottomSheetBehavior.STATE_COLLAPSED);
}
});
}
public boolean isInAdvancedMode() {
return mAdvancedEditorContainer != null
&& mAdvancedEditorContainer.getVisibility() == View.VISIBLE;
}
public void setCommentText(CharSequence text, boolean clearFocus) {
if (isInAdvancedMode()) {
mAdvancedEditor.setText(text);
if (clearFocus) {
mAdvancedEditor.clearFocus();
}
} else {
mBasicEditor.setText(text);
if (clearFocus) {
mBasicEditor.clearFocus();
}
}
}
private Editable getCommentText() {
if (isInAdvancedMode()) {
return mAdvancedEditor.getText();
}
return mBasicEditor.getText();
}
private void setAdvancedEditorVisible(boolean visible) {
if (mAdvancedEditor == null) {
initAdvancedMode();
}
mAdvancedEditorContainer.setVisibility(visible ? View.VISIBLE : View.GONE);
mBasicEditor.setVisibility(visible ? View.GONE : View.VISIBLE);
mTabs.setVisibility(visible ? View.VISIBLE : View.GONE);
if (visible) {
mAdvancedEditor.setText(mBasicEditor.getText());
mAdvancedEditor.requestFocus();
mAdvancedEditor.setSelection(mAdvancedEditor.getText().length());
} else {
mBasicEditor.setText(mAdvancedEditor.getText());
mBasicEditor.requestFocus();
mBasicEditor.setSelection(mBasicEditor.getText().length());
}
mAdvancedEditorToggle.setImageResource(UiUtils.resolveDrawable(getContext(),
visible ? R.attr.collapseIcon : R.attr.expandIcon));
if (mOnToggleAdvancedMode != null) {
mOnToggleAdvancedMode.onToggleAdvancedMode(visible);
}
}
private void initAdvancedMode() {
ViewStub stub = (ViewStub) findViewById(R.id.advanced_editor_stub);
mAdvancedEditorContainer = stub.inflate();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new AdvancedEditorPagerAdapter(getContext()));
mTabs = (TabLayout) findViewById(R.id.tabs);
mTabs.setupWithViewPager(viewPager);
LinearLayout tabStrip = (LinearLayout) mTabs.getChildAt(0);
for (int i = 0; i < tabStrip.getChildCount(); i++) {
View tab = tabStrip.getChildAt(i);
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tab.getLayoutParams();
lp.width = LinearLayout.LayoutParams.WRAP_CONTENT;
lp.weight = 1;
tab.setLayoutParams(lp);
}
mAdvancedEditor = (CommentEditor) mAdvancedEditorContainer.findViewById(R.id.editor);
mAdvancedEditor.addTextChangedListener(
new UiUtils.ButtonEnableTextWatcher(mAdvancedEditor, findViewById(R.id.send_button)));
if (mCallback != null) {
mAdvancedEditor.setCommentEditorHintResId(mCallback.getCommentEditorHintResId());
}
mAdvancedEditor.setLocked(mBasicEditor.isLocked());
mAdvancedEditor.setMentionUsers(mBasicEditor.getMentionUsers());
mMarkdownButtons =
(MarkdownButtonsBar) mAdvancedEditorContainer.findViewById(R.id.markdown_buttons);
mMarkdownButtons.setEditText(mAdvancedEditor);
if (mHighlightColor != Color.TRANSPARENT) {
mMarkdownButtons.setBackgroundColor(mHighlightColor);
}
mPreviewWebView = (MarkdownPreviewWebView) findViewById(R.id.preview);
mPreviewWebView.setEditText(mAdvancedEditor);
mAdvancedEditorContainer.findViewById(R.id.editor_scroller).setOnTouchListener(this);
mPreviewWebView.setOnTouchListener(this);
mAdvancedEditor.setOnTouchListener(this);
viewPager.setOnTouchListener(this);
}
private ToggleableBottomSheetBehavior getBehavior() {
if (mBehavior == null) {
mBehavior = (ToggleableBottomSheetBehavior) BottomSheetBehavior.from(this);
}
return mBehavior;
}
private class CommentTask extends ProgressDialogTask<Void> {
private final String mText;
public CommentTask(String text) {
super(mCallback.getActivity(), mCallback.getRootLayout(), R.string.saving_comment);
mText = text;
}
@Override
protected ProgressDialogTask<Void> clone() {
return new CommentTask(mText);
}
@Override
protected Void run() throws IOException {
mCallback.onSendCommentInBackground(mText);
return null;
}
@Override
protected void onSuccess(Void result) {
mCallback.onCommentSent();
setCommentText(null, true);
setAdvancedMode(false);
}
@Override
protected String getErrorMessage() {
return getContext().getString(R.string.issue_error_comment);
}
}
private static class AdvancedEditorPagerAdapter extends PagerAdapter {
private static final int[] TITLES = new int[] {
R.string.edit, R.string.preview
};
private Context mContext;
public AdvancedEditorPagerAdapter(Context context) {
mContext = context;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
@IdRes
int resId = 0;
switch (position) {
case 0:
resId = R.id.comment_container;
break;
case 1:
resId = R.id.preview;
break;
}
return container.findViewById(resId);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public CharSequence getPageTitle(int position) {
return mContext.getString(TITLES[position]);
}
@Override
public int getCount() {
return TITLES.length;
}
}
} |
package com.samourai.wallet.util;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.HashMap;
public class UTXOUtil {
private static UTXOUtil instance = null;
private static HashMap<String,String> utxoTags = null;
private static HashMap<String,String> utxoNotes = null;
private UTXOUtil() { ; }
public static UTXOUtil getInstance() {
if(instance == null) {
utxoTags = new HashMap<String,String>();
utxoNotes = new HashMap<String,String>();
instance = new UTXOUtil();
}
return instance;
}
public void reset() {
utxoTags.clear();
utxoNotes.clear();
}
public void add(String utxo, String tag) {
utxoTags.put(utxo, tag);
}
public String get(String utxo) {
if(utxoTags.containsKey(utxo)) {
return utxoTags.get(utxo);
}
else {
return null;
}
}
public HashMap<String,String> getTags() {
return utxoTags;
}
public void remove(String utxo) {
utxoTags.remove(utxo);
}
public void addNote(String utxo, String note) {
utxoNotes.put(utxo, note);
}
public String getNote(String utxo) {
if(utxoNotes.containsKey(utxo)) {
return utxoNotes.get(utxo);
}
else {
return null;
}
}
public HashMap<String,String> getNotes() {
return utxoNotes;
}
public void removeNote(String utxo) {
utxoNotes.remove(utxo);
}
public JSONArray toJSON() {
JSONArray utxos = new JSONArray();
for(String key : utxoTags.keySet()) {
JSONArray tag = new JSONArray();
tag.put(key);
tag.put(utxoTags.get(key));
utxos.put(tag);
}
for(String key : utxoNotes.keySet()) {
JSONArray note = new JSONArray();
note.put(key);
note.put(utxoNotes.get(key));
utxos.put(note);
}
return utxos;
}
public void fromJSON(JSONArray utxos) {
try {
for(int i = 0; i < utxos.length(); i++) {
JSONArray tag = (JSONArray)utxos.get(i);
utxoTags.put((String)tag.get(0), (String)tag.get(1));
}
for(int i = 0; i < utxos.length(); i++) {
JSONArray note = (JSONArray)utxos.get(i);
utxoNotes.put((String)note.get(0), (String)note.get(1));
}
}
catch(JSONException ex) {
throw new RuntimeException(ex);
}
}
public JSONArray toJSON_notes() {
JSONArray utxos = new JSONArray();
for(String key : utxoNotes.keySet()) {
JSONArray note = new JSONArray();
note.put(key);
note.put(utxoNotes.get(key));
utxos.put(note);
}
return utxos;
}
public void fromJSON_notes(JSONArray utxos) {
try {
for(int i = 0; i < utxos.length(); i++) {
JSONArray note = (JSONArray)utxos.get(i);
utxoNotes.put((String)note.get(0), (String)note.get(1));
}
}
catch(JSONException ex) {
throw new RuntimeException(ex);
}
}
} |
package info.tregmine.gamemagic;
import info.tregmine.Tregmine;
import java.util.*;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.*;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.player.*;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.*;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
public class GameMagic extends JavaPlugin implements Listener
{
private Map<Integer, String> portalLookup;
public Tregmine tregmine = null;
public GameMagic()
{
portalLookup = new HashMap<Integer, String>();
}
@Override
public void onEnable()
{
PluginManager pluginMgm = getServer().getPluginManager();
// Check for tregmine plugin
if (tregmine == null) {
Plugin mainPlugin = pluginMgm.getPlugin("tregmine");
if (mainPlugin != null) {
tregmine = (Tregmine)mainPlugin;
} else {
Tregmine.LOGGER.info(getDescription().getName() + " " +
getDescription().getVersion() +
" - could not find Tregmine");
pluginMgm.disablePlugin(this);
return;
}
}
// Register events
pluginMgm.registerEvents(this, this);
pluginMgm.registerEvents(new Gates(this), this);
pluginMgm.registerEvents(new ButtonListener(this), this);
pluginMgm.registerEvents(new SpongeCouponListener(this), this);
WorldCreator alpha = new WorldCreator("alpha");
alpha.environment(World.Environment.NORMAL);
alpha.createWorld();
WorldCreator elva = new WorldCreator("elva");
elva.environment(World.Environment.NORMAL);
elva.createWorld();
WorldCreator treton = new WorldCreator("treton");
treton.environment(World.Environment.NORMAL);
treton.createWorld();
WorldCreator einhome = new WorldCreator("einhome");
einhome.environment(World.Environment.NORMAL);
einhome.createWorld();
WorldCreator citadel = new WorldCreator("citadel");
citadel.environment(World.Environment.NORMAL);
citadel.createWorld();
// Portal in tower of einhome
portalLookup.put(-1488547832, "world");
// Portal in elva
portalLookup.put(-1559526734, "world");
portalLookup.put(-1349166371, "treton");
portalLookup.put(1371197620, "citadel");
// portals in world
portalLookup.put(-973919203, "treton");
portalLookup.put(-777405698, "treton");
portalLookup.put(1259780606, "citadel");
portalLookup.put(690186900, "elva");
portalLookup.put(209068875, "einhome");
// portals in TRETON
portalLookup.put(45939467, "world");
portalLookup.put(-1408237330, "citadel");
portalLookup.put(559131756, "elva");
// portals in CITADEL
portalLookup.put(1609346891, "world");
portalLookup.put(-449465967, "treton");
portalLookup.put(1112623336, "elva");
// Shoot fireworks at spawn
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this,
new Runnable() {
public void run() {
World world = GameMagic.this.getServer().getWorld("world");
Location loc = world.getSpawnLocation().add(0.5, 0, 0.5);
FireworksFactory factory = new FireworksFactory();
factory.addColor(Color.BLUE);
factory.addColor(Color.YELLOW);
factory.addType(FireworkEffect.Type.STAR);
factory.shot(loc);
}
}, 100L, 200L);
}
public static int locationChecksum(Location loc)
{
int checksum = (loc.getBlockX() + "," +
loc.getBlockZ() + "," +
loc.getBlockY() + "," +
loc.getWorld().getName()).hashCode();
return checksum;
}
private void gotoWorld(Player player, Location loc)
{
Inventory inventory = player.getInventory();
for (int i = 0; i < inventory.getSize(); i++) {
if (inventory.getItem(i) != null) {
player.sendMessage(ChatColor.RED + "You are carrying too much " +
"for the portal's magic to work.");
return;
}
}
World world = loc.getWorld();
Chunk chunk = world.getChunkAt(loc);
world.loadChunk(chunk);
if (world.isChunkLoaded(chunk)) {
player.teleport(loc);
player.sendMessage(ChatColor.YELLOW + "Thanks for traveling with " +
"TregPort!");
} else {
player.sendMessage(ChatColor.RED + "The portal needs some " +
"preparation. Please try again!");
}
}
@EventHandler
public void buttons(PlayerInteractEvent event)
{
if (event.getAction() == Action.LEFT_CLICK_AIR ||
event.getAction() == Action.RIGHT_CLICK_AIR) {
return;
}
Block block = event.getClickedBlock();
Player player = event.getPlayer();
int checksum = locationChecksum(block.getLocation());
if (!portalLookup.containsKey(checksum)) {
return;
}
String worldName = portalLookup.get(checksum);
Location loc = getServer().getWorld(worldName).getSpawnLocation();
gotoWorld(player, loc);
}
@EventHandler
public void onPlayerBucketFill(PlayerBucketFillEvent event)
{
if ("alpha".equals(event.getPlayer().getWorld().getName())) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event)
{
if (event.getBlockClicked().getWorld().getName().equalsIgnoreCase(tregmine.getRulelessWorld().getName())) {
return;
}
if (event.getBucket() == Material.LAVA_BUCKET) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerPickupItem(PlayerPickupItemEvent event)
{
if ("alpha".equals(event.getPlayer().getWorld().getName())) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event)
{
if ("alpha".equals(event.getPlayer().getWorld().getName())) {
event.setCancelled(true);
}
}
@EventHandler
public void onCreatureSpawn(CreatureSpawnEvent event)
{
if (event.getSpawnReason() == SpawnReason.SPAWNER_EGG) {
event.setCancelled(true);
}
}
@EventHandler
public void onEntityExplode(EntityExplodeEvent event)
{
if (event.getLocation().getWorld().getName().equalsIgnoreCase(tregmine.getRulelessWorld().getName())) {
return;
}
event.setCancelled(true);
}
@EventHandler
public void onBlockBurn(BlockBurnEvent event)
{
if (event.getBlock().getWorld().getName().equalsIgnoreCase(tregmine.getRulelessWorld().getName())) {
return;
}
event.setCancelled(true);
}
@EventHandler
public void onLeavesDecay(LeavesDecayEvent event)
{
Location l = event.getBlock().getLocation();
Block fence =
event.getBlock()
.getWorld()
.getBlockAt(l.getBlockX(), l.getBlockY() - 1, l.getBlockZ());
if (fence.getType() == Material.FENCE) {
event.setCancelled(true);
}
}
@EventHandler
public void onBlockIgnite(BlockIgniteEvent event)
{
if (event.getBlock().getWorld().getName().equalsIgnoreCase(tregmine.getRulelessWorld().getName())) {
return;
}
event.setCancelled(true);
Location l = event.getBlock().getLocation();
Block block =
event.getBlock()
.getWorld()
.getBlockAt(l.getBlockX(), l.getBlockY() - 1, l.getBlockZ());
if (block.getType() == Material.OBSIDIAN) {
event.setCancelled(false);
}
}
@EventHandler
public void onUseElevator(PlayerInteractEvent event)
{
Player player = event.getPlayer();
Block block = event.getClickedBlock();
if (block == null) {
return;
}
if (block.getType().equals(Material.STONE_BUTTON)) {
Location loc = player.getLocation();
World world = player.getWorld();
Block standOn = world.getBlockAt(loc.getBlockX(), loc.getBlockY()-1, loc.getBlockZ());
if (Material.SPONGE.equals(standOn.getType())) {
Location bLoc = block.getLocation();
Block signBlock = world.getBlockAt(bLoc.getBlockX(), bLoc.getBlockY()+1, bLoc.getBlockZ());
if(signBlock.getState() instanceof Sign) {
Sign sign = (Sign) signBlock.getState();
if (sign.getLine(0).contains("up")) {
sign.setLine(0, ChatColor.DARK_RED + "Elevator");
sign.setLine(2, ChatColor.GOLD + "[" + ChatColor.DARK_GRAY + "UP" + ChatColor.GOLD + "]");
sign.update(true);
player.sendMessage(ChatColor.GREEN + "Elevator Setup!");
}
else if (sign.getLine(0).equals(ChatColor.DARK_RED + "Elevator")
&& sign.getLine(2).equals(ChatColor.GOLD + "[" + ChatColor.DARK_GRAY + "UP" + ChatColor.GOLD + "]")) {
int i = standOn.getLocation().getBlockY();
while (i < 255) {
i++;
Block sponge = event.getPlayer().getWorld().getBlockAt(standOn.getLocation().getBlockX(), i, standOn.getLocation().getBlockZ());
if (sponge.getType().equals(Material.SPONGE)) {
i=256;
Location tp = sponge.getLocation();
tp.setY(tp.getBlockY() + 1.5);
tp.setZ(tp.getBlockZ() + 0.5);
tp.setX(tp.getBlockX() + 0.5);
tp.setPitch(player.getLocation().getPitch());
tp.setYaw(player.getLocation().getYaw());
player.teleport(tp);
}
}
player.sendMessage(ChatColor.AQUA + "Going up");
}
// sign.setLine(0, ChatColor.DARK_PURPLE + "Elevator");
// sign.setLine(2, ChatColor.GOLD + "[ " + ChatColor.DARK_GRAY + "UP" + ChatColor.GOLD + " ]");
if (sign.getLine(0).contains("down")) {
sign.setLine(0, ChatColor.DARK_RED + "Elevator");
sign.setLine(2, ChatColor.GOLD + "[" + ChatColor.DARK_GRAY + "DOWN" + ChatColor.GOLD + "]");
sign.update(true);
player.sendMessage(ChatColor.GREEN + "Elevator Setup!");
}
else if (sign.getLine(0).equals(ChatColor.DARK_RED + "Elevator")
&& sign.getLine(2).equals(ChatColor.GOLD + "[" + ChatColor.DARK_GRAY + "DOWN" + ChatColor.GOLD + "]")) {
int i = standOn.getLocation().getBlockY();
while (i > 0) {
i
Block sponge = event.getPlayer().getWorld().getBlockAt(standOn.getLocation().getBlockX(), i, standOn.getLocation().getBlockZ());
if (sponge.getType().equals(Material.SPONGE)) {
i=0;
Location tp = sponge.getLocation();
tp.setY(tp.getBlockY() + 1.5);
tp.setZ(tp.getBlockZ() + 0.5);
tp.setX(tp.getBlockX() + 0.5);
tp.setPitch(player.getLocation().getPitch());
tp.setYaw(player.getLocation().getYaw());
player.teleport(tp);
}
}
player.sendMessage(ChatColor.AQUA +"Going down");
}
}
}
}
}
} |
package info.limpet.data;
import info.limpet.IBaseTemporalCollection;
import info.limpet.ICollection;
import info.limpet.ICommand;
import info.limpet.IStore;
import info.limpet.IStore.IStoreItem;
import info.limpet.ITemporalQuantityCollection.InterpMethod;
import info.limpet.data.csv.CsvParser;
import info.limpet.data.impl.TemporalObjectCollection;
import info.limpet.data.impl.samples.StockTypes;
import info.limpet.data.impl.samples.StockTypes.NonTemporal;
import info.limpet.data.impl.samples.StockTypes.NonTemporal.Location;
import info.limpet.data.impl.samples.StockTypes.Temporal;
import info.limpet.data.impl.samples.StockTypes.Temporal.Speed_Kts;
import info.limpet.data.impl.samples.TemporalLocation;
import info.limpet.data.operations.CollectionComplianceTests;
import info.limpet.data.operations.CollectionComplianceTests.TimePeriod;
import info.limpet.data.operations.spatial.DistanceBetweenTracksOperation;
import info.limpet.data.operations.spatial.DopplerShiftBetweenTracksOperation;
import info.limpet.data.operations.spatial.DopplerShiftBetweenTracksOperation.DopplerShiftOperation;
import info.limpet.data.operations.spatial.GenerateCourseAndSpeedOperation;
import info.limpet.data.operations.spatial.GeoSupport;
import info.limpet.data.store.InMemoryStore;
import info.limpet.data.store.InMemoryStore.StoreGroup;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import javax.measure.converter.ConversionException;
import javax.measure.quantity.Frequency;
import junit.framework.TestCase;
import org.geotools.factory.Hints;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.geometry.GeometryBuilder;
import org.geotools.geometry.GeometryFactoryFinder;
import org.geotools.referencing.GeodeticCalculator;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.junit.Assert;
import org.opengis.geometry.DirectPosition;
import org.opengis.geometry.Geometry;
import org.opengis.geometry.primitive.Point;
import org.opengis.geometry.primitive.PrimitiveFactory;
import org.opengis.referencing.operation.TransformException;
public class TestGeotoolsGeometry extends TestCase
{
public void testCreateTemporalObjectCollection()
{
TemporalObjectCollection<Geometry> locations = new TemporalObjectCollection<Geometry>(
"test");
assertNotNull(locations);
}
public void testGenerateSingleCourse() throws IOException
{
File file = TestCsvParser.getDataFile("americas_cup/usa.csv");
assertTrue(file.isFile());
CsvParser parser = new CsvParser();
List<IStoreItem> items = parser.parse(file.getAbsolutePath());
assertEquals("correct group", 1, items.size());
StoreGroup group = (StoreGroup) items.get(0);
assertEquals("correct num collections", 3, group.size());
ICollection firstColl = (ICollection) group.get(2);
assertEquals("correct num rows", 1708, firstColl.size());
TemporalLocation track = (TemporalLocation) firstColl;
GenerateCourseAndSpeedOperation genny = new GenerateCourseAndSpeedOperation();
List<IStoreItem> sel = new ArrayList<IStoreItem>();
sel.add(track);
InMemoryStore store = new InMemoryStore();
Collection<ICommand<IStoreItem>> ops = genny.actionsFor(sel, store);
assertNotNull("created command", ops);
assertEquals("created operatoins", 2, ops.size());
ICommand<IStoreItem> firstOp = ops.iterator().next();
assertEquals("store empty", 0, store.size());
firstOp.execute();
assertEquals("new coll created", 1, store.size());
ICollection newColl = (ICollection) firstOp.getOutputs().get(0);
assertEquals("correct size", firstColl.size() - 1, newColl.size());
assertNotNull("knows about parent", newColl.getPrecedent());
}
public void testGenerateMultipleCourse() throws IOException
{
File file = TestCsvParser.getDataFile("americas_cup/usa.csv");
assertTrue(file.isFile());
File file2 = TestCsvParser.getDataFile("americas_cup/nzl.csv");
assertTrue(file2.isFile());
CsvParser parser = new CsvParser();
List<IStoreItem> items = parser.parse(file.getAbsolutePath());
assertEquals("correct group", 1, items.size());
StoreGroup group = (StoreGroup) items.get(0);
assertEquals("correct num collections", 3, group.size());
ICollection firstColl = (ICollection) group.get(2);
assertEquals("correct num rows", 1708, firstColl.size());
List<IStoreItem> items2 = parser.parse(file2.getAbsolutePath());
assertEquals("correct group", 1, items2.size());
StoreGroup group2 = (StoreGroup) items2.get(0);
assertEquals("correct num collections", 3, group2.size());
ICollection secondColl = (ICollection) group2.get(2);
assertEquals("correct num rows", 1708, secondColl.size());
TemporalLocation track1 = (TemporalLocation) firstColl;
TemporalLocation track2 = (TemporalLocation) secondColl;
GenerateCourseAndSpeedOperation genny = new GenerateCourseAndSpeedOperation();
List<IStoreItem> sel = new ArrayList<IStoreItem>();
sel.add(track1);
sel.add(track2);
InMemoryStore store = new InMemoryStore();
List<ICommand<IStoreItem>> ops = (List<ICommand<IStoreItem>>) genny
.actionsFor(sel, store);
assertNotNull("created command", ops);
assertEquals("created operatoins", 2, ops.size());
ICommand<IStoreItem> courseOp = ops.get(0);
assertEquals("store empty", 0, store.size());
courseOp.execute();
assertEquals("new colls created", 2, store.size());
ICollection newColl = (ICollection) courseOp.getOutputs().get(0);
assertEquals("correct size", firstColl.size() - 1, newColl.size());
ICommand<IStoreItem> speedOp = ops.get(1);
assertEquals("store empty", 2, store.size());
speedOp.execute();
assertEquals("new colls created", 4, store.size());
newColl = (ICollection) courseOp.getOutputs().get(0);
assertEquals("correct size", firstColl.size() - 1, newColl.size());
}
public void testBuilder() throws TransformException
{
final Location track_1 = new StockTypes.NonTemporal.Location(
"some location data");
GeometryBuilder builder = new GeometryBuilder(DefaultGeographicCRS.WGS84);
GeodeticCalculator geoCalc = new GeodeticCalculator(
DefaultGeographicCRS.WGS84);
DirectPosition pos_1 = new DirectPosition2D(-4, 55.8);
geoCalc.setStartingGeographicPoint(pos_1.getOrdinate(0),
pos_1.getOrdinate(1));
geoCalc.setDirection(Math.toRadians(54), 0.003);
pos_1 = geoCalc.getDestinationPosition();
Point p1 = builder.createPoint(pos_1.getOrdinate(0), pos_1.getOrdinate(1));
track_1.add(p1);
assertEquals("track has point", 1, track_1.size());
}
public void testCreatePoint()
{
GeometryBuilder builder = new GeometryBuilder(DefaultGeographicCRS.WGS84);
Point point = builder.createPoint(48.44, -123.37);
Assert.assertNotNull(point);
Hints hints = new Hints(Hints.CRS, DefaultGeographicCRS.WGS84);
PrimitiveFactory primitiveFactory = GeometryFactoryFinder
.getPrimitiveFactory(hints);
Point point2 = primitiveFactory.createPoint(new double[]
{ 48.44, -123.37 });
Assert.assertNotNull(point2);
}
public void testRangeCalc()
{
GeodeticCalculator calc = GeoSupport.getCalculator();
Point p1 = GeoSupport.getBuilder().createPoint(0, 80);
Point p2 = GeoSupport.getBuilder().createPoint(0, 81);
Point p3 = GeoSupport.getBuilder().createPoint(1, 80);
calc.setStartingGeographicPoint(p1.getCentroid().getOrdinate(0), p1
.getCentroid().getOrdinate(1));
calc.setDestinationGeographicPoint(p2.getCentroid().getOrdinate(0), p2
.getCentroid().getOrdinate(1));
final double dest1 = calc.getOrthodromicDistance();
calc.setDestinationGeographicPoint(p3.getCentroid().getOrdinate(0), p3
.getCentroid().getOrdinate(1));
final double dest2 = calc.getOrthodromicDistance();
assertEquals("range 1 right", 111663, dest1, 10);
assertEquals("range 2 right", 19393, dest2, 10);
}
public void testBearingCalc()
{
GeodeticCalculator calc = GeoSupport.getCalculator();
Point p1 = GeoSupport.getBuilder().createPoint(1, 0);
Point p2 = GeoSupport.getBuilder().createPoint(2, 1);
calc.setStartingGeographicPoint(p1.getCentroid().getOrdinate(0), p1
.getCentroid().getOrdinate(1));
calc.setDestinationGeographicPoint(p2.getCentroid().getOrdinate(0), p2
.getCentroid().getOrdinate(1));
assertEquals("correct result", 45, calc.getAzimuth(), 0.2);
}
public void testLocationInterp()
{
TemporalLocation loc1 = new TemporalLocation("loc1");
GeometryBuilder builder = GeoSupport.getBuilder();
loc1.add(1000, builder.createPoint(2, 3));
loc1.add(2000, builder.createPoint(3, 4));
Geometry geo1 = loc1.interpolateValue(1500, InterpMethod.Linear);
assertEquals("correct value", 2.5, geo1.getRepresentativePoint()
.getDirectPosition().getCoordinate()[0]);
assertEquals("correct value", 3.5, geo1.getRepresentativePoint()
.getDirectPosition().getCoordinate()[1]);
geo1 = loc1.interpolateValue(1700, InterpMethod.Linear);
assertEquals("correct value", 2.7, geo1.getRepresentativePoint()
.getDirectPosition().getCoordinate()[0]);
assertEquals("correct value", 3.7, geo1.getRepresentativePoint()
.getDirectPosition().getCoordinate()[1]);
}
public void testLocationCalc()
{
TemporalLocation loc1 = new TemporalLocation("loc1");
TemporalLocation loc2 = new TemporalLocation("loc2");
Temporal.Length_M len1 = new Temporal.Length_M("dummy2");
List<IStoreItem> selection = new ArrayList<IStoreItem>();
selection.add(loc1);
IStore store = new InMemoryStore();
;
Collection<ICommand<IStoreItem>> ops = new DistanceBetweenTracksOperation()
.actionsFor(selection, store);
assertEquals("empty collection", 0, ops.size());
selection.add(len1);
ops = new DistanceBetweenTracksOperation().actionsFor(selection, store);
assertEquals("empty collection", 0, ops.size());
selection.remove(len1);
selection.add(loc2);
ops = new DistanceBetweenTracksOperation().actionsFor(selection, store);
assertEquals("empty collection", 1, ops.size());
// ok, try adding some data
GeometryBuilder builder = GeoSupport.getBuilder();
loc1.add(1000, builder.createPoint(4, 3));
loc2.add(2000, builder.createPoint(3, 4));
ops = new DistanceBetweenTracksOperation().actionsFor(selection, store);
assertEquals("empty collection", 1, ops.size());
}
@SuppressWarnings("unused")
public void testDoppler()
{
final ArrayList<IStoreItem> items = new ArrayList<IStoreItem>();
final DopplerShiftBetweenTracksOperation doppler = new DopplerShiftBetweenTracksOperation();
final InMemoryStore store = new InMemoryStore();
final CollectionComplianceTests tests = new CollectionComplianceTests();
// create datasets
TemporalLocation loc1 = new TemporalLocation("loc 1");
TemporalLocation loc2 = new TemporalLocation("loc 2");
NonTemporal.Location loc3 = new NonTemporal.Location("loc 3");
NonTemporal.Location loc4 = new NonTemporal.Location("loc 4");
Temporal.Angle_Degrees angD1 = new Temporal.Angle_Degrees("ang D 1", null);
Temporal.Angle_Radians angR2 = new Temporal.Angle_Radians("ang R 2");
NonTemporal.Angle_Radians angR3 = new NonTemporal.Angle_Radians("ang R 3");
NonTemporal.Angle_Degrees angD4 = new NonTemporal.Angle_Degrees("ang D 4");
Temporal.Speed_Kts spdK1 = new Temporal.Speed_Kts("speed kts 1");
Temporal.Speed_MSec spdM2 = new Temporal.Speed_MSec("speed M 2");
NonTemporal.Speed_Kts spdK3 = new NonTemporal.Speed_Kts("speed kts 1");
NonTemporal.Speed_MSec spdM4 = new NonTemporal.Speed_MSec("speed kts 1");
Temporal.Frequency_Hz freq1 = new Temporal.Frequency_Hz("freq 1");
NonTemporal.Frequency_Hz freq2 = new NonTemporal.Frequency_Hz("freq 2");
Temporal.Speed_MSec sspdM1 = new Temporal.Speed_MSec("sound speed M 1");
NonTemporal.Speed_Kts sspdK2 = new NonTemporal.Speed_Kts(
"sound speed kts 2");
// populate the datasets
for (int i = 10000; i <= 90000; i += 5000)
{
double j = Math.toRadians(i / 1000);
loc1.add(
i,
GeoSupport.getBuilder().createPoint(2 + Math.cos(5 * j) * 5,
4 + Math.sin(6 * j) * 5));
if (i % 2000 == 0)
loc2.add(
i,
GeoSupport.getBuilder().createPoint(4 - Math.cos(3 * j) * 2,
9 - Math.sin(4 * j) * 3));
if (i % 2000 == 0)
angD1.add(i, 55 + Math.sin(j) * 4);
if (i % 3000 == 0)
angR2.add(i, Math.toRadians(45 + Math.cos(j) * 3));
if (i % 4000 == 0)
spdK1.add(i, 5 + Math.sin(j) * 2);
if (i % 6000 == 0)
spdM2.add(i, 6 + Math.sin(j) * 2);
if (i % 3000 == 0)
freq1.add(i, 55 + Math.sin(j) * 4);
if (i % 4000 == 0)
sspdM1.add(i, 950 + Math.sin(j) * 4);
}
loc3.add(GeoSupport.getBuilder().createPoint(4, 9));
loc4.add(GeoSupport.getBuilder().createPoint(6, 12));
angR3.add(Math.toRadians(155));
angD4.add(255);
freq2.add(55.5);
sspdK2.add(400);
spdK3.add(4);
// check we've got roughly the right amount of data
assertEquals("correct items", 17, loc1.size());
assertEquals("correct items", 9, loc2.size());
assertEquals("correct items", 9, angD1.size());
assertEquals("correct items", 6, angR2.size());
assertEquals("correct items", 4, spdK1.size());
assertEquals("correct items", 3, spdM2.size());
assertEquals("correct items", 6, freq1.size());
// create some incomplete input data
StoreGroup track1 = new StoreGroup("Track 1");
StoreGroup track2 = new StoreGroup("Track 1");
items.add(track1);
items.add(track2);
assertEquals("empty", 0, doppler.actionsFor(items, store).size());
track1.add(loc1);
assertEquals("empty", 0, doppler.actionsFor(items, store).size());
track1.add(angD1);
assertEquals("empty", 0, doppler.actionsFor(items, store).size());
assertFalse("valid track", tests.numberOfTracks(items, 1));
track1.add(spdK1);
assertEquals("empty", 0, doppler.actionsFor(items, store).size());
assertTrue("valid track", tests.numberOfTracks(items, 1));
// now for track two
track2.add(loc2);
track2.add(angR2);
assertFalse("valid track", tests.numberOfTracks(items, 2));
track2.add(spdK3);
assertTrue("valid track", tests.numberOfTracks(items, 2));
assertEquals("still empty", 0, doppler.actionsFor(items, store).size());
assertEquals("has freq", null,
tests.someHave(items, Frequency.UNIT.getDimension(), true));
// give one a freq
track1.add(freq1);
assertEquals("still empty", 0, doppler.actionsFor(items, store).size());
assertEquals("has freq", null,
tests.someHave(items, Frequency.UNIT.getDimension(), false));
assertNotNull("has freq",
tests.someHave(items, Frequency.UNIT.getDimension(), true));
assertNotNull("has freq",
tests.someHave(track1, Frequency.UNIT.getDimension(), true));
assertEquals("has freq", null,
tests.someHave(track2, Frequency.UNIT.getDimension(), true));
// and now complete dataset (with temporal location)
// add the missing sound speed
items.add(sspdK2);
assertEquals("not empty", 1, doppler.actionsFor(items, store).size());
// and now complete dataset (with one non temporal location)
track1.remove(loc1);
track1.add(loc3);
assertEquals("not empty", 1, doppler.actionsFor(items, store).size());
// and now complete dataset (with two non temporal locations)
track2.remove(loc2);
track2.add(loc4);
assertEquals("not empty", 1, doppler.actionsFor(items, store).size());
// back to original type
track1.remove(loc3);
track1.add(loc1);
track2.remove(loc4);
track2.add(loc2);
assertEquals("not empty", 1, doppler.actionsFor(items, store).size());
// try giving track 2 a frewquency
track2.add(freq2);
assertEquals("actions for both tracks", 2, doppler.actionsFor(items, store).size());
// and remove that freq
track2.remove(freq2);
assertEquals("actions for just one track", 1, doppler.actionsFor(items, store).size());
// quick extra test
track1.remove(loc1);
assertEquals("empty", 0, doppler.actionsFor(items, store).size());
// quick extra test
track1.add(loc1);
assertEquals("empty", 1, doppler.actionsFor(items, store).size());
// ok, now check how the doppler handler organises its data
DopplerShiftOperation op1 = (DopplerShiftOperation) doppler
.actionsFor(items, store).iterator().next();
assertNotNull("found operation", op1);
op1.organiseData();
HashMap<String, ICollection> map = op1.getDataMap();
assertEquals("all items", 8, map.size());
// ok, let's try undo redo
assertEquals("correct size store", store.size(), 0);
op1.execute();
assertEquals("new correct size store", store.size(), 1);
op1.undo();
assertEquals("new correct size store", store.size(), 0);
op1.redo();
assertEquals("new correct size store", store.size(), 1);
op1.undo();
assertEquals("new correct size store", store.size(), 0);
op1.redo();
assertEquals("new correct size store", store.size(), 1);
}
public void testGetOptimalTimes()
{
CollectionComplianceTests aTests = new CollectionComplianceTests();
Collection<ICollection> items = new ArrayList<ICollection>();
Speed_Kts speed1 = new Temporal.Speed_Kts("spd1");
Speed_Kts speed2 = new Temporal.Speed_Kts("spd2");
Speed_Kts speed3 = new Temporal.Speed_Kts("spd3");
speed1.add(100, 5);
speed1.add(120, 5);
speed1.add(140, 5);
speed1.add(160, 5);
speed1.add(180, 5);
speed2.add(130, 5);
speed2.add(140, 5);
speed2.add(141, 5);
speed2.add(142, 5);
speed2.add(143, 5);
speed2.add(145, 5);
speed2.add(150, 5);
speed2.add(160, 5);
speed2.add(230, 5);
speed3.add(90, 5);
speed3.add(120, 5);
speed3.add(160, 5);
TimePeriod period = new TimePeriod(120, 180);
IBaseTemporalCollection common = aTests.getOptimalTimes(period , items);
assertEquals("duh, empty set",null, common);
items.add(speed1);
period = aTests.getBoundingTime(items);
assertEquals("correct period", 100, period.startTime);
assertEquals("correct period", 180, period.endTime);
common = aTests.getOptimalTimes(period, items);
assertNotNull("duh, empty set",common);
assertEquals("correct choice", common, speed1);
items.add(speed2);
common = aTests.getOptimalTimes(period, items);
assertNotNull("duh, empty set",common);
assertEquals("correct choice", common, speed2);
items.add(speed3);
common = aTests.getOptimalTimes(period, items);
assertNotNull("duh, empty set",common);
assertEquals("still correct choice", common, speed2);
// step back, test it without the period
common = aTests.getOptimalTimes(null, items);
assertNotNull("duh, empty set",common);
assertEquals("correct choice", common, speed2);
}
public void testGetCommonTimePeriod()
{
CollectionComplianceTests aTests = new CollectionComplianceTests();
Collection<ICollection> items = new ArrayList<ICollection>();
Speed_Kts speed1 = new Temporal.Speed_Kts("spd1");
Speed_Kts speed2 = new Temporal.Speed_Kts("spd2");
Speed_Kts speed3 = new Temporal.Speed_Kts("spd3");
speed1.add(100, 5);
speed1.add(120, 5);
speed1.add(140, 5);
speed1.add(160, 5);
speed1.add(180, 5);
speed2.add(130, 5);
speed2.add(230, 5);
speed3.add(90, 5);
speed3.add(120, 5);
speed3.add(160, 5);
TimePeriod common = aTests.getBoundingTime(items);
assertEquals("duh, empty set",null, common);
// ok, now add the items to hte collection
items.add(speed1);
common = aTests.getBoundingTime(items);
assertNotNull("duh, empty set",common);
assertEquals("correct times", speed1.start(), common.startTime);
assertEquals("correct times", speed1.finish(), common.endTime);
items.add(speed2);
common = aTests.getBoundingTime(items);
assertNotNull("duh, empty set",common);
assertEquals("correct times", speed2.start(), common.startTime);
assertEquals("correct times", speed1.finish(), common.endTime);
items.add(speed3);
common = aTests.getBoundingTime(items);
assertNotNull("duh, empty set",common);
assertEquals("correct times", speed2.start(), common.startTime);
assertEquals("correct times", speed3.finish(), common.endTime);
}
public void testDopplerInterpolation()
{
final CollectionComplianceTests aTests = new CollectionComplianceTests();
Temporal.Speed_Kts sKts = new Temporal.Speed_Kts("Speed knots");
sKts.add(1000, 10);
sKts.add(2000, 20);
sKts.add(4000, 30);
double val = aTests.valueAt(sKts, 1500L, sKts.getUnits());
assertEquals("correct value", 15.0, val);
val = aTests.valueAt(sKts, 3000L, sKts.getUnits());
assertEquals("correct value", 25.0, val);
// try converting to m_sec
val = aTests.valueAt(sKts, 1500L, new Temporal.Speed_MSec().getUnits());
assertEquals("correct value", 7.72, val, 0.01);
// try converting to m_sec
try
{
val = aTests.valueAt(sKts, 1500L,
new Temporal.Angle_Degrees().getUnits());
}
catch (ConversionException ce)
{
assertNotNull("exception thrown", ce);
}
}
} |
package com.mongodb.rhino;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Undefined;
import com.mongodb.rhino.util.JSONException;
import com.mongodb.rhino.util.JSONTokener;
public class JSON
{
// Static operations
/**
* Recursively convert from JSON into native JavaScript values.
* <p>
* Creates JavaScript objects, arrays and primitives.
*
* @param json
* The JSON string
* @return A JavaScript object or array
* @throws JSONException
*/
public static Object from( String json ) throws JSONException
{
return from( json, false );
}
public static Object from( String json, boolean extendedJSON ) throws JSONException
{
JSONTokener tokener = new JSONTokener( json );
Object object = tokener.createNative();
if( extendedJSON )
object = fromExtendedJSON( object );
return object;
}
/**
* Recursively convert from native JavaScript, a few JVM types and BSON
* types to extended JSON.
* <p>
* Recognizes JavaScript objects, arrays, Date objects, RegExp objects and
* primitives.
* <p>
* Recognizes JVM types: java.util.Map, java.util.Collection,
* java.util.Date, java.util.regex.Pattern and java.lang.Long.
* <p>
* Recognizes BSON types: ObjectId, Binary and DBRef.
*
* @param object
* A native JavaScript object
* @return The JSON string
* @see #fromExtendedJSON(Object)
*/
public static String to( Object object )
{
return to( object, false );
}
/**
* Recursively convert from native JavaScript, a few JVM types and BSON
* types to extended JSON.
* <p>
* Recognizes JavaScript objects, arrays, Date objects, RegExp objects and
* primitives.
* <p>
* Recognizes JVM types: java.util.Map, java.util.Collection, java.util.Date
* and java.util.regex.Pattern.
* <p>
* Recognizes BSON types: ObjectId, Binary and DBRef.
* <p>
* Note that java.lang.Long will be converted only if necessary in order to
* preserve its value when converted to a JavaScript Number object.
*
* @param object
* A native JavaScript object
* @param indent
* Whether to indent the JSON for human readability
* @return The JSON string
* @see #fromExtendedJSON(Object)
*/
public static String to( Object object, boolean indent )
{
StringBuilder s = new StringBuilder();
encode( s, object, indent, indent ? 0 : -1 );
return s.toString();
}
public static Object fromExtendedJSON( Object object )
{
if( object instanceof NativeArray )
{
NativeArray array = (NativeArray) object;
int length = (int) array.getLength();
for( int i = 0; i < length; i++ )
{
Object value = ScriptableObject.getProperty( array, i );
Object converted = fromExtendedJSON( value );
if( converted != value )
ScriptableObject.putProperty( array, i, converted );
}
}
else if( object instanceof ScriptableObject )
{
ScriptableObject scriptable = (ScriptableObject) object;
Object r = ExtendedJSON.from( scriptable, true );
if( r != null )
return r;
// Convert regular Rhino object
Object[] ids = scriptable.getAllIds();
for( Object id : ids )
{
String key = id.toString();
Object value = ScriptableObject.getProperty( scriptable, key );
Object converted = fromExtendedJSON( value );
if( converted != value )
ScriptableObject.putProperty( scriptable, key, converted );
}
}
return object;
}
// Private
private static void encode( StringBuilder s, Object object, boolean indent, int depth )
{
if( indent )
indent( s, depth );
Object r = ExtendedJSON.to( object, false );
if( r != null )
{
encode( s, r, indent, depth );
return;
}
if( ( object == null ) || ( object instanceof Undefined ) )
s.append( "null" );
else if( ( object instanceof Number ) || ( object instanceof Boolean ) )
s.append( object );
else if( object instanceof NativeJavaObject )
{
// This happens either because the developer purposely creates a
// Java object, or because it was returned from a Java call and
// wrapped by Rhino.
encode( s, ( (NativeJavaObject) object ).unwrap(), false, depth );
}
else if( object instanceof Collection )
encode( s, (Collection<?>) object, depth );
else if( object instanceof Map )
encode( s, (Map<?, ?>) object, depth );
else if( object instanceof NativeArray )
encode( s, (NativeArray) object, depth );
else if( object instanceof ScriptableObject )
{
ScriptableObject scriptable = (ScriptableObject) object;
String className = scriptable.getClassName();
if( className.equals( "String" ) )
{
// Unpack NativeString
s.append( '\"' );
s.append( escape( object.toString() ) );
s.append( '\"' );
}
else if( className.equals( "Function" ) )
{
// Trying to encode functions can result in stack overflows...
s.append( '\"' );
s.append( escape( object.toString() ) );
s.append( '\"' );
}
else
encode( s, scriptable, depth );
}
else
{
s.append( '\"' );
s.append( escape( object.toString() ) );
s.append( '\"' );
}
}
private static void encode( StringBuilder s, Collection<?> collection, int depth )
{
s.append( '[' );
Iterator<?> i = collection.iterator();
if( i.hasNext() )
{
if( depth > -1 )
s.append( '\n' );
while( true )
{
Object value = i.next();
encode( s, value, true, depth > -1 ? depth + 1 : -1 );
if( i.hasNext() )
{
s.append( ',' );
if( depth > -1 )
s.append( '\n' );
}
else
break;
}
if( depth > -1 )
{
s.append( '\n' );
indent( s, depth );
}
}
s.append( ']' );
}
private static void encode( StringBuilder s, Map<?, ?> map, int depth )
{
s.append( '{' );
Iterator<?> i = map.entrySet().iterator();
if( i.hasNext() )
{
if( depth > -1 )
s.append( '\n' );
while( true )
{
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) i.next();
String key = entry.getKey().toString();
Object value = entry.getValue();
if( depth > -1 )
indent( s, depth + 1 );
s.append( '\"' );
s.append( escape( key ) );
s.append( "\":" );
if( depth > -1 )
s.append( ' ' );
encode( s, value, false, depth > -1 ? depth + 1 : -1 );
if( i.hasNext() )
{
s.append( ',' );
if( depth > -1 )
s.append( '\n' );
}
else
break;
}
if( depth > -1 )
{
s.append( '\n' );
indent( s, depth );
}
}
s.append( '}' );
}
private static void encode( StringBuilder s, NativeArray array, int depth )
{
s.append( '[' );
long length = array.getLength();
if( length > 0 )
{
if( depth > -1 )
s.append( '\n' );
for( int i = 0; i < length; i++ )
{
Object value = ScriptableObject.getProperty( array, i );
encode( s, value, true, depth > -1 ? depth + 1 : -1 );
if( i < length - 1 )
{
s.append( ',' );
if( depth > -1 )
s.append( '\n' );
}
}
if( depth > -1 )
{
s.append( '\n' );
indent( s, depth );
}
}
s.append( ']' );
}
private static void encode( StringBuilder s, ScriptableObject object, int depth )
{
s.append( '{' );
Object[] ids = object.getAllIds();
int length = ids.length;
if( length > 0 )
{
if( depth > -1 )
s.append( '\n' );
for( int i = 0; i < length; i++ )
{
String key = ids[i].toString();
Object value = ScriptableObject.getProperty( object, key );
if( depth > -1 )
indent( s, depth + 1 );
s.append( '\"' );
s.append( escape( key ) );
s.append( "\":" );
if( depth > -1 )
s.append( ' ' );
encode( s, value, false, depth > -1 ? depth + 1 : -1 );
if( i < length - 1 )
{
s.append( ',' );
if( depth > -1 )
s.append( '\n' );
}
}
if( depth > -1 )
{
s.append( '\n' );
indent( s, depth );
}
}
s.append( '}' );
}
private static void indent( StringBuilder s, int depth )
{
for( int i = depth - 1; i >= 0; i
s.append( " " );
}
private static Pattern[] ESCAPE_PATTERNS = new Pattern[]
{
Pattern.compile( "\\\\" ), Pattern.compile( "\\n" ), Pattern.compile( "\\r" ), Pattern.compile( "\\t" ), Pattern.compile( "\\f" ), Pattern.compile( "\\\"" )
};
private static String[] ESCAPE_REPLACEMENTS = new String[]
{
Matcher.quoteReplacement( "\\\\" ), Matcher.quoteReplacement( "\\n" ), Matcher.quoteReplacement( "\\r" ), Matcher.quoteReplacement( "\\t" ), Matcher.quoteReplacement( "\\f" ), Matcher.quoteReplacement( "\\\"" )
};
private static String escape( String string )
{
for( int i = 0, length = ESCAPE_PATTERNS.length; i < length; i++ )
string = ESCAPE_PATTERNS[i].matcher( string ).replaceAll( ESCAPE_REPLACEMENTS[i] );
return string;
}
} |
package org.intermine.api.bag;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.intermine.InterMineException;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.query.MainHelper;
import org.intermine.api.template.TemplateQuery;
import org.intermine.model.InterMineObject;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.Results;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.OrderElement;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathConstraint;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
/**
* Static helper routines to convert bags between different types.
*
* @author Matthew Wakeling
* @author Richard Smith
*/
public final class TypeConverter
{
private TypeConverter() {
}
/**
* Converts a List of objects from one type to another type using a TemplateQuery,
* returns a map from an original object to the converted object(s).
*
* @param conversionTemplates a list of templates to be used for conversion
* @param typeA the type to convert from
* @param typeB the type to convert to
* @param bagOrIds an InterMineBag or Collection of Integer object ids
* @param os the ObjectStore to execute queries in
* @return a Map from original object to a List of converted objects, or null if conversion is
* possible (because no suitable template is available)
* @throws InterMineException if an error occurs
*/
public static Map<InterMineObject, List<InterMineObject>>
getConvertedObjectMap(List<TemplateQuery> conversionTemplates, Class<?> typeA, Class<?> typeB,
Object bagOrIds, ObjectStore os) throws InterMineException {
PathQuery pq = getConversionMapQuery(conversionTemplates, typeA, typeB, bagOrIds);
Map<String, InterMineBag> savedBags = new HashMap<String, InterMineBag>();
if (bagOrIds instanceof InterMineBag) {
InterMineBag bag = (InterMineBag) bagOrIds;
savedBags.put(bag.getName(), bag);
}
if (pq == null) {
return null;
}
Query q;
try {
// we can call without a BagQueryRunner as a valid conversion query can't contain
// LOOKUP constraints.
q = MainHelper.makeQuery(pq, savedBags, null, null, null);
} catch (ObjectStoreException e) {
throw new InterMineException(e);
}
Results r;
Map<InterMineObject, List<InterMineObject>> retval =
new HashMap<InterMineObject, List<InterMineObject>>();
r = os.execute(q);
Iterator iter = r.iterator();
while (iter.hasNext()) {
List row = (List) iter.next();
InterMineObject orig = (InterMineObject) row.get(0);
InterMineObject derived = (InterMineObject) row.get(1);
List<InterMineObject> ders = retval.get(orig);
if (ders == null) {
ders = new ArrayList<InterMineObject>();
retval.put(orig, ders);
}
ders.add(derived);
}
return retval;
}
/**
* Get conversion query for the types provided, edited so that the first
* type is constrained to be in the bag.
*
* @param conversionTemplates a list of templates to be used for conversion
* @param typeA the type to convert from
* @param typeB the type to convert to
* @param bagOrIds an InterMineBag or Collection of Integer object ids
* @return a PathQuery that finds a conversion mapping for the given bag
*/
public static PathQuery getConversionMapQuery(List<TemplateQuery> conversionTemplates,
Class typeA, Class typeB, Object bagOrIds) {
TemplateQuery tq = getConversionTemplates(conversionTemplates, typeA).get(typeB);
if (tq == null) {
return null;
}
tq = tq.clone();
// We can be reckless here because all this is checked by getConversionTemplate
String node = tq.getEditablePaths().iterator().next();
PathConstraint c = tq.getEditableConstraints(node).iterator().next();
// This is a MAJOR hack - we assume that the constraint is on an ATTRIBUTE of the node we
// want to constrain.
try {
String parent = tq.makePath(node).getPrefix().getNoConstraintsString();
if (bagOrIds instanceof InterMineBag) {
InterMineBag bag = (InterMineBag) bagOrIds;
tq.replaceConstraint(c, Constraints.in(parent, bag.getName()));
} else if (bagOrIds instanceof Collection) {
Collection<Integer> ids = (Collection<Integer>) bagOrIds;
tq.replaceConstraint(c, Constraints.inIds(parent, ids));
}
return tq;
} catch (PathException e) {
throw new RuntimeException("Template is invalid", e);
}
}
/**
* Get conversion query for the types provided, edited so that the first
* type is constrained to be in the bag and the first type is removed from the
* view list so that the query only returns the converted type.
*
* @param conversionTemplates a list of templates to be used for conversion
* @param typeA the type to convert from
* @param typeB the type to convert to
* @param bagOrIds an InterMineBag or Collection of Integer object identifiers
* @return a PathQuery that finds converted objects for the given bag
*/
public static PathQuery getConversionQuery(List<TemplateQuery> conversionTemplates,
Class<?> typeA, Class<?> typeB, Object bagOrIds) {
PathQuery pq = getConversionMapQuery(conversionTemplates, typeA, typeB, bagOrIds);
if (pq == null) {
return null;
}
// remove typeA from the output
try {
List<String> view = pq.getView();
for (String viewElement : view) {
Path path = pq.makePath(viewElement);
if (path.getLastClassDescriptor().getType().equals(typeA)) {
pq.removeView(viewElement);
for (OrderElement orderBy : pq.getOrderBy()) {
if (orderBy.getOrderPath().equals(viewElement)) {
pq.removeOrderBy(viewElement);
}
}
}
}
return pq;
} catch (PathException e) {
throw new RuntimeException("Template is invalid", e);
}
}
/**
* Return a Map from typeB to a TemplateQuery that will convert from typeA to typeB.
*
* @param conversionTemplates a list of templates to be used for conversion
* @param typeA the type to convert from
* @return a Map from Class to TemplateQuery
*/
public static Map<Class, TemplateQuery> getConversionTemplates(
List<TemplateQuery> conversionTemplates, Class typeA) {
try {
Map<Class, TemplateQuery> retval = new HashMap();
for (TemplateQuery tq : conversionTemplates) {
// Find conversion types
List<String> view = tq.getView();
if (view.size() == 2) {
// Correct number of SELECT list items
Path select1 = tq.makePath(view.get(0));
Class tqTypeA = select1.getLastClassDescriptor().getType();
if (tqTypeA.isAssignableFrom(typeA)) {
// Correct typeA in SELECT list. Now check for editable constraint.
if ((tq.getEditableConstraints(select1.toStringNoConstraints()).size() == 1)
&& (tq.getEditableConstraints().size() == 1)) {
// Editable constraint is okay.
Class typeB = tq.makePath(view.get(1)).getLastClassDescriptor()
.getType();
TemplateQuery prevTq = retval.get(typeB);
if (prevTq != null) {
Class prevTypeA = prevTq.makePath(prevTq.getView().get(0))
.getLastClassDescriptor().getType();
if (prevTypeA.isAssignableFrom(tqTypeA)) {
// This tq is more specific
retval.put(typeB, tq);
}
} else {
retval.put(typeB, tq);
}
}
}
}
}
return retval;
} catch (PathException e) {
throw new RuntimeException("Template is invalid", e);
}
}
} |
package jadx.core.dex.visitors;
import java.util.ArrayList;
import java.util.List;
import jadx.core.codegen.TypeGen;
import jadx.core.deobf.NameMapper;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.nodes.EnumClassAttr;
import jadx.core.dex.attributes.nodes.EnumClassAttr.EnumField;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.DexNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.ErrorsCounter;
import jadx.core.utils.InsnUtils;
import jadx.core.utils.exceptions.JadxException;
import org.jetbrains.annotations.Nullable;
@JadxVisitor(
name = "EnumVisitor",
desc = "Restore enum classes",
runAfter = {CodeShrinker.class, ModVisitor.class}
)
public class EnumVisitor extends AbstractVisitor {
@Override
public boolean visit(ClassNode cls) throws JadxException {
if (!cls.isEnum()) {
return true;
}
// search class init method
MethodNode staticMethod = null;
for (MethodNode mth : cls.getMethods()) {
MethodInfo mi = mth.getMethodInfo();
if (mi.isClassInit()) {
staticMethod = mth;
break;
}
}
if (staticMethod == null) {
ErrorsCounter.classError(cls, "Enum class init method not found");
return true;
}
ArgType clsType = cls.getClassInfo().getType();
String enumConstructor = "<init>(Ljava/lang/String;I)V";
// TODO: detect these methods by analyzing method instructions
String valuesOfMethod = "valueOf(Ljava/lang/String;)" + TypeGen.signature(clsType);
String valuesMethod = "values()" + TypeGen.signature(ArgType.array(clsType));
// collect enum fields, remove synthetic
List<FieldNode> enumFields = new ArrayList<>();
for (FieldNode f : cls.getFields()) {
if (f.getAccessFlags().isEnum()) {
enumFields.add(f);
f.add(AFlag.DONT_GENERATE);
} else if (f.getAccessFlags().isSynthetic()) {
f.add(AFlag.DONT_GENERATE);
}
}
// remove synthetic methods
for (MethodNode mth : cls.getMethods()) {
MethodInfo mi = mth.getMethodInfo();
if (mi.isClassInit()) {
continue;
}
String shortId = mi.getShortId();
boolean isSynthetic = mth.getAccessFlags().isSynthetic();
if (mi.isConstructor() && !isSynthetic) {
if (shortId.equals(enumConstructor)) {
mth.add(AFlag.DONT_GENERATE);
}
} else if (isSynthetic
|| shortId.equals(valuesMethod)
|| shortId.equals(valuesOfMethod)) {
mth.add(AFlag.DONT_GENERATE);
}
}
EnumClassAttr attr = new EnumClassAttr(enumFields.size());
cls.addAttr(attr);
attr.setStaticMethod(staticMethod);
ClassInfo classInfo = cls.getClassInfo();
// move enum specific instruction from static method to separate list
BlockNode staticBlock = staticMethod.getBasicBlocks().get(0);
List<InsnNode> enumPutInsns = new ArrayList<>();
List<InsnNode> list = staticBlock.getInstructions();
int size = list.size();
for (int i = 0; i < size; i++) {
InsnNode insn = list.get(i);
if (insn.getType() != InsnType.SPUT) {
continue;
}
FieldInfo f = (FieldInfo) ((IndexInsnNode) insn).getIndex();
if (!f.getDeclClass().equals(classInfo)) {
continue;
}
FieldNode fieldNode = cls.searchField(f);
if (fieldNode != null && isEnumArrayField(classInfo, fieldNode)) {
if (i == size - 1) {
staticMethod.add(AFlag.DONT_GENERATE);
} else {
list.subList(0, i + 1).clear();
}
break;
} else {
enumPutInsns.add(insn);
}
}
for (InsnNode putInsn : enumPutInsns) {
ConstructorInsn co = getConstructorInsn(putInsn);
if (co == null || co.getArgsCount() < 2) {
continue;
}
ClassInfo clsInfo = co.getClassType();
ClassNode constrCls = cls.dex().resolveClass(clsInfo);
if (constrCls == null) {
continue;
}
if (!clsInfo.equals(classInfo) && !constrCls.getAccessFlags().isEnum()) {
continue;
}
FieldInfo fieldInfo = (FieldInfo) ((IndexInsnNode) putInsn).getIndex();
String name = getConstString(cls.dex(), co.getArg(0));
if (name != null
&& !fieldInfo.getAlias().equals(name)
&& NameMapper.isValidIdentifier(name)) {
// LOG.debug("Rename enum field: '{}' to '{}' in {}", fieldInfo.getName(), name, cls);
fieldInfo.setAlias(name);
}
EnumField field = new EnumField(fieldInfo, co, 2);
attr.getFields().add(field);
if (!co.getClassType().equals(classInfo)) {
// enum contains additional methods
for (ClassNode innerCls : cls.getInnerClasses()) {
processEnumInnerCls(co, field, innerCls);
}
}
}
return false;
}
private static void processEnumInnerCls(ConstructorInsn co, EnumField field, ClassNode innerCls) {
if (!innerCls.getClassInfo().equals(co.getClassType())) {
return;
}
// remove constructor, because it is anonymous class
for (MethodNode innerMth : innerCls.getMethods()) {
if (innerMth.getAccessFlags().isConstructor()) {
innerMth.add(AFlag.DONT_GENERATE);
}
}
field.setCls(innerCls);
innerCls.add(AFlag.DONT_GENERATE);
}
private boolean isEnumArrayField(ClassInfo classInfo, FieldNode fieldNode) {
if (fieldNode.getAccessFlags().isSynthetic()) {
ArgType fType = fieldNode.getType();
return fType.isArray() && fType.getArrayRootElement().equals(classInfo.getType());
}
return false;
}
private ConstructorInsn getConstructorInsn(InsnNode putInsn) {
if (putInsn.getArgsCount() != 1) {
return null;
}
InsnArg arg = putInsn.getArg(0);
if (arg.isInsnWrap()) {
return castConstructorInsn(((InsnWrapArg) arg).getWrapInsn());
}
if (arg.isRegister()) {
return castConstructorInsn(((RegisterArg) arg).getAssignInsn());
}
return null;
}
@Nullable
private ConstructorInsn castConstructorInsn(InsnNode coCandidate) {
if (coCandidate != null && coCandidate.getType() == InsnType.CONSTRUCTOR) {
return (ConstructorInsn) coCandidate;
}
return null;
}
private String getConstString(DexNode dex, InsnArg arg) {
if (arg.isInsnWrap()) {
InsnNode constInsn = ((InsnWrapArg) arg).getWrapInsn();
Object constValue = InsnUtils.getConstValueByInsn(dex, constInsn);
if (constValue instanceof String) {
return (String) constValue;
}
}
return null;
}
} |
package com.example.rest.config;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
@Configuration
public class RestConfig {
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
return new Jackson2ObjectMapperBuilder()
.indentOutput(true)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
}
@Bean
public CustomEditorConfigurer customEditorConfigurer(PropertyEditorRegistrar propertyEditorRegistrar) {
CustomEditorConfigurer ret = new CustomEditorConfigurer();
ret.setPropertyEditorRegistrars(new PropertyEditorRegistrar[]{propertyEditorRegistrar});
return ret;
}
@Bean
public PropertyEditorRegistrar propertyEditorRegistrar() {
return r -> {
r.registerCustomEditor(LocalDateTime.class, new LocalDateTimePropertyEditor());
};
}
} |
package com.google.devtools.moe.client.project;
import com.google.devtools.moe.client.Injector;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Configuration for a scrubber.
*/
public class ScrubberConfig {
// General options
@SerializedName("ignore_files_re")
private String ignoreFilesRe;
@SerializedName("do_not_scrub_files_re")
private String doNotScrubFilesRe;
@SerializedName("extension_map")
private JsonArray extensionMap;
@SerializedName("sensitive_string_file")
private String sensitiveStringFile;
@SerializedName("sensitive_words")
private List<String> sensitiveWords;
@SerializedName("sensitive_res")
private List<String> sensitiveRes;
private List<JsonObject> whitelist;
@SerializedName("scrub_sensitive_comments")
private boolean scrubSensitiveComments = true;
@SerializedName("rearranging_config")
private JsonObject rearrangingConfig;
@SerializedName("string_replacements")
private List<Map<String, String>> stringReplacements;
@SerializedName("regex_replacements")
private List<Map<String, String>> regexReplacements;
@SerializedName("scrub_non_documentation_comments")
private boolean scrubNonDocumentationComments;
@SerializedName("scrub_all_comments")
private boolean scrubAllComments;
// User options
@SerializedName("usernames_to_scrub")
private final List<String> usernamesToScrub = new ArrayList<>();
@SerializedName("usernames_to_publish")
private final List<String> usernamesToPublish = new ArrayList<>();
@SerializedName("usernames_file")
private String usernamesFile;
@SerializedName("scrub_unknown_users")
private boolean scrubUnknownUsers;
@SerializedName("scrub_authors")
private boolean scrubAuthors = true;
// C/C++ options
@SerializedName("c_includes_config_file")
private String cIncludesConfigFile;
@SerializedName("c_includes_config")
private JsonObject cIncludesConfig;
// Java options
@SerializedName("empty_java_file_action")
private String emptyJavaFileAction;
@SerializedName("maximum_blank_lines")
private int maximumBlankLines;
@SerializedName("scrub_java_testsize_annotations")
private boolean scrubJavaTestsizeAnnotations;
@SerializedName("java_renames")
private List<Map<String, String>> javaRenames;
// JavaScript options
@SerializedName("js_directory_rename")
private Map<String, String> jsDirectoryRename;
@SerializedName("js_directory_renames")
private List<Map<String, String>> jsDirectoryRenames;
// Python options
@SerializedName("python_module_renames")
private List<JsonObject> pythonModuleRenames;
@SerializedName("python_module_removes")
private List<JsonObject> pythonModuleRemoves;
@SerializedName("python_shebang_replace")
private JsonObject pythonShebangReplace;
// GWT options
@SerializedName("scrub_gwt_inherits")
private List<String> scrubGwtInherits;
// proto options
@SerializedName("scrub_proto_comments")
private boolean scrubProtoComments;
private ScrubberConfig() { // Instantiated by GSON.
}
/**
* @param author Author in the format "Name <username@domain>".
*/
public boolean shouldScrubAuthor(String author) throws InvalidProject {
if (!scrubAuthors) {
return false;
}
// TODO(cgruber): Create a custom deserializer that does this logic once, on deserialization.
if (usernamesFile != null) {
try {
UsernamesConfig usernamesConfig =
ProjectConfig.makeGson()
.fromJson(
Injector.INSTANCE.fileSystem().fileToString(new File(usernamesFile)),
UsernamesConfig.class);
addUsernames(usernamesToScrub, usernamesConfig.getScrubbableUsernames());
addUsernames(usernamesToPublish, usernamesConfig.getPublishableUsernames());
} catch (IOException exception) {
throw new InvalidProject(
"File " + usernamesFile + " referenced by usernames_file not found.");
}
usernamesFile = null;
}
return scrubUnknownUsers
? !matchesUsername(author, usernamesToPublish)
: matchesUsername(author, usernamesToScrub);
}
private void addUsernames(List<String> local, List<String> global) {
if (global != null) {
for (String username : global) {
if (!local.contains(username)) {
local.add(username);
}
}
}
}
// TODO(cgruber): Parse out the actual usernames in a custom deserializer.
private boolean matchesUsername(String author, List<String> usernames) {
if (usernames != null) {
for (String username : usernames) {
if (author.matches(".*<" + Pattern.quote(username) + "@.*")) {
return true;
}
}
}
return false;
}
} |
package ohmdb.client;
public class OhmConstants {
public static final int DEFAULT_INIT_SCAN = 100;
public static final int MAX_REQUEST_SIZE = 1000000;
public static final long FLUSH_PERIOD = 30000;
public static final int AMOUNT_OF_FLUSH_PER_COMPACT = 10;
public static final int MSG_SIZE = 100;
public static final int DEFAULT_PORT = 8080;
public static int TEST_PORT = 8080;
public static int MAX_CACHE_SZ = MAX_REQUEST_SIZE * 2;
public static final String LOG_NAME = "log";
public static final String WAL_DIR = "wal";
public static final String ARCHIVE_DIR = "old_wal";
public static final String TMP_DIR = "/tmp";
} |
package org.folio.okapi;
import com.hazelcast.config.Config;
import com.hazelcast.config.ClasspathXmlConfig;
import com.hazelcast.config.FileSystemXmlConfig;
import com.hazelcast.config.InterfacesConfig;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.config.UrlXmlConfig;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Handler;
import io.vertx.core.Verticle;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager;
import java.util.concurrent.TimeUnit;
import static java.lang.System.*;
import static java.lang.Integer.*;
import static org.folio.okapi.common.ErrorType.*;
import org.folio.okapi.common.ExtendedAsyncResult;
import org.folio.okapi.common.Failure;
import org.folio.okapi.common.Success;
import org.folio.okapi.util.DropwizardHelper;
public class MainCluster {
private static final String CANNOT_LOAD_STR = "Cannot load ";
private MainCluster() {
throw new IllegalAccessError("MainCluster");
}
public static void main(String[] args) {
final Logger logger = LoggerFactory.getLogger("okapi");
main1(args, res -> {
if (res.failed()) {
logger.error(res.cause());
exit(1);
}
});
}
public static void main1(String[] args, Handler<ExtendedAsyncResult<Vertx>> fut) {
setProperty("vertx.logger-delegate-factory-class-name",
"io.vertx.core.logging.SLF4JLogDelegateFactory");
final Logger logger = LoggerFactory.getLogger("okapi");
if (args.length < 1) {
fut.handle(new Failure<>(USER, "Missing command; use help"));
return;
}
VertxOptions vopt = new VertxOptions();
Config hConfig = null;
JsonObject conf = new JsonObject();
String clusterHost = null;
int clusterPort = -1;
int i = 0;
while (i < args.length) {
if (!args[i].startsWith("-")) {
if ("help".equals(args[i])) {
out.println("Usage: command [options]\n"
+ "Commands:\n"
+ " help Display help\n"
+ " cluster Run in clustered mode\n"
+ " dev Development mode\n"
+ " deployment Deployment only. Clustered mode\n"
+ " proxy Proxy + discovery. Clustered mode\n"
+ "Options:\n"
+ " -hazelcast-config-cp file Read config from class path\n"
+ " -hazelcast-config-file file Read config from local file\n"
+ " -hazelcast-config-url url Read config from URL\n"
+ " -cluster-host ip Vertx cluster host\n"
+ " -cluster-port port Vertx cluster port\n"
+ " -enable-metrics\n"
);
exit(0);
}
conf.put("mode", args[i]);
} else if ("-hazelcast-config-cp".equals(args[i]) && i < args.length - 1) {
i++;
String resource = args[i];
try {
hConfig = new ClasspathXmlConfig(resource);
} catch (Exception e) {
fut.handle(new Failure<>(USER, CANNOT_LOAD_STR + resource + ": " + e));
return;
}
} else if ("-hazelcast-config-file".equals(args[i]) && i < args.length - 1) {
i++;
String resource = args[i];
try {
hConfig = new FileSystemXmlConfig(resource);
} catch (Exception e) {
fut.handle(new Failure<>(USER, CANNOT_LOAD_STR + resource + ": " + e));
return;
}
} else if ("-hazelcast-config-url".equals(args[i]) && i < args.length - 1) {
i++;
String resource = args[i];
try {
hConfig = new UrlXmlConfig(resource);
} catch (Exception e) {
fut.handle(new Failure<>(USER, CANNOT_LOAD_STR + resource + ": " + e));
return;
}
} else if ("-cluster-host".equals(args[i]) && i < args.length - 1) {
i++;
clusterHost = args[i];
} else if ("-cluster-port".equals(args[i]) && i < args.length - 1) {
i++;
clusterPort = Integer.parseInt(args[i]);
} else if ("-enable-metrics".equals(args[i])) {
i++;
final String graphiteHost = getProperty("graphiteHost", "localhost");
final Integer graphitePort = parseInt(
getProperty("graphitePort", "2003"));
final TimeUnit tu = TimeUnit.valueOf(getProperty("reporterTimeUnit", "SECONDS"));
final Integer reporterPeriod = parseInt(getProperty("reporterPeriod", "1"));
final String hostName = getProperty("host", "localhost");
DropwizardHelper.config(graphiteHost, graphitePort, tu, reporterPeriod, vopt, hostName);
} else {
fut.handle(new Failure<>(USER, "Invalid option: " + args[i]));
return;
}
i++;
}
final String mode = conf.getString("mode", "dev");
switch (mode) {
case "dev":
case "initdatabase":
case "purgedatabase":
deploy(new MainVerticle(), conf, Vertx.vertx(vopt), fut);
break;
case "cluster":
case "proxy":
case "deployment":
if (hConfig == null) {
hConfig = new Config();
if (clusterHost != null) {
NetworkConfig network = hConfig.getNetworkConfig();
InterfacesConfig iFace = network.getInterfaces();
iFace.setEnabled(true).addInterface(clusterHost);
}
}
hConfig.setProperty("hazelcast.logging.type", "slf4j");
HazelcastClusterManager mgr = new HazelcastClusterManager(hConfig);
vopt.setClusterManager(mgr);
if (clusterHost != null) {
logger.info("clusterHost=" + clusterHost);
vopt.setClusterHost(clusterHost);
} else {
logger.warn("clusterHost not set");
}
if (clusterPort != -1) {
logger.info("clusterPort=" + clusterPort);
vopt.setClusterPort(clusterPort);
} else {
logger.warn("clusterPort not set");
}
vopt.setClustered(true);
Vertx.clusteredVertx(vopt, res -> {
if (res.succeeded()) {
MainVerticle v = new MainVerticle();
v.setClusterManager(mgr);
deploy(v, conf, res.result(), fut);
} else {
fut.handle(new Failure<>(USER, res.cause()));
}
});
break;
default:
fut.handle(new Failure<>(USER, "Unknown command '" + mode + "'"));
return;
}
}
private static void deploy(Verticle v, JsonObject conf, Vertx vertx, Handler<ExtendedAsyncResult<Vertx>> fut) {
DeploymentOptions opt = new DeploymentOptions().setConfig(conf);
vertx.deployVerticle(v, opt, dep -> {
if (dep.failed()) {
fut.handle(new Failure<>(INTERNAL, dep.cause()));
} else {
fut.handle(new Success<>(vertx));
}
});
}
} |
package org.gem.engine.hazard.parsers.crisis;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import org.gem.engine.hazard.parsers.GemFileParser;
import org.opensha.commons.calc.GaussianDistCalc;
import org.opensha.commons.geo.Location;
import org.opensha.commons.geo.LocationList;
import org.opensha.commons.data.function.ArbitrarilyDiscretizedFunc;
import org.opensha.commons.geo.Region;
import org.opensha.sha.earthquake.FocalMechanism;
import org.opensha.sha.earthquake.griddedForecast.MagFreqDistsForFocalMechs;
import org.opensha.sha.earthquake.rupForecastImpl.GEM1.SourceData.GEMAreaSourceData;
import org.opensha.sha.earthquake.rupForecastImpl.GEM1.SourceData.GEMSourceData;
import org.opensha.sha.earthquake.rupForecastImpl.GEM1.SourceData.GEMSubductionFaultSourceData;
import org.opensha.sha.faultSurface.FaultTrace;
import org.opensha.sha.magdist.IncrementalMagFreqDist;
import org.opensha.sha.util.TectonicRegionType;
/**
* <b>Title:</b> InputFileParser
* <p>
*
* <b>Description:</b> This class extends the GemInput Parser class. It parses a
* Crisis input file and creates a list of GemSourceData objects.
* <p>
* Note that Crisis can associate distinct GMPE to distinct seismic sources of
* the same input.
*
* @author M.M. Pagani
* @created 2010-03-01
* @version 1.0
*/
public class CrisisSourceData extends GemFileParser {
private static boolean INFO = false;
private static double MMIN = 5.0;
private static double MWDT = 0.1;
private static boolean USEDIPPINGAREAS = true;
private static boolean USEAREASOURCES = true;
/**
*
* @param file
*/
public CrisisSourceData(BufferedReader input) {
ArrayList<GEMSourceData> srcList = new ArrayList<GEMSourceData>();
int subSrcCounter = 0;
// Reading the file
try {
// Instantiate a BufferedReader
// BufferedReader input = new BufferedReader(file);
try {
// Reading the header
InputFileHeader head = new InputFileHeader(input);
// Reading sources
for (int i = 0; i < head.nRegions; i++) {
InputFileSource tmpsrc = new InputFileSource(input);
if (INFO) {
System.out
.println("=====================================================");
System.out.printf("Reading source # %d \n", i);
System.out.printf(" name: %s \n", tmpsrc.getName());
}
// Crisis "Poisson" model
String name = tmpsrc.getName();
LocationList locList = new LocationList();
// Hash map with depths
HashMap<Double, Integer> depthMap =
new HashMap<Double, Integer>();
for (int j = 0; j < tmpsrc.getCoords().length; j++) {
// Add the location to the list
locList.add(new Location(tmpsrc.getCoords()[j][1],
tmpsrc.getCoords()[j][0]));
// This is a hash map used to identify the number and
// values of depths
// used to specify the source
if (depthMap.containsKey(tmpsrc.getDepth())) {
depthMap.put(tmpsrc.getDepth()[j],
depthMap.get(tmpsrc.getDepth()) + 1);
} else {
depthMap.put(tmpsrc.getDepth()[j], 1);
}
}
// Check how many depths were used
if (INFO) {
System.out.println(" Number of depths: "
+ depthMap.keySet().size());
Iterator<Double> iterator =
depthMap.keySet().iterator();
while (iterator.hasNext()) {
System.out.println(" Depth: " + iterator.next());
}
}
// Creating the mfd distribution
IncrementalMagFreqDist mfd = null;
if (tmpsrc.getOccMod() == 1) {
if (INFO)
System.out.printf(" mmax: %.2f \n",
tmpsrc.getMuUn());
double tmpMM =
Math.ceil(tmpsrc.getMuUn() / MWDT) * MWDT;
if (INFO)
System.out.printf(" recomputed mmax: %.2f\n",
tmpMM);
// Crisis Double truncated GR
int num = (int) Math.round((tmpMM - MMIN) / MWDT);
mfd =
new IncrementalMagFreqDist(MMIN + MWDT / 2,
tmpMM - MWDT / 2, num);
double mup = MMIN + MWDT;
double betaGR = tmpsrc.getBetaGR();
double alphaGR =
Math.log(tmpsrc.getOccRate()
/ (Math.exp(-betaGR * tmpsrc.getMmin()) - Math
.exp(-betaGR * tmpMM)));
int idx = 0;
while (mup <= tmpMM + MWDT * 0.1) {
double occ =
Math.exp(alphaGR - betaGR * (mup - MWDT))
- Math.exp(alphaGR - betaGR * mup);
mup += MWDT;
mfd.add(idx, occ);
idx++;
}
if (INFO) {
for (int j = 0; j < mfd.getNum(); j++) {
System.out.printf(" %5.2f %7.5f \n",
mfd.getX(j), mfd.getY(j));
}
}
} else if (tmpsrc.getOccMod() == 2) {
// Crisis Characteristic model
double roundMMin =
Math.floor(tmpsrc.getMCharMin() / MWDT) * MWDT;
double roundMMax =
Math.ceil(tmpsrc.getMCharMax() / MWDT) * MWDT;
int num =
(int) Math
.round((roundMMax - roundMMin) / MWDT);
// mfd = new IncrementalMagFreqDist(roundMMin+MWDT/2,
// roundMMax-MWDT/2,num);
mfd =
new IncrementalMagFreqDist(
roundMMin + MWDT / 2, num, MWDT);
int idx = 0;
// This is the denominator to be used to compute
// occurrences
double den =
GaussianDistCalc
.getCDF((tmpsrc.getMCharMax() - tmpsrc
.getMCharExp())
/ tmpsrc.getSigmaMChar())
- GaussianDistCalc.getCDF((tmpsrc
.getMCharMin() - tmpsrc
.getMCharExp())
/ tmpsrc.getSigmaMChar());
double mmin, mmax;
// Expected MChar
double mexp = tmpsrc.getMCharExp();
// Sigma
double sigma = tmpsrc.getSigmaMChar();
double soc = 0.0;
double mup = roundMMin + MWDT;
while (mup <= roundMMax - MWDT / 2) {
mmin = mup - MWDT;
if (idx == 1) {
mmin = tmpsrc.getMCharMin();
}
double occ =
1.
/ tmpsrc.getMedianRate()
* ((GaussianDistCalc
.getCDF((mup - mexp)
/ sigma)) - (GaussianDistCalc
.getCDF((mmin - mexp)
/ sigma))) / den;
if (INFO)
System.out.printf(
"%5.2f %5.2f %5.2f: %8.5f %8.5f\n",
mmin, mup, den, mup - MWDT / 2, occ);
mup += MWDT;
soc += occ;
mfd.add(idx, occ);
idx++;
}
if (INFO)
System.out
.printf(" sum of occ: %7.4f (original rate: %7.4f)\n",
soc, 1. / tmpsrc.getMedianRate());
} else {
// To do throw an exception
System.err
.println("Occorrence/mfd model: unsupported option");
throw new RuntimeException("");
}
// if (INFO) {
// System.out.println("MFD");
// for (int w= 0; w < mfd.getNum(); w++){
// System.out.printf(" mag: %5.2f rte: %6.3e\n",mfd.getX(w),mfd.getY(w));
// MFD for focal mechanism
FocalMechanism fm = new FocalMechanism();
fm.setStrike(0.0);
fm.setDip(90.0);
fm.setRake(0.0);
IncrementalMagFreqDist[] arrMfd =
new IncrementalMagFreqDist[1];
arrMfd[0] = mfd;
FocalMechanism[] arrFm = new FocalMechanism[1];
arrFm[0] = fm;
MagFreqDistsForFocalMechs mfdffm =
new MagFreqDistsForFocalMechs(arrMfd, arrFm);
// Top of rupture
ArbitrarilyDiscretizedFunc depTopRup =
new ArbitrarilyDiscretizedFunc();
double depth = (Double) depthMap.keySet().toArray()[0];
depTopRup.set(MMIN, depth);
if (depthMap.keySet().size() == 1) {
if (USEAREASOURCES) {
// Instantiate the region
Region reg = new Region(locList, null);
// Shallow active tectonic sources
GEMAreaSourceData src =
new GEMAreaSourceData("0", name,
TectonicRegionType.ACTIVE_SHALLOW,
reg, mfdffm, depTopRup, depth);
srcList.add(src);
}
} else if (depthMap.keySet().size() == 2) {
if (USEDIPPINGAREAS) {
// Fault trace
FaultTrace upperTrace = new FaultTrace("");
double upperDepth = -1.0;
FaultTrace lowerTrace = new FaultTrace("");
double lowerDepth = -1.0;
// Create a list with depths (depths ordered in
// increasing order)
ArrayList<Double> depList = new ArrayList<Double>();
for (double dep : depthMap.keySet()) {
depList.add(dep);
}
Collections.sort(depList);
upperDepth = depList.get(0);
lowerDepth = depList.get(1);
// Create the upper and lower traces
for (int j = 0; j < tmpsrc.getCoords().length; j++) {
if (Math.abs(tmpsrc.getDepth()[j] - upperDepth) < 1e-1) {
upperTrace.add(new Location(tmpsrc
.getCoords()[j][1], tmpsrc
.getCoords()[j][0], upperDepth));
} else {
lowerTrace.add(new Location(tmpsrc
.getCoords()[j][1], tmpsrc
.getCoords()[j][0], lowerDepth));
}
}
// Find the directions of the two traces and -
// eventually - revert one trace
if (Math.abs(upperTrace
.getStrikeDirectionDifference(lowerTrace)) > 90.0) {
lowerTrace.reverse();
}
// Fix the rake ???????????????????????????
double rake = 90.0;
// Do some checks
if (upperTrace.getTraceLength() < 1e-2) {
// To do throw an exception
System.err
.println("Upper trace lenght equal to 0");
throw new RuntimeException("");
}
// Do some checks
if (lowerTrace.getTraceLength() < 1e-2) {
// To do throw an exception
System.err
.println("Lower trace lenght equal to 0");
throw new RuntimeException("");
}
// Information
if (INFO) {
System.out
.println("
System.out.println(" Name: " + name);
System.out.println(" Upper trace: ");
// LocationList loclUP = new LocationList();
// for (int w=0; w<upperTrace.size(); w++){
// loclUP.add(upperTrace.getLocationAt(w));
// for (Location loc : loclUP){
// System.out.printf(" %6.2f %6.2f %5.1f\n",
// loc.getLongitude(),loc.getLatitude(),loc.getDepth());
// System.out.println(" Lower trace: ");
// for (Location loc :
// lowerTrace.getLocationList){
// System.out.printf(" %6.2f %6.2f %5.2f\n",
// loc.getLongitude(),loc.getLatitude(),loc.getDepth());
}
// Subduction source
GEMSubductionFaultSourceData src =
new GEMSubductionFaultSourceData(
String.format("%d", subSrcCounter),
name,
TectonicRegionType.SUBDUCTION_INTERFACE,
upperTrace, lowerTrace, rake, mfd,
true);
//srcList.add(src);
if (INFO)
System.out
.println("Adding subduction ========== "
+ name);
subSrcCounter++;
}
} else {
// To do throw an exception
System.err
.println("Source geometry: unsupported option");
throw new RuntimeException("");
}
}
} finally {
input.close();
this.setList(srcList);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
} |
package VASSAL.build.module;
import VASSAL.Info;
import VASSAL.build.GameModule;
import VASSAL.build.module.properties.MutableProperty;
import VASSAL.command.Logger;
import VASSAL.counters.GamePiece;
import VASSAL.counters.KeyBuffer;
import VASSAL.tools.BugUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.LoggerFactory;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
/**
* Expandable "Console" to allow entering commands into the Chatter.
*/
public class Console {
Iterator<String> tok;
String commandLine;
int commandIndex = 0;
List<String> commands = new ArrayList<>();
private static final org.slf4j.Logger log =
LoggerFactory.getLogger(Console.class);
private void show(String s) {
GameModule.getGameModule().warn(s);
}
private boolean matches(String s1, String s2) {
return matches(s1, s2, 2);
}
private boolean matches(String s1, String s2, int min) {
if (s2.isEmpty() || (s2.length() > s1.length()) || ((s2.length() < min) && (s1.length() > s2.length()))) {
return false;
}
if (s2.length() < min) {
return s1.equalsIgnoreCase(s2);
}
return s1.substring(0, s2.length()).equalsIgnoreCase(s2);
}
private String nextString(String def) {
return tok.hasNext() ? tok.next() : def;
}
private int nextInt(int def) {
try {
return tok.hasNext() ? Integer.parseInt(tok.next()) : def;
}
catch (NumberFormatException e) {
return def;
}
}
/**
* Opens the specified file (or folder) using the Desktop's default method
* @param file file or folder to open
*/
private void browseFileOrFolder(File file) {
final Desktop desktop = Desktop.getDesktop();
try {
desktop.open(file);
}
catch (IOException e) {
log.error("File Not Found", e); //NON-NLS
}
catch (IllegalArgumentException iae) {
log.error("Illegal argument", iae); //NON-NLS
}
}
private boolean doErrorLog() {
final String option = nextString("");
if (matches("show", option)) { //NON-NLS
final String errorLog = BugUtils.getErrorLog();
final String delims2 = "[\n]+";
final String[] lines = errorLog.split(delims2);
if (lines.length > 0) {
final int end = lines.length - 1;
final int linesToShow = nextInt(0);
final int start = (linesToShow <= 0) ? 0 : Math.max(0, end - linesToShow + 1);
for (int line = start; line <= end; line++) {
show(lines[line]);
}
}
}
else if (matches("write", option)) { //NON-NLS
final int where = commandLine.toLowerCase().indexOf("write"); //NON-NLS
if ((where > 0) && commandLine.length() > where + 6) {
log.info(commandLine.substring(where + 6));
}
}
else if (matches("folder", option)) { //NON-NLS
browseFileOrFolder(Info.getConfDir());
}
else if (matches("noecho", option)) { //NON-NLS
GameModule.setErrorLogToChat(false);
show("Errorlog Echo: OFF"); //NON-NLS
}
else if (matches("echo", option)) { //NON-NLS
GameModule.setErrorLogToChat(true);
show("Errorlog Echo: ON"); //NON-NLS
}
else if (matches("open", option)) { //NON-NLS
browseFileOrFolder(Info.getErrorLogPath());
}
else if (matches("wipe", option)) { //NON-NLS
final File errorLog = Info.getErrorLogPath();
try {
Files.newOutputStream(errorLog.toPath()).close();
show("Wiped errorlog"); //NON-NLS
}
catch (IOException e) {
show("Failed to wipe errorlog"); //NON-NLS
}
}
else if (matches("?", option) || matches("help", option) || ("".equals(option))) { //NON-NLS
show("Usage:"); //NON-NLS
show(" /errorlog echo - Echoes new errorlog info in chat log"); //NON-NLS
show(" /errorlog folder - Opens folder containing errorlog"); //NON-NLS
show(" /errorlog noecho - Disables echoing of errorlog info in chat log"); //NON-NLS
show(" /errorlog open - Opens errorlog in OS"); //NON-NLS
show(" /errorlog show [n] - Show last n lines of errorlog"); //NON-NLS
show(" /errorlog wipe - Wipe the errorlog file"); //NON-NLS
show(" /errorlog write [text] - Write text into the errorlog file"); //NON-NLS
}
else {
show("Unknown command."); //NON-NLS
show("Use '/errorlog help' for usage info."); //NON-NLS
}
return true;
}
private boolean doProperty() {
final String first = nextString("");
final String option;
final boolean useSelected;
if (first.toLowerCase().startsWith("sel")) { //NON-NLS
option = nextString("");
useSelected = true;
}
else {
option = first;
useSelected = false;
}
final String property = nextString("");
if (matches("?", option) || matches("help", option)) { //NON-NLS
show("Usage:"); //NON-NLS
show(" /property [selected] show [property] - show global property value"); //NON-NLS
show(" /property [selected] set [property] [value] - set global property new value"); //NON-NLS
show(" If optional keyword 'selected' included, show or set is for property of selected piece(s). "); //NON-NLS
show(" NOTE: many piece trait properties cannot be set (e.g. 'ObscuredToOthers', 'Invisible'), and the attempt to set them will simply fail quietly. "); //NON-NLS
}
else if (matches("show", option) || matches("set", option)) { //NON-NLS
final GameModule gm = GameModule.getGameModule();
if (useSelected) {
final List<GamePiece> selected = KeyBuffer.getBuffer().asList();
if (selected != null) {
for (final GamePiece piece : selected) {
final Object obj = piece.getProperty(property);
if (matches("set", option)) { //NON-NLS
if (obj != null) {
final String to = nextString("");
if (obj instanceof String) {
piece.setProperty(property, to);
}
else if (obj instanceof Integer) {
piece.setProperty(property, NumberUtils.toInt(to));
}
else if (obj instanceof Boolean) {
piece.setProperty(property, BooleanUtils.toBoolean(to));
}
}
}
final String val = (obj != null) ? obj.toString() : "(null)"; //NON-NLS
show(piece.getName() + " [" + property + "]: " + val);
}
}
}
else {
final MutableProperty.Impl propValue = (MutableProperty.Impl) gm.getMutableProperty(property);
if (matches("show", option)) { //NON-NLS
if (propValue != null) {
show("[" + property + "]: " + propValue.getPropertyValue());
}
else {
final String propVal = String.valueOf(gm.getProperty(property));
if (propVal != null) {
show("[" + property + "]: " + propVal);
}
}
}
else if (matches("set", option)) { //NON-NLS
if (propValue != null) {
propValue.setPropertyValue(nextString(""));
show("[" + property + "]: " + propValue.getPropertyValue());
}
}
}
}
return true;
}
private boolean doHelp() {
final String topic = nextString("");
if (topic.isEmpty()) {
show("VASSAL console commands:"); //NON-NLS
show(" /errorlog - commands for opening/clearing/altering errorlog"); //NON-NLS
show(" /help - shows list of commands"); //NON-NLS
show(" /property - commands for reading/writing global properties"); //NON-NLS
}
else {
tok = Pattern.compile(" +").splitAsStream("help").iterator(); //NON-NLS // Fake up a help subcommand
if (matches("errorlog", topic)) { //NON-NLS
return doErrorLog();
}
else if (matches("property", topic)) { //NON-NLS
return doProperty();
}
show("Unknown help topic"); //NON-NLS
}
return true;
}
public String commandsUp() {
if (commands.isEmpty() || (commandIndex <= 0)) {
return null;
}
commandIndex
return commands.get(commandIndex);
}
public String commandsDown() {
if (commands.isEmpty() || (commandIndex >= commands.size() - 1)) {
return null;
}
commandIndex++;
return commands.get(commandIndex);
}
public String commandsTop() {
if (commands.isEmpty()) {
return null;
}
commandIndex = 0;
return commands.get(commandIndex);
}
public String commandsBottom() {
if (commands.isEmpty()) {
return null;
}
commandIndex = commands.size() - 1;
return commands.get(commandIndex);
}
public boolean consoleHook(String s, String commandLine, Iterator<String> tok, String command) {
// Hook for console subclasses, etc.
return false;
}
public boolean exec(String s, String style, boolean html_allowed) {
if (s.isEmpty() || (s.charAt(0) != '/')) {
return false;
}
if (commands.isEmpty() || !s.equals(commands.get(Math.max(0, Math.min(commands.size() - 1, commandIndex))))) {
commands.add(s);
}
commandIndex = commands.size(); //NB: supposed to be one beyond the end
commandLine = s.substring(1);
show(s);
// First get rid of any extra spaces between things
tok = Pattern.compile(" +").splitAsStream(commandLine).iterator();
final String command = nextString("");
if (matches("help", command) || matches("?", command)) { //NON-NLS
return doHelp();
}
if (matches("errorlog", command)) { //NON-NLS
return doErrorLog();
}
// If this has EVER been a multiplayer game (has ever been connected to Server, or has ever had two player slots filled simultaneously), then
// it will not accept console commands.
final Logger log = GameModule.getGameModule().getLogger();
if (log instanceof BasicLogger) {
if (((BasicLogger)log).isMultiPlayer() || GameModule.getGameModule().isMultiPlayer()) {
show("|<b>Console commands that affect game state not allowed in multiplayer games.</b>"); //NON-NLS
return false;
}
}
if (matches("property", command)) { //NON-NLS
return doProperty();
}
if (!consoleHook(s, commandLine, tok, command)) {
show("Unknown command. Use /help for list of commands."); //NON-NLS
return false;
}
return true;
}
} |
package com.intellij.openapi.vcs.changes;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsBundle;
public class Waiter implements Runnable {
private final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.Waiter");
private final Project myProject;
private final Runnable myRunnable;
private boolean myStarted;
private boolean myDone;
private final Object myLock = new Object();
public Waiter(final Project project, final Runnable runnable) {
myRunnable = runnable;
myProject = project;
myDone = false;
myStarted = false;
}
public void run() {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setIndeterminate(true);
indicator.setText2(VcsBundle.message("commit.wait.util.synched.text"));
}
synchronized (myLock) {
if (myStarted) {
LOG.error("Waiter running under progress being started again.");
return;
}
myStarted = true;
while (! myDone) {
try {
// every second check whether we are canceled
myLock.wait(500);
}
catch (InterruptedException e) {
}
if (indicator != null) {
indicator.checkCanceled();
}
}
}
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
synchronized (myLock) {
if (! myDone) {
return;
}
}
if (myProject.isDisposed()) return;
myRunnable.run();
ChangesViewManager.getInstance(myProject).refreshView();
}
}, ModalityState.NON_MODAL);
}
public void done() {
synchronized (myLock) {
myDone = true;
myLock.notifyAll();
}
}
} |
package org.lionsoul.jcseg.tokenizer;
import org.lionsoul.jcseg.tokenizer.core.IWord;
/**
* word class for Jcseg with the {@link org.lionsoul.jcseg.core.IWord} interface implemented
*
* @author chenxin<chenxin619315@gmail.com>
*/
public class Word implements IWord,Cloneable
{
private String value;
private int fre = 0;
private int type;
private int position;
/**
* well the we could get the length of the word by invoke #getValue().length
* owing to the implementation of Jcseg and {@link #getValue()}.length may no equals to {@link #getLength()}
*
* {@link #getLength()} will return the value setted by
*/
private int length = -1;
private int h = -1;
/**
* @Note added at 2016/11/12
* word string entity name and
* it could be assign from the lexicon or the word item setting
* or assign dynamic during the cut runtime
*/
private String entity = null;
private String pinyin = null;
private String[] partspeech = null;
private String[] syn = null;
/**
* construct method to initialize the newly created Word instance
*
* @param value
* @param fre
* @param type
* @param entity
*/
public Word(String value, int fre, int type, String entity)
{
this.value = value;
this.fre = fre;
this.type = type;
this.entity = entity;
}
public Word( String value, int fre, int type )
{
this(value, fre, type, null);
}
public Word( String value, int type )
{
this(value, 0, type, null);
}
public Word(String value, int type, String entity)
{
this(value, 0, type, entity);
}
/**
* @see IWord#getValue()
*/
@Override
public String getValue()
{
return value;
}
/**
* @see IWord#getLength()
*/
@Override
public int getLength()
{
return (length == -1 ) ? value.length() : length;
}
/**
* @see IWord#setLength(int)
*/
@Override
public void setLength( int length )
{
this.length = length;
}
/**
* @see IWord#getFrequency()
*/
@Override
public int getFrequency()
{
return fre;
}
/**
* @see IWord#getType()
*/
@Override
public int getType()
{
return type;
}
/**
* @see IWord#setPosition(int)
*/
@Override
public void setPosition( int pos )
{
position = pos;
}
/**
* @see IWord#getPosition()
*/
public int getPosition()
{
return position;
}
/**
* @see IWord#getEntity()
*/
public String getEntity()
{
return entity;
}
/**
* @see IWord#setEntity(String)
*/
public void setEntity(String entity)
{
this.entity = entity;
}
/**
* @see IWord#getPinying()
*/
@Override
public String getPinyin()
{
return pinyin;
}
/**
* @see IWord#getSyn()
*/
@Override
public String[] getSyn()
{
return syn;
}
@Override
public void setSyn(String[] syn)
{
this.syn = syn;
}
/**
* @see IWord#getPartSpeech()
*/
@Override
public String[] getPartSpeech()
{
return partspeech;
}
@Override
public void setPartSpeech(String[] partspeech)
{
this.partspeech = partspeech;
}
/**
* @see IWord#setPinying(String)
*/
public void setPinyin( String py )
{
pinyin = py;
}
/**
* @see IWord#addPartSpeech( String );
*/
@Override
public void addPartSpeech( String ps )
{
if ( partspeech == null ) {
partspeech = new String[1];
partspeech[0] = ps;
} else {
String[] bak = partspeech;
partspeech = new String[partspeech.length + 1];
int j;
for ( j = 0; j < bak.length; j++ ) {
partspeech[j] = bak[j];
}
partspeech[j] = ps;
bak = null;
}
}
/**
* @see IWord#addSyn(String)
*/
@Override
public void addSyn( String s )
{
if ( syn == null ) {
syn = new String[1];
syn[0] = s;
} else {
String[] tycA = syn;
syn = new String[syn.length + 1];
int j;
for ( j = 0; j < tycA.length; j++ ) {
syn[j] = tycA[j];
}
syn[j] = s;
tycA = null;
}
}
/**
* @see Object#equals(Object)
* @see IWord#equals(Object)
*/
public boolean equals( Object o )
{
if ( this == o ) return true;
if ( o instanceof IWord ) {
IWord word = (IWord) o;
boolean bool = word.getValue().equalsIgnoreCase(this.getValue());
/*
* value equals and the type of the word must
* be equals too, for there is many words in
* different lexicon with a same value but
* in different use.
*/
return (bool && (word.getType() == this.getType()));
}
return false;
}
/**
* Interface to clone the current object
*
* @return IWord
*/
@Override
public IWord clone()
{
IWord w = null;
try {
w = (IWord) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return w;
}
/**
* for debug testing
*/
public String __toString()
{
StringBuilder sb = new StringBuilder();
sb.append(value);
sb.append('/');
//append the cx
if ( partspeech != null ) {
for ( int j = 0; j < partspeech.length; j++ ) {
if ( j == 0 ) {
sb.append(partspeech[j]);
} else {
sb.append(',');
sb.append(partspeech[j]);
}
}
} else {
sb.append("null");
}
sb.append('/');
sb.append(pinyin);
sb.append('/');
//append the tyc
if ( syn != null ) {
for ( int j = 0; j < syn.length; j++ ) {
if ( j == 0 ) {
sb.append(syn[j]);
} else {
sb.append(',');
sb.append(syn[j]);
}
}
} else {
sb.append("null");
}
if ( value.length() == 1 ) {
sb.append('/');
sb.append(fre);
}
if ( entity != null ) {
sb.append('/');
sb.append(entity);
}
return sb.toString();
}
/**
* @see Object#toString()
*/
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append('{');
/*
* @Note: Check and pre-process the word value
* for if there is char "\"" or "\\" inside
* the Json Anti-analysis will be end with parse error ...
*/
if ( value.length() == 1
&& (value.charAt(0) == '"' || value.charAt(0) == '\\') ) {
sb.append("\"word\":\"\\").append(value).append('"');
} else {
sb.append("\"word\":\"").append(value).append('"');
}
sb.append(",\"position\":").append(position);
sb.append(",\"length\":").append(getLength());
if ( pinyin != null ) {
sb.append(",\"pinyin\":\"").append(pinyin).append('"');
} else {
sb.append(",\"pinyin\":null");
}
if ( partspeech != null ) {
sb.append(",\"pos\":\"").append(partspeech[0]).append('"');
} else {
sb.append(",\"pos\":null");
}
if ( entity != null ) {
sb.append(",\"entity\":\"").append(entity).append('"');
} else {
sb.append(",\"entity\":null");
}
sb.append('}');
return sb.toString();
}
/**
* rewrite the hash code generate algorithm
* take the value as the main factor
*
* @return int
*/
@Override
public int hashCode()
{
if ( h == -1 ) {
/*
* DJB hash algorithm 2
* invented by doctor Daniel J. Bernstein.
*/
h = 5381;
for ( int j = 0; j < value.length(); j++ ) {
h = h * 33 ^ value.charAt(j);
}
h &= 0x7FFFFFFF;
}
return h;
}
} |
package com.oldterns.vilebot.handlers.user;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.oldterns.vilebot.CharactersThatBreakEclipse;
import net.engio.mbassy.listener.Handler;
import ca.szc.keratin.bot.annotation.HandlerContainer;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
@HandlerContainer
public class Jokes
{
private static final Pattern listJokePattern = Pattern.compile( "!(randommeme|dance|chuck)" );
private static final Pattern redditPattern = Pattern.compile( "(?i)reddit" );
private static final Pattern containerPattern = Pattern.compile( "(?i)container" );
private static final Random random = new Random();
private static final List<String> memes = generateMemes();
private static final List<String> dances = generateDances();
private static final List<String> chucks = generateChucks();
private static final List<String> jokes = generateJokes();
@Handler
private void containersIsLinux ( ReceivePrivmsg event) {
String text = event.getText();
Matcher matcher = containerPattern.matcher( text );
if ( matcher.find() ) {
event.reply( jokes.get( random.nextInt( jokes.size() ) ) );
}
}
@Handler
private void redditLOD( ReceivePrivmsg event )
{
String text = event.getText();
Matcher containerMatcher = redditPattern.matcher( text );
if ( containerMatcher.matches() )
{
if ( random.nextInt( 10 ) > 6 )
{
event.reply( CharactersThatBreakEclipse.LODEMOT );
}
}
}
/**
* Reply to user !randommeme command with a random selection from the meme list
*/
@Handler
private void listBasedJokes( ReceivePrivmsg event )
{
String text = event.getText();
Matcher matcher = listJokePattern.matcher( text );
if ( matcher.matches() )
{
String mode = matcher.group( 1 );
String reply;
if ( "dance".equals( mode ) )
reply = dances.get( random.nextInt( dances.size() ) );
else if ( "chuck".equals( mode ) )
reply = chucks.get( random.nextInt( chucks.size() ) );
else
reply = memes.get( random.nextInt( memes.size() ) );
event.reply( reply );
}
}
private static List<String> generateChucks()
{
List<String> chucks = new ArrayList<String>();
// Anyone called Chuck except Chuck Norris
chucks.add( "Chuck Palahniuk once said, \"Your birth is a mistake you'll spend your whole life trying to correct.\"" );
chucks.add( "Chuck Tanner once said, \"If you don't like the way the Atlanta Braves are playing then you don't like baseball.\"" );
chucks.add( "Chuck Berry once said, \"Roll over, Beethoven, and tell Tchaikovsky the news.\"" );
chucks.add( "Chuck Yeager once said, \"Rules are made for people who aren't willing to make up their own.\"" );
chucks.add( "Chuck Klosterman once said, \"I guess what I'm saying is, I'm not your enemy.\"" );
chucks.add( "Chuck Jones once said, \"A lion's work hours are only when he's hungry; once he's satisfied, the predator and prey live peacefully together.\"" );
chucks.add( "Chuck Close once said, \"I'm very learning-disabled, and I think it drove me to what I'm doing.\"" );
chucks.add( "Chuck D once said, \"I think governments are the cancer of civilization.\"" );
chucks.add( "Chuck Knox once said, \"Always have a plan, and believe in it. Nothing happens by accident.\"" );
chucks.add( "Chuck Zito once said, \"If the challenge to fight was there, I always took it.\"" );
return chucks;
}
private static List<String> generateDances()
{
List<String> dances = new ArrayList<String>();
dances.add( "No. " + CharactersThatBreakEclipse.LODEMOT );
dances.add( "Bots as vile as I do not dance." );
dances.add( "ScumbagBot does not dance." );
dances.add( "Chuck Norris once asked me to dance. He didn't have a comeback after the roundhouse kickban." );
dances.add( CharactersThatBreakEclipse.KIRBYFLIP + "\n*kills Kirby*\n*kills dance*" );
dances.add( "Does doing a barrel roll count?" );
return dances;
}
private static List<String> generateMemes()
{
List<String> memes = new ArrayList<String>();
memes.add( CharactersThatBreakEclipse.LODEMOT );
memes.add( "Derp." );
memes.add( "looks like his string was, *puts on glasses*\nnull terminated.\nYEEEEEEEEEEEEEEEEEEEEEEAAAAAAHHHHHHHHH" );
memes.add( "Yo Dawg" );
memes.add( "Imma gunna cut you so bad, you gunna wish I dun cut you so bad" );
memes.add( "So i herd u liek mudkipz" );
memes.add( "Never gunna give you up, Never gunna let you down!" );
memes.add( "DO A BARREL ROLL ._. |: .-. :| ._." );
memes.add( "ScumbagBot, shows up to the party, drinks all your beer." );
memes.add( "Don't tase me bro" );
return memes;
}
@SuppressWarnings( "unused" )
private static List<String> generateEaster()
{
List<String> easter = new ArrayList<String>();
easter.add( "I hate easter. Laying foil-covered eggs is no fun, no fun at all." );
easter.add( "Buck, buck." );
easter.add( "twitches her nose. Isn't that cute?" );
easter.add( "strains and grunts a little, and out pops a Cadbury cream egg!" );
easter.add( "Has anybody seen Santa Claus around? He's supposed to cover for me on my lunch break." );
easter.add( "nibbles on a hunk of milk chocolate." );
easter.add( "takes three hops to the left." );
easter.add( "Buck." );
easter.add( "Bu-buck." );
easter.add( "takes three hops to the right." );
easter.add( "Bu-bu-buck." );
easter.add( "just sits here being fuzzy." );
easter.add( "Buck, buck, buck." );
return easter;
}
private static List<String> generateJokes()
{
List<String> jokes = new ArrayList<String>();
jokes.add( "C O N T A I N E D");
jokes.add("H Y B R I D C L O U D");
jokes.add("\"Linux is Containers and Containers is RHEL\"");
jokes.add("It can contain anything, even monster apps!");
jokes.add("I sell Container and Container accessories");
jokes.add("Do U Even Small VM bro?");
jokes.add("Y SO CONTAINED?");
jokes.add("Containers give me lyfe.");
jokes.add("Containers pay the bills.");
jokes.add("My name is yzhang and I'm a containerholic.");
jokes.add("\"Containers\"");
jokes.add("Keep your containers to yourself!");
jokes.add("*insert bad container joke here*");
jokes.add("AM I BEING CONTAINED?");
jokes.add("friggin' containers, how do they work?");
jokes.add("I put the \"I\" in contaIners");
jokes.add("DON'T CONTAZE ME BRO");
jokes.add("Every day we stray farther from gods light.");
jokes.add("Please, contain yourself.");
jokes.add("PRESS Z TO DO A CONTAINER ROLL");
jokes.add("STOP. CONTAINER TIME");
jokes.add("Dat feel when you can only contain monster apps and not your feelings");
jokes.add("- Refer to the Container Coloring Book");
return jokes;
}
} |
package com.jenjinstudios.core;
import com.jenjinstudios.core.io.Message;
import com.jenjinstudios.core.io.MessageInputStream;
import com.jenjinstudios.core.io.MessageOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.security.Key;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Used to contain a {@code MessageInputStream} and {@code MessageOutputStream}.
*
* @author Caleb Brinkman
*/
public class MessageIO
{
private static final Logger LOGGER = Logger.getLogger(MessageIO.class.getName());
private final MessageInputStream in;
private final MessageOutputStream out;
private final InetAddress address;
private final LinkedList<Message> outgoingMessages;
/**
* Construct a new {@code MessageIO} from the given message input and output streams.
*
* @param in The input stream.
* @param out The output stream.
*/
public MessageIO(MessageInputStream in, MessageOutputStream out) {
this(in, out, null);
}
/**
* Construct a new {@code MessageIO} from the given message input and output streams.
*
* @param in The input stream.
* @param out The output stream.
* @param address The Internet Address of the complementary connection.
*/
public MessageIO(MessageInputStream in, MessageOutputStream out, InetAddress address) {
this.in = in;
this.out = out;
this.address = address;
outgoingMessages = new LinkedList<>();
}
/**
* Get the address of the complementary connection, if it exists. Returns null if no address is known.
*
* @return The address of the complementary connection, null if unknown.
*/
public InetAddress getAddress() { return address; }
/**
* Get the {@code MessageInputStream} managed by this {@code MessageIO}.
*
* @return The {@code MessageInputStream} managed by this {@code MessageIO}.
*/
MessageInputStream getIn() { return in; }
/**
* Set the public key used to encrypt relevant messages.
*
* @param publicKey The public key.
*/
public void setPublicKey(Key publicKey) { out.setPublicKey(publicKey); }
/**
* Add the specified {@code Message} to the queue of outgoing messages. This queue is written when {@code
* writeAllMessages} is called.
*
* @param message The {@code Message} to write.
*/
public void queueOutgoingMessage(Message message) {
if (out.isClosed())
{
throw new MessageQueueException(message);
}
synchronized (outgoingMessages)
{
outgoingMessages.add(message);
}
}
/**
* Write all the messages in the outgoing messages queue to the output stream.
*
* @throws java.io.IOException If there is an exception writing a message to the output stream.
*/
public void writeAllMessages() throws IOException {
synchronized (outgoingMessages)
{
while (!outgoingMessages.isEmpty())
{
writeMessage(outgoingMessages.remove());
}
}
}
void writeMessage(Message o) throws IOException { out.writeMessage(o); }
void closeOutputStream() {
try
{
out.close();
} catch (IOException e)
{
LOGGER.log(Level.INFO, "Error closing output stream.", e);
}
}
void closeInputStream() {
try
{
in.close();
} catch (IOException e)
{
LOGGER.log(Level.INFO, "Error closing input stream.", e);
}
}
} |
package io.searchbox.client.http;
import io.searchbox.action.Action;
import io.searchbox.client.AbstractJestClient;
import io.searchbox.client.JestResult;
import io.searchbox.client.JestResultHandler;
import io.searchbox.client.config.exception.CouldNotConnectException;
import io.searchbox.client.http.apache.HttpDeleteWithEntity;
import io.searchbox.client.http.apache.HttpGetWithEntity;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.concurrent.Future;
import org.apache.http.*;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
/**
* @author Dogukan Sonmez
* @author cihat keser
*/
public class JestHttpClient extends AbstractJestClient {
private final static Logger log = LoggerFactory.getLogger(JestHttpClient.class);
protected ContentType requestContentType = ContentType.APPLICATION_JSON.withCharset("utf-8");
private CloseableHttpClient httpClient;
private CloseableHttpAsyncClient asyncClient;
private HttpClientContext httpClientContextTemplate;
/**
* @throws IOException in case of a problem or the connection was aborted during request,
* or in case of a problem while reading the response stream
* @throws CouldNotConnectException if an {@link HttpHostConnectException} is encountered
*/
@Override
public <T extends JestResult> T execute(Action<T> clientRequest) throws IOException {
HttpUriRequest request = prepareRequest(clientRequest);
CloseableHttpResponse response = null;
try {
response = executeRequest(request);
return deserializeResponse(response, request, clientRequest);
} catch (HttpHostConnectException ex) {
throw new CouldNotConnectException(ex.getHost().toURI(), ex);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException ex) {
log.error("Exception occurred while closing response stream.", ex);
}
}
}
}
@Override
public <T extends JestResult> void executeAsync(final Action<T> clientRequest, final JestResultHandler<? super T> resultHandler) {
synchronized (this) {
if (!asyncClient.isRunning()) {
asyncClient.start();
}
}
HttpUriRequest request = prepareRequest(clientRequest);
executeAsyncRequest(clientRequest, resultHandler, request);
}
@Override
public void shutdownClient() {
super.shutdownClient();
try {
asyncClient.close();
} catch (IOException ex) {
log.error("Exception occurred while shutting down the async client.", ex);
}
try {
httpClient.close();
} catch (IOException ex) {
log.error("Exception occurred while shutting down the sync client.", ex);
}
}
protected <T extends JestResult> HttpUriRequest prepareRequest(final Action<T> clientRequest) {
String elasticSearchRestUrl = getRequestURL(getNextServer(), clientRequest.getURI());
HttpUriRequest request = constructHttpMethod(clientRequest.getRestMethodName(), elasticSearchRestUrl, clientRequest.getData(gson));
log.debug("Request method={} url={}", clientRequest.getRestMethodName(), elasticSearchRestUrl);
// add headers added to action
for (Entry<String, Object> header : clientRequest.getHeaders().entrySet()) {
request.addHeader(header.getKey(), header.getValue().toString());
}
return request;
}
protected CloseableHttpResponse executeRequest(HttpUriRequest request) throws IOException {
if (httpClientContextTemplate != null) {
return httpClient.execute(request, createContextInstance());
}
return httpClient.execute(request);
}
protected <T extends JestResult> Future<HttpResponse> executeAsyncRequest(Action<T> clientRequest, JestResultHandler<? super T> resultHandler, HttpUriRequest request) {
if (httpClientContextTemplate != null) {
return asyncClient.execute(request, createContextInstance(), new DefaultCallback<T>(clientRequest, request, resultHandler));
}
return asyncClient.execute(request, new DefaultCallback<T>(clientRequest, request, resultHandler));
}
protected HttpClientContext createContextInstance() {
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(httpClientContextTemplate.getCredentialsProvider());
context.setAuthCache(httpClientContextTemplate.getAuthCache());
return context;
}
protected HttpUriRequest constructHttpMethod(String methodName, String url, String payload) {
HttpUriRequest httpUriRequest = null;
if (methodName.equalsIgnoreCase("POST")) {
httpUriRequest = new HttpPost(url);
log.debug("POST method created based on client request");
} else if (methodName.equalsIgnoreCase("PUT")) {
httpUriRequest = new HttpPut(url);
log.debug("PUT method created based on client request");
} else if (methodName.equalsIgnoreCase("DELETE")) {
httpUriRequest = new HttpDeleteWithEntity(url);
log.debug("DELETE method created based on client request");
} else if (methodName.equalsIgnoreCase("GET")) {
httpUriRequest = new HttpGetWithEntity(url);
log.debug("GET method created based on client request");
} else if (methodName.equalsIgnoreCase("HEAD")) {
httpUriRequest = new HttpHead(url);
log.debug("HEAD method created based on client request");
}
if (httpUriRequest != null && httpUriRequest instanceof HttpEntityEnclosingRequest && payload != null) {
EntityBuilder entityBuilder = EntityBuilder.create()
.setText(payload)
.setContentType(requestContentType);
if (isRequestCompressionEnabled()) {
entityBuilder.gzipCompress();
}
((HttpEntityEnclosingRequest) httpUriRequest).setEntity(entityBuilder.build());
}
return httpUriRequest;
}
private <T extends JestResult> T deserializeResponse(HttpResponse response, final HttpRequest httpRequest, Action<T> clientRequest) throws IOException {
StatusLine statusLine = response.getStatusLine();
try {
return clientRequest.createNewElasticSearchResult(
response.getEntity() == null ? null : EntityUtils.toString(response.getEntity()),
statusLine.getStatusCode(),
statusLine.getReasonPhrase(),
gson
);
} catch (com.google.gson.JsonSyntaxException e) {
for (Header header : response.getHeaders("Content-Type")) {
final String mimeType = header.getValue();
if (!mimeType.startsWith("application/json")) {
// probably a proxy that responded in text/html
final String message = "Request " + httpRequest.toString() + " yielded " + mimeType
+ ", should be json: " + statusLine.toString();
throw new IOException(message, e);
}
}
throw e;
}
}
public CloseableHttpClient getHttpClient() {
return httpClient;
}
public void setHttpClient(CloseableHttpClient httpClient) {
this.httpClient = httpClient;
}
public CloseableHttpAsyncClient getAsyncClient() {
return asyncClient;
}
public void setAsyncClient(CloseableHttpAsyncClient asyncClient) {
this.asyncClient = asyncClient;
}
public Gson getGson() {
return gson;
}
public void setGson(Gson gson) {
this.gson = gson;
}
public HttpClientContext getHttpClientContextTemplate() {
return httpClientContextTemplate;
}
public void setHttpClientContextTemplate(HttpClientContext httpClientContext) {
this.httpClientContextTemplate = httpClientContext;
}
protected class DefaultCallback<T extends JestResult> implements FutureCallback<HttpResponse> {
private final Action<T> clientRequest;
private final HttpRequest request;
private final JestResultHandler<? super T> resultHandler;
public DefaultCallback(Action<T> clientRequest, final HttpRequest request, JestResultHandler<? super T> resultHandler) {
this.clientRequest = clientRequest;
this.request = request;
this.resultHandler = resultHandler;
}
@Override
public void completed(final HttpResponse response) {
T jestResult = null;
try {
jestResult = deserializeResponse(response, request, clientRequest);
} catch (IOException e) {
failed(e);
}
if (jestResult != null) resultHandler.completed(jestResult);
}
@Override
public void failed(final Exception ex) {
log.error("Exception occurred during async execution.", ex);
if (ex instanceof HttpHostConnectException) {
String host = ((HttpHostConnectException) ex).getHost().toURI();
resultHandler.failed(new CouldNotConnectException(host, ex));
return;
}
resultHandler.failed(ex);
}
@Override
public void cancelled() {
log.warn("Async execution was cancelled; this is not expected to occur under normal operation.");
}
}
} |
package io.searchbox.core;
import io.searchbox.common.AbstractIntegrationTest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.test.ESIntegTestCase;
import org.junit.Test;
/**
* @author Dogukan Sonmez
*/
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE, numDataNodes = 1)
public class UpdateIntegrationTest extends AbstractIntegrationTest {
private static final String INDEX = "twitter";
private static final String TYPE = "tweet";
@Test
public void scriptedUpdateWithValidParameters() throws Exception {
String id = "1";
String script = "{\n" +
" \"script\": {\n" +
" \"lang\": \"painless\",\n" +
" \"inline\": \"ctx._source.tags += params.tag\",\n" +
" \"params\": {\n" +
" \"tag\": \"blue\"\n" +
" }\n" +
" }\n" +
"}";
client().index(
new IndexRequest(INDEX, TYPE, id)
.source("{\"user\":\"kimchy\", \"tags\":\"That is test\"}")
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
).actionGet();
DocumentResult result = client.execute(new Update.Builder(script).index(INDEX).type(TYPE).id(id).build());
assertTrue(result.getErrorMessage(), result.isSucceeded());
assertEquals(INDEX, result.getIndex());
assertEquals(TYPE, result.getType());
assertEquals(id, result.getId());
GetResponse getResult = get(INDEX, TYPE, id);
assertTrue(getResult.isExists());
assertFalse(getResult.isSourceEmpty());
assertEquals("That is testblue", getResult.getSource().get("tags"));
}
@Test
public void partialDocUpdateWithValidParameters() throws Exception {
String id = "2";
String partialDoc = "{\n" +
" \"doc\" : {\n" +
" \"tags\" : \"blue\"\n" +
" }\n" +
"}";
client().index(
new IndexRequest(INDEX, TYPE, id)
.source("{\"user\":\"kimchy\", \"tags\":\"That is test\"}")
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
).actionGet();
DocumentResult result = client.execute(new Update.Builder(partialDoc).index(INDEX).type(TYPE).id(id).build());
assertTrue(result.getErrorMessage(), result.isSucceeded());
assertEquals(INDEX, result.getIndex());
assertEquals(TYPE, result.getType());
assertEquals(id, result.getId());
GetResponse getResult = get(INDEX, TYPE, id);
assertTrue(getResult.isExists());
assertFalse(getResult.isSourceEmpty());
assertEquals("blue", getResult.getSource().get("tags"));
}
@Test
public void partialDocUpdateWithValidVersion() throws Exception {
String id = "2";
String partialDoc = "{\n" +
" \"doc\" : {\n" +
" \"tags\" : \"blue\"\n" +
" }\n" +
"}";
IndexResponse response = client().index(
new IndexRequest(INDEX, TYPE, id)
.source("{\"user\":\"kimchy\", \"tags\":\"That is test\"}")
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
).actionGet();
long version = response.getVersion();
DocumentResult result = client.execute(new Update.VersionBuilder(partialDoc, version)
.index(INDEX)
.type(TYPE)
.id(id)
.build());
assertTrue(result.getErrorMessage(), result.isSucceeded());
assertEquals(INDEX, result.getIndex());
assertEquals(TYPE, result.getType());
assertEquals(id, result.getId());
assertEquals(version + 1, result.getVersion().longValue());
GetResponse getResult = get(INDEX, TYPE, id);
assertTrue(getResult.isExists());
assertFalse(getResult.isSourceEmpty());
assertEquals("blue", getResult.getSource().get("tags"));
}
@Test
public void partialDocUpdateWithInvalidVersion() throws Exception {
String id = "2";
String partialDoc = "{\n" +
" \"doc\" : {\n" +
" \"tags\" : \"blue\"\n" +
" }\n" +
"}";
String partialDoc2 = "{\n" +
" \"doc\" : {\n" +
" \"tags\" : \"red\"\n" +
" }\n" +
"}";
IndexResponse response = client().index(
new IndexRequest(INDEX, TYPE, id)
.source("{\"user\":\"kimchy\", \"tags\":\"That is test\"}")
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
).actionGet();
long version = response.getVersion();
DocumentResult result = client.execute(new Update.VersionBuilder(partialDoc, version)
.index(INDEX)
.type(TYPE)
.id(id)
.build());
assertTrue(result.getErrorMessage(), result.isSucceeded());
// and again ...
result = client.execute(new Update.VersionBuilder(partialDoc2, version)
.index(INDEX)
.type(TYPE)
.id(id)
.build());
assertFalse(result.getErrorMessage(), result.isSucceeded());
assertEquals("Invalid response code", RestStatus.CONFLICT.getStatus(), result.getResponseCode());
GetResponse getResult = get(INDEX, TYPE, id);
assertTrue(getResult.isExists());
assertEquals(version + 1, getResult.getVersion());
assertEquals("blue", getResult.getSource().get("tags"));
}
} |
package com.haskforce.jps.model;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.annotations.AbstractCollection;
import com.intellij.util.xmlb.annotations.Tag;
import java.util.List;
/**
* Serialization object for communicating build settings with the build server.
*/
public class HaskellBuildOptions {
public static final boolean DEFAULT_USE_CABAL = false;
public static final boolean DEFAULT_USE_CABAL_SANDBOX = false;
public static final boolean DEFAULT_USE_PROFILING_BUILD = false;
public static final String DEFAULT_GHC_PATH = "";
public static final String DEFAULT_CABAL_PATH = "";
public static final String DEFAULT_CABAL_FLAGS = "";
public static final boolean DEFAULT_INSTALL_CABAL_DEPENDENCIES = false;
public static final boolean DEFAULT_ENABLE_TESTS = false;
public static final boolean DEFAULT_USE_STACK = false;
public static final String DEFAULT_STACK_FILE = "stack.yaml";
public HaskellBuildOptions() {
}
public HaskellBuildOptions(HaskellBuildOptions options) {
myUseCabal = options.myUseCabal;
myUseCabalSandbox = options.myUseCabalSandbox;
myProfilingBuild = options.myProfilingBuild;
myGhcPath = options.myGhcPath;
myCabalPath = options.myCabalPath;
myCabalFlags = options.myCabalFlags;
myInstallCabalDependencies = options.myInstallCabalDependencies;
}
@Tag("useCabal")
public boolean myUseCabal = DEFAULT_USE_CABAL;
@Tag("useCabalSandbox")
public boolean myUseCabalSandbox = DEFAULT_USE_CABAL_SANDBOX;
@Tag("useProfilingBuild")
public boolean myProfilingBuild = DEFAULT_USE_PROFILING_BUILD;
@Tag("ghcPath")
public String myGhcPath = DEFAULT_GHC_PATH;
@Tag("cabalPath")
public String myCabalPath = DEFAULT_CABAL_PATH;
@Tag("cabalFlags")
public String myCabalFlags = DEFAULT_CABAL_FLAGS;
@Tag("cabalFiles")
@AbstractCollection(surroundWithTag = false, elementTag = "cabalFile")
public List<String> myCabalFiles = ContainerUtil.newArrayList();
@Tag("installDependencies")
public boolean myInstallCabalDependencies = DEFAULT_INSTALL_CABAL_DEPENDENCIES;
@Tag("enableTests")
public boolean myEnableTests = DEFAULT_ENABLE_TESTS;
@Tag("useStack")
public boolean myUseStack = DEFAULT_USE_STACK;
@Tag("stackPath")
public String myStackPath = "";
@Tag("stackFlags")
public String myStackFlags = "";
@Tag("stackFile")
public String myStackFile = DEFAULT_STACK_FILE;
@Override
public String toString() {
return "HaskellBuildOptions{" +
"myUseCabal=" + myUseCabal +
", myUseCabalSandbox=" + myUseCabalSandbox +
", myProfilingBuild=" + myProfilingBuild +
", myGhcPath=" + myGhcPath +
", myCabalPath=" + myCabalPath +
", myCabalFlags=" + myCabalFlags +
", myCabalFiles=" + myCabalFiles +
", myInstallCabalDependencies=" + myInstallCabalDependencies +
", myEnableTests=" + myEnableTests +
", myUseStack=" + myUseStack +
", myStackPath=" + myStackPath +
'}';
}
} |
package jsettlers.ai.highlevel;
import static jsettlers.ai.construction.BestStoneCutterConstructionPositionFinder.MAX_STONE_DISTANCE;
import static jsettlers.common.buildings.EBuildingType.BAKER;
import static jsettlers.common.buildings.EBuildingType.BARRACK;
import static jsettlers.common.buildings.EBuildingType.BIG_LIVINGHOUSE;
import static jsettlers.common.buildings.EBuildingType.COALMINE;
import static jsettlers.common.buildings.EBuildingType.FARM;
import static jsettlers.common.buildings.EBuildingType.FISHER;
import static jsettlers.common.buildings.EBuildingType.FORESTER;
import static jsettlers.common.buildings.EBuildingType.GOLDMELT;
import static jsettlers.common.buildings.EBuildingType.GOLDMINE;
import static jsettlers.common.buildings.EBuildingType.IRONMELT;
import static jsettlers.common.buildings.EBuildingType.IRONMINE;
import static jsettlers.common.buildings.EBuildingType.LUMBERJACK;
import static jsettlers.common.buildings.EBuildingType.MEDIUM_LIVINGHOUSE;
import static jsettlers.common.buildings.EBuildingType.MILL;
import static jsettlers.common.buildings.EBuildingType.PIG_FARM;
import static jsettlers.common.buildings.EBuildingType.SAWMILL;
import static jsettlers.common.buildings.EBuildingType.SLAUGHTERHOUSE;
import static jsettlers.common.buildings.EBuildingType.SMALL_LIVINGHOUSE;
import static jsettlers.common.buildings.EBuildingType.STOCK;
import static jsettlers.common.buildings.EBuildingType.STONECUTTER;
import static jsettlers.common.buildings.EBuildingType.TEMPLE;
import static jsettlers.common.buildings.EBuildingType.TOOLSMITH;
import static jsettlers.common.buildings.EBuildingType.TOWER;
import static jsettlers.common.buildings.EBuildingType.WATERWORKS;
import static jsettlers.common.buildings.EBuildingType.WEAPONSMITH;
import static jsettlers.common.buildings.EBuildingType.WINEGROWER;
import static jsettlers.common.material.EMaterialType.GOLD;
import static jsettlers.common.material.EMaterialType.HAMMER;
import static jsettlers.common.material.EMaterialType.PICK;
import static jsettlers.logic.constants.Constants.TOWER_SEARCH_RADIUS;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jsettlers.ai.construction.BestConstructionPositionFinderFactory;
import jsettlers.ai.construction.BuildingCount;
import jsettlers.common.buildings.EBuildingType;
import jsettlers.common.material.EMaterialType;
import jsettlers.common.movable.EMovableType;
import jsettlers.common.position.ShortPoint2D;
import jsettlers.input.tasks.ConstructBuildingTask;
import jsettlers.input.tasks.EGuiAction;
import jsettlers.input.tasks.MoveToGuiTask;
import jsettlers.logic.buildings.military.OccupyingBuilding;
import jsettlers.logic.map.grid.MainGrid;
import jsettlers.logic.movable.Movable;
import jsettlers.network.client.interfaces.ITaskScheduler;
public class RomanWhatToDoAi implements IWhatToDoAi {
private final MainGrid mainGrid;
private final byte playerId;
private final ITaskScheduler taskScheduler;
private final AiStatistics aiStatistics;
private final List<EBuildingType> buildingsToBuild;
private final Map<EBuildingType, List<BuildingCount>> buildingNeeds;
private final Map<EBuildingType, List<EBuildingType>> buildingIsNeededBy;
BestConstructionPositionFinderFactory bestConstructionPositionFinderFactory;
public RomanWhatToDoAi(byte playerId, AiStatistics aiStatistics, MainGrid mainGrid, ITaskScheduler taskScheduler) {
this.playerId = playerId;
this.mainGrid = mainGrid;
this.taskScheduler = taskScheduler;
this.aiStatistics = aiStatistics;
buildingNeeds = new HashMap<EBuildingType, List<BuildingCount>>();
buildingIsNeededBy = new HashMap<EBuildingType, List<EBuildingType>>();
bestConstructionPositionFinderFactory = new BestConstructionPositionFinderFactory();
buildingsToBuild = new ArrayList<EBuildingType>();
initializeBuildingLists();
}
private void initializeBuildingLists() {
for (EBuildingType buildingType : EBuildingType.values()) {
buildingNeeds.put(buildingType, new ArrayList<BuildingCount>());
buildingIsNeededBy.put(buildingType, new ArrayList<EBuildingType>());
}
buildingNeeds.get(SAWMILL).add(new BuildingCount(LUMBERJACK, 3));
buildingNeeds.get(TEMPLE).add(new BuildingCount(WINEGROWER, 1));
buildingNeeds.get(WATERWORKS).add(new BuildingCount(FARM, 2));
buildingNeeds.get(MILL).add(new BuildingCount(FARM, 1));
buildingNeeds.get(BAKER).add(new BuildingCount(MILL, 1 / 3));
buildingNeeds.get(PIG_FARM).add(new BuildingCount(FARM, 1));
buildingNeeds.get(SLAUGHTERHOUSE).add(new BuildingCount(PIG_FARM, 1 / 3));
buildingNeeds.get(IRONMELT).add(new BuildingCount(COALMINE, 1));
buildingNeeds.get(IRONMELT).add(new BuildingCount(IRONMINE, 1));
buildingNeeds.get(WEAPONSMITH).add(new BuildingCount(COALMINE, 1));
buildingNeeds.get(WEAPONSMITH).add(new BuildingCount(IRONMELT, 1));
buildingNeeds.get(GOLDMELT).add(new BuildingCount(GOLDMINE, 1));
buildingNeeds.get(BARRACK).add(new BuildingCount(WEAPONSMITH, 4));
//Ironmine depends of coalmine to prevent iron and coal are build 1:1 when picks are missing
//otherwise always as loop: one additional ironmine and coalmine would be build for inform toolsmith to produce picks
buildingNeeds.get(IRONMINE).add(new BuildingCount(COALMINE, 2));
for (Map.Entry<EBuildingType, List<BuildingCount>> buildingNeedsEntry : buildingNeeds.entrySet()) {
for (BuildingCount neededBuildingCount : buildingNeedsEntry.getValue()) {
buildingIsNeededBy.get(neededBuildingCount.buildingType).add(buildingNeedsEntry.getKey());
}
}
buildingsToBuild.add(LUMBERJACK);
buildingsToBuild.add(LUMBERJACK);
buildingsToBuild.add(SAWMILL);
buildingsToBuild.add(LUMBERJACK);
buildingsToBuild.add(FORESTER);
buildingsToBuild.add(STONECUTTER);
buildingsToBuild.add(LUMBERJACK);
buildingsToBuild.add(FORESTER);
buildingsToBuild.add(LUMBERJACK);
buildingsToBuild.add(SAWMILL);
buildingsToBuild.add(LUMBERJACK);
buildingsToBuild.add(FORESTER);
buildingsToBuild.add(STONECUTTER);
buildingsToBuild.add(LUMBERJACK);
buildingsToBuild.add(LUMBERJACK);
buildingsToBuild.add(SAWMILL);
buildingsToBuild.add(FORESTER);
buildingsToBuild.add(STONECUTTER);
buildingsToBuild.add(STONECUTTER);
buildingsToBuild.add(STONECUTTER);
buildingsToBuild.add(WINEGROWER);
buildingsToBuild.add(FARM);
buildingsToBuild.add(FARM);
buildingsToBuild.add(FARM);
buildingsToBuild.add(TEMPLE);
buildingsToBuild.add(WATERWORKS);
buildingsToBuild.add(MILL);
buildingsToBuild.add(BAKER);
buildingsToBuild.add(BAKER);
buildingsToBuild.add(PIG_FARM);
buildingsToBuild.add(SLAUGHTERHOUSE);
buildingsToBuild.add(WATERWORKS);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(IRONMINE);
buildingsToBuild.add(IRONMELT);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(WEAPONSMITH);
buildingsToBuild.add(BARRACK);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(IRONMINE);
buildingsToBuild.add(IRONMELT);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(WEAPONSMITH);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(IRONMINE);
buildingsToBuild.add(IRONMELT);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(WEAPONSMITH);
buildingsToBuild.add(FISHER);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(GOLDMINE);
buildingsToBuild.add(GOLDMELT);
buildingsToBuild.add(FARM);
buildingsToBuild.add(FARM);
buildingsToBuild.add(FARM);
buildingsToBuild.add(WATERWORKS);
buildingsToBuild.add(MILL);
buildingsToBuild.add(BAKER);
buildingsToBuild.add(BAKER);
buildingsToBuild.add(PIG_FARM);
buildingsToBuild.add(WATERWORKS);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(IRONMINE);
buildingsToBuild.add(IRONMELT);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(WEAPONSMITH);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(IRONMINE);
buildingsToBuild.add(IRONMELT);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(WEAPONSMITH);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(IRONMINE);
buildingsToBuild.add(IRONMELT);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(WEAPONSMITH);
buildingsToBuild.add(BARRACK);
}
@Override
public void applyRules() {
destroyBuildings();
occupyTowers();
buildBuildings();
}
private void occupyTowers() {
for (ShortPoint2D towerPosition : aiStatistics.getBuildingPositionsOfTypeForPlayer(TOWER, playerId)) {
OccupyingBuilding tower = (OccupyingBuilding) aiStatistics.getBuildingAt(towerPosition);
if (tower.getStateProgress() == 1 && !tower.isOccupied()) {
ShortPoint2D door = tower.getDoor();
Movable soldier = aiStatistics.getNearestSwordsmanOf(door, playerId);
if (soldier != null && aiStatistics.getDistance(tower.getPos(), soldier.getPos()) > TOWER_SEARCH_RADIUS) {
sendMovableTo(soldier, door);
}
}
}
}
private void sendMovableTo(Movable movable, ShortPoint2D target) {
List<Integer> selectedIds = new ArrayList<Integer>();
if (movable != null) {
selectedIds.add(movable.getID());
taskScheduler.scheduleTask(new MoveToGuiTask(playerId, target, selectedIds));
}
}
private void destroyBuildings() {
// destroy stonecutters
List<ShortPoint2D> stones = aiStatistics.getStonesForPlayer(playerId);
for (ShortPoint2D stoneCutterPosition : aiStatistics.getBuildingPositionsOfTypeForPlayer(STONECUTTER, playerId)) {
ShortPoint2D nearestStone = aiStatistics.detectNearestPointFromList(stoneCutterPosition, stones);
if (nearestStone != null && aiStatistics.getDistance(stoneCutterPosition, nearestStone) > MAX_STONE_DISTANCE) {
aiStatistics.getBuildingAt(stoneCutterPosition).kill();
}
}
// TODO: destroy towers which are surrounded by other towers or are in direction of no other player
// TODO: destroy living houses to get material back
// TODO: destroy mines which have no resources anymore
}
private void buildBuildings() {
if (aiStatistics.getNumberOfNotFinishedBuildingsForPlayer(playerId) <= 4) {
if (buildLivingHouse())
return;
if (buildTower())
return;
if (buildStock())
return;
buildEconomy();
}
}
private boolean buildStock() {
if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(GOLDMELT, playerId) < 1) {
return false;
}
int stockCount = aiStatistics.getTotalNumberOfBuildingTypeForPlayer(STOCK, playerId);
int goldCount = aiStatistics.getNumberOfMaterialTypeForPlayer(GOLD, playerId);
if (stockCount * 6 * 8 - 32 < goldCount) {
return construct(STOCK);
}
return false;
}
private void buildEconomy() {
boolean toolsEconomyNeedsToBeChecked = true;
Map<EBuildingType, Integer> playerBuildingPlan = new HashMap<EBuildingType, Integer>();
for (EBuildingType currentBuildingType : buildingsToBuild) {
addBuildingCountToBuildingPlan(currentBuildingType, playerBuildingPlan);
System.out.println("build " + playerId
+ " " + currentBuildingType
+ " " + buildingNeedsToBeBuild(playerBuildingPlan, currentBuildingType)
+ " " + buildingDependenciesAreFulfilled(currentBuildingType)
+ " " + numberOfAvailableToolsForBuildingType(currentBuildingType)
+ " " + newBuildingWouldUseReservedTool(currentBuildingType)
);
if (buildingNeedsToBeBuild(playerBuildingPlan, currentBuildingType)
&& buildingDependenciesAreFulfilled(currentBuildingType)) {
int numberOfAvailableTools = numberOfAvailableToolsForBuildingType(currentBuildingType);
if (toolsEconomyNeedsToBeChecked && numberOfAvailableTools < 1) {
if (buildToolsEconomy()) {
return;
}
toolsEconomyNeedsToBeChecked = false;
}
if (numberOfAvailableTools >= 0 && !newBuildingWouldUseReservedTool(currentBuildingType)
&& construct(currentBuildingType)) {
return;
}
}
}
}
private boolean buildingDependenciesAreFulfilled(EBuildingType targetBuilding) {
boolean buildingDependenciesAreFulfilled = true;
for (BuildingCount neededBuilding : buildingNeeds.get(targetBuilding)) {
if (!unusedBuildingExists(neededBuilding.buildingType)) {
buildingDependenciesAreFulfilled = false;
}
}
return buildingDependenciesAreFulfilled;
}
private boolean unusedBuildingExists(EBuildingType me) {
float howOftenAmIUsed = 0;
for (EBuildingType buildingWhichNeedsMe : buildingIsNeededBy.get(me)) {
for (BuildingCount buildingCount : buildingNeeds.get(buildingWhichNeedsMe)) {
if (buildingCount.buildingType == me) {
howOftenAmIUsed = howOftenAmIUsed + buildingCount.count
* aiStatistics.getTotalNumberOfBuildingTypeForPlayer(buildingWhichNeedsMe, playerId);
}
}
}
return aiStatistics.getTotalNumberOfBuildingTypeForPlayer(me, playerId) >= howOftenAmIUsed;
}
private boolean buildToolsEconomy() {
if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(COALMINE, playerId) < 1) {
return construct(COALMINE);
}
if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(IRONMINE, playerId) < 1) {
return construct(IRONMINE);
}
if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(IRONMELT, playerId) < 1) {
return construct(IRONMELT);
}
if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(TOOLSMITH, playerId) < 1) {
return construct(TOOLSMITH);
}
return false;
}
private boolean buildingNeedsToBeBuild(Map<EBuildingType, Integer> playerBuildingPlan, EBuildingType currentBuildingType) {
int currentNumberOfBuildings = aiStatistics.getTotalNumberOfBuildingTypeForPlayer(currentBuildingType, playerId);
int targetNumberOfBuildings = playerBuildingPlan.get(currentBuildingType);
return currentNumberOfBuildings < targetNumberOfBuildings;
}
private void addBuildingCountToBuildingPlan(EBuildingType buildingType, Map<EBuildingType, Integer> playerBuildingPlan) {
if (!playerBuildingPlan.containsKey(buildingType)) {
playerBuildingPlan.put(buildingType, 0);
}
playerBuildingPlan.put(buildingType, playerBuildingPlan.get(buildingType) + 1);
}
private boolean buildTower() {
if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(STONECUTTER, playerId) >= 1
&& aiStatistics.getNumberOfNotOccupiedTowers(playerId) == 0) {
return construct(TOWER);
}
return false;
}
private boolean buildLivingHouse() {
int futureNumberOfBearers = aiStatistics.getMovablePositionsByTypeForPlayer(EMovableType.BEARER, playerId).size()
+ aiStatistics.getNumberOfNotFinishedBuildingTypesForPlayer(SMALL_LIVINGHOUSE, playerId) * 10
+ aiStatistics.getNumberOfNotFinishedBuildingTypesForPlayer(MEDIUM_LIVINGHOUSE, playerId) * 30
+ aiStatistics.getNumberOfNotFinishedBuildingTypesForPlayer(BIG_LIVINGHOUSE, playerId) * 100;
if (futureNumberOfBearers < 10 || aiStatistics.getNumberOfTotalBuildingsForPlayer(playerId) * 1.5 > futureNumberOfBearers) {
if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(STONECUTTER,
playerId) < 2 || aiStatistics.getTotalNumberOfBuildingTypeForPlayer(SAWMILL, playerId) < 1) {
return construct(SMALL_LIVINGHOUSE);
} else {
return construct(MEDIUM_LIVINGHOUSE);
}
}
return false;
}
private int numberOfAvailableToolsForBuildingType(EBuildingType buildingType) {
EMovableType movableType = buildingType.getWorkerType();
if (movableType == null) {
return Integer.MAX_VALUE;
}
EMaterialType materialType = movableType.getTool();
if (materialType == EMaterialType.NO_MATERIAL) {
return Integer.MAX_VALUE;
}
return aiStatistics.getNumberOfMaterialTypeForPlayer(materialType, playerId)
- aiStatistics.getNumberOfNotFinishedBuildingTypesForPlayer(buildingType, playerId)
- aiStatistics.getNumberOfUnoccupiedBuildingTypeForPlayer(buildingType, playerId);
}
private boolean construct(EBuildingType type) {
ShortPoint2D position = bestConstructionPositionFinderFactory
.getBestConstructionPositionFinderFor(type)
.findBestConstructionPosition(aiStatistics, mainGrid.getConstructionMarksGrid(), playerId);
if (position != null) {
taskScheduler.scheduleTask(new ConstructBuildingTask(EGuiAction.BUILD, playerId, position, type));
if (type == TOWER) {
Movable soldier = aiStatistics.getNearestSwordsmanOf(position, playerId);
if (soldier != null) {
sendMovableTo(soldier, position);
}
}
return true;
}
return false;
}
private boolean newBuildingWouldUseReservedTool(EBuildingType buildingType) {
EMovableType movableType = buildingType.getWorkerType();
if (movableType == null) {
return false;
}
EMaterialType materialType = movableType.getTool();
if (materialType == PICK) {
int numberOfCoalMines = aiStatistics.getTotalNumberOfBuildingTypeForPlayer(COALMINE, playerId);
int numberOfIronMines = aiStatistics.getTotalNumberOfBuildingTypeForPlayer(IRONMINE, playerId);
if (numberOfCoalMines >= 1 && numberOfIronMines >= 1) {
return false;
}
if (buildingType == COALMINE && numberOfCoalMines == 0) {
return false;
}
if (buildingType == IRONMINE && numberOfIronMines == 0) {
return false;
}
int requiredPicks = 1;
requiredPicks += aiStatistics.getNumberOfUnoccupiedBuildingTypeForPlayer(COALMINE, playerId);
requiredPicks += aiStatistics.getNumberOfUnoccupiedBuildingTypeForPlayer(IRONMINE, playerId);
requiredPicks += aiStatistics.getNumberOfUnoccupiedBuildingTypeForPlayer(STONECUTTER, playerId);
requiredPicks += aiStatistics.getNumberOfUnoccupiedBuildingTypeForPlayer(GOLDMINE, playerId);
if (numberOfCoalMines == 0) {
requiredPicks++;
}
if (numberOfIronMines == 0) {
requiredPicks++;
}
return aiStatistics.getNumberOfMaterialTypeForPlayer(PICK, playerId) < requiredPicks;
}
if (materialType == HAMMER) {
if (buildingType == TOOLSMITH || aiStatistics.getTotalNumberOfBuildingTypeForPlayer(TOOLSMITH, playerId) >= 1) {
return false;
}
int requiredPicks = 2 + aiStatistics.getNumberOfUnoccupiedBuildingTypeForPlayer(WEAPONSMITH, playerId);
return aiStatistics.getNumberOfMaterialTypeForPlayer(HAMMER, playerId) < requiredPicks;
}
return false;
}
} |
package com.alibaba.akita.proxy;
import com.alibaba.akita.annotation.*;
import com.alibaba.akita.exception.AkInvokeException;
import com.alibaba.akita.io.HttpInvoker;
import com.alibaba.akita.util.GsonUtil;
import com.alibaba.akita.util.JsonMapper;
import com.alibaba.akita.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.JsonProcessingException;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Dynamic Proxy Invocation Handler
* @author zhe.yangz 2011-12-28 04:47:56
*/
public class ProxyInvocationHandler implements InvocationHandler {
private static final String TAG = "ProxyInvocationHandler";
public Object bind(Class<?> clazz) {
Class<?>[] clazzs = {clazz};
Object newProxyInstance = Proxy.newProxyInstance(
clazz.getClassLoader(),
clazzs,
this);
return newProxyInstance;
}
/**
* Dynamic proxy invoke
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
AkPOST akPost = method.getAnnotation(AkPOST.class);
AkGET akGet = method.getAnnotation(AkGET.class);
AkAPI akApi = method.getAnnotation(AkAPI.class);
Annotation[][] annosArr = method.getParameterAnnotations();
String invokeUrl = akApi.url();
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
// AkApiParams to hashmap, filter out of null-value
HashMap<String, File> filesToSend = new HashMap<String, File>();
HashMap<String, String> paramsMapOri = new HashMap<String, String>();
HashMap<String, String> paramsMap =
getRawApiParams2HashMap(annosArr, args, filesToSend, paramsMapOri);
// Record this invocation
ApiInvokeInfo apiInvokeInfo = new ApiInvokeInfo();
apiInvokeInfo.apiName = method.getName();
apiInvokeInfo.paramsMap.putAll(paramsMapOri);
apiInvokeInfo.url = invokeUrl;
// parse '{}'s in url
invokeUrl = parseUrlbyParams(invokeUrl, paramsMap);
// cleared hashmap to params, and filter out of the null value
Iterator<Entry<String, String>> iter = paramsMap.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// get the signature string if using
AkSignature akSig = method.getAnnotation(AkSignature.class);
if (akSig != null) {
Class<?> clazzSignature = akSig.using();
if (clazzSignature.getInterfaces().length > 0 // TODO: NEED VERIFY WHEN I HAVE TIME
&& InvokeSignature.class.getName().equals(
clazzSignature.getInterfaces()[0].getName())) {
InvokeSignature is =
(InvokeSignature) clazzSignature.getConstructors()[0].newInstance();
String sigValue = is.signature(akSig, invokeUrl, params, paramsMapOri);
String sigParamName = is.getSignatureParamName();
if (sigValue != null && sigParamName != null
&& sigValue.length()>0 && sigParamName.length()>0 ) {
params.add(new BasicNameValuePair(sigParamName, sigValue));
}
}
}
// choose POST GET PUT DELETE to use for this invoke
String retString = "";
if (akGet != null) {
StringBuilder sbUrl = new StringBuilder(invokeUrl);
if (!(invokeUrl.endsWith("?") || invokeUrl.endsWith("&"))) {
sbUrl.append("?");
}
for (NameValuePair nvp : params) {
sbUrl.append(nvp.getName());
sbUrl.append("=");
sbUrl.append(nvp.getValue());
sbUrl.append("&");
} // now default using UTF-8, maybe improved later
retString = HttpInvoker.get(sbUrl.toString());
} else if (akPost != null) {
if (filesToSend.isEmpty()) {
retString = HttpInvoker.post(invokeUrl, params);
} else {
retString = HttpInvoker.postWithFilesUsingURLConnection(
invokeUrl, params, filesToSend);
}
} else { // use POST for default
retString = HttpInvoker.post(invokeUrl, params);
}
// invoked, then add to history
//ApiStats.addApiInvocation(apiInvokeInfo);
//Log.d(TAG, retString);
// parse the return-string
final Class<?> returnType = method.getReturnType();
try {
if (String.class.equals(returnType)) { // the result return raw string
return retString;
} else { // return object using json decode
AkJsonPaser akJsonPaser = method.getAnnotation(AkJsonPaser.class);
if (akJsonPaser != null && akJsonPaser.value() != null) {
if ("jackson".equals(akJsonPaser.value())) {
return JsonMapper.json2pojo(retString, returnType);
} else if ("gson".equals(akJsonPaser.value())) {
return GsonUtil.getGson().fromJson(retString, returnType);
} else {
return GsonUtil.getGson().fromJson(retString, returnType);
}
} else {
return GsonUtil.getGson().fromJson(retString, returnType);
}
}
} catch (Exception e) {
Log.e(TAG, retString, e); // log can print the error return-string
throw new AkInvokeException(AkInvokeException.CODE_JSONPROCESS_EXCEPTION,
e.getMessage(), e);
}
}
private String parseUrlbyParams(String url, HashMap<String, String> params)
throws AkInvokeException {
StringBuffer sbUrl = new StringBuffer();
Pattern pattern = Pattern.compile("\\{(.+?)\\}");
Matcher matcher = pattern.matcher(url);
while (matcher.find()) {
String paramValue = params.get(matcher.group(1));
if (paramValue != null) {
matcher.appendReplacement(sbUrl, paramValue);
} else { // {name}
throw new AkInvokeException(AkInvokeException.CODE_PARAM_IN_URL_NOT_FOUND,
"Parameter {"+matcher.group(1)+"}'s value not found of url "+url+".");
}
params.remove(matcher.group(1));
}
matcher.appendTail(sbUrl);
return sbUrl.toString();
}
/**
* AkApiParams to hashmap, filter out of null-value
*
* @param annosArr Method's params' annotation array[][]
* @param args Method's params' values
* @param filesToSend
* @return HashMap all (paramName -> paramValue)
*/
private HashMap<String, String> getRawApiParams2HashMap(Annotation[][] annosArr,
Object[] args,
HashMap<String, File> filesToSend,
HashMap<String, String> paramsMapOri) {
HashMap<String, String> paramsMap = new HashMap<String, String>();
for (int idx = 0; idx < args.length; idx++) {
String paramName = null;
String encode = "none";
for (Annotation a : annosArr[idx]) {
if(AkParam.class.equals(a.annotationType())){
AkParam ap = (AkParam)a;
paramName = ap.value();
encode = ap.encode();
}
}
if (paramName != null) {
Object arg = args[idx];
if (arg != null) { // filter out of null-value param
if ("$paramMap".equals(paramName)) {
Map<String, String> paramMap = (Map<String, String>)arg;
paramsMapOri.putAll(paramMap);
if (encode != null && !"none".equals(encode)) {
HashMap<String, String> encodedMap = new HashMap<String, String>();
for (Entry<String, String> entry : paramMap.entrySet()) {
try {
encodedMap.put(entry.getKey(),
URLEncoder.encode(entry.getValue(), encode));
} catch (Exception e) {
Log.w(TAG, "UnsupportedEncodingException:" + encode);
encodedMap.put(entry.getKey(), entry.getValue());
}
}
paramsMap.putAll(encodedMap);
} else {
paramsMap.putAll(paramMap);
}
} else if ("$filesToSend".equals(paramName)) {
if (arg instanceof Map) {
Map<String, File> files = (Map<String, File>)arg;
filesToSend.putAll(files);
}
} else if (encode != null && !"none".equals(encode)) {
try {
paramsMap.put(paramName, URLEncoder.encode(arg.toString(), encode));
} catch (UnsupportedEncodingException e) {
Log.w(TAG, "UnsupportedEncodingException:" + encode);
paramsMap.put(paramName, arg.toString());
}
paramsMapOri.put(paramName, arg.toString());
} else {
paramsMap.put(paramName, arg.toString());
paramsMapOri.put(paramName, arg.toString());
}
}
}
}
return paramsMap;
}
} |
package com.mapswithme.maps.editor.data;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.IntRange;
import android.text.format.DateFormat;
import com.mapswithme.maps.MwmApplication;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
public class HoursMinutes implements Parcelable
{
public final long hours;
public final long minutes;
public HoursMinutes(@IntRange(from = 0, to = 23) long hours, @IntRange(from = 0, to = 59) long minutes)
{
this.hours = hours;
this.minutes = minutes;
}
protected HoursMinutes(Parcel in)
{
hours = in.readLong();
minutes = in.readLong();
}
private boolean is24HourFormat() { return DateFormat.is24HourFormat(MwmApplication.get()); }
@Override
public String toString()
{
if (is24HourFormat())
return String.format(Locale.US, "%02d:%02d", hours, minutes);
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.HOUR_OF_DAY, (int)hours);
calendar.set(Calendar.MINUTE, (int)minutes);
SimpleDateFormat fmt12 = new SimpleDateFormat("hh:mm a");
return fmt12.format(calendar.getTime());
}
@Override
public int describeContents()
{
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeLong(hours);
dest.writeLong(minutes);
}
public static final Creator<HoursMinutes> CREATOR = new Creator<HoursMinutes>()
{
@Override
public HoursMinutes createFromParcel(Parcel in)
{
return new HoursMinutes(in);
}
@Override
public HoursMinutes[] newArray(int size)
{
return new HoursMinutes[size];
}
};
} |
package com.oney.WebRTCModule;
import android.app.Application;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.net.URISyntaxException;
import java.util.LinkedList;
import android.util.Base64;
import android.util.SparseArray;
import android.hardware.Camera;
import android.media.AudioManager;
import android.content.Context;
import android.view.Window;
import android.view.WindowManager;
import android.app.Activity;
import android.os.PowerManager;
import android.opengl.EGLContext;
import android.util.Log;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import org.webrtc.*;
public class WebRTCModule extends ReactContextBaseJavaModule {
private final static String TAG = WebRTCModule.class.getCanonicalName();
private static final String LANGUAGE = "language";
private PeerConnectionFactory mFactory;
private int mMediaStreamId = 0;
private int mMediaStreamTrackId = 0;
private final SparseArray<PeerConnection> mPeerConnections;
public final SparseArray<MediaStream> mMediaStreams;
public final SparseArray<MediaStreamTrack> mMediaStreamTracks;
private final SparseArray<DataChannel> mDataChannels;
private MediaConstraints pcConstraints = new MediaConstraints();
private VideoSource videoSource;
private VideoCapturerAndroid currentVideoCapturerAndroid;
public WebRTCModule(ReactApplicationContext reactContext) {
super(reactContext);
mPeerConnections = new SparseArray<PeerConnection>();
mMediaStreams = new SparseArray<MediaStream>();
mMediaStreamTracks = new SparseArray<MediaStreamTrack>();
mDataChannels = new SparseArray<DataChannel>();
pcConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
pcConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"));
pcConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
PeerConnectionFactory.initializeAndroidGlobals(reactContext, true, true, true);
mFactory = new PeerConnectionFactory();
}
@Override
public String getName() {
return "WebRTCModule";
}
private String getCurrentLanguage(){
Locale current = getReactApplicationContext().getResources().getConfiguration().locale;
return current.getLanguage();
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put(LANGUAGE, getCurrentLanguage());
return constants;
}
@ReactMethod
public void getLanguage(Callback callback){
String language = getCurrentLanguage();
System.out.println("The current language is "+language);
callback.invoke(null, language);
}
private void sendEvent(String eventName, @Nullable WritableMap params) {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
private List<PeerConnection.IceServer> createIceServers(ReadableArray iceServersArray) {
LinkedList<PeerConnection.IceServer> iceServers = new LinkedList<>();
for (int i = 0; i < iceServersArray.size(); i++) {
ReadableMap iceServerMap = iceServersArray.getMap(i);
boolean hasUsernameAndCredential = iceServerMap.hasKey("username") && iceServerMap.hasKey("credential");
if (iceServerMap.hasKey("url")) {
if (hasUsernameAndCredential) {
iceServers.add(new PeerConnection.IceServer(iceServerMap.getString("url"),iceServerMap.getString("username"), iceServerMap.getString("credential")));
} else {
iceServers.add(new PeerConnection.IceServer(iceServerMap.getString("url")));
}
} else if (iceServerMap.hasKey("urls")) {
switch (iceServerMap.getType("urls")) {
case String:
if (hasUsernameAndCredential) {
iceServers.add(new PeerConnection.IceServer(iceServerMap.getString("urls"),iceServerMap.getString("username"), iceServerMap.getString("credential")));
} else {
iceServers.add(new PeerConnection.IceServer(iceServerMap.getString("urls")));
}
break;
case Array:
ReadableArray urls = iceServerMap.getArray("urls");
for (int j = 0; j < urls.size(); j++) {
String url = urls.getString(j);
if (hasUsernameAndCredential) {
iceServers.add(new PeerConnection.IceServer(url,iceServerMap.getString("username"), iceServerMap.getString("credential")));
} else {
iceServers.add(new PeerConnection.IceServer(url));
}
}
break;
}
}
}
return iceServers;
}
@ReactMethod
public void peerConnectionInit(ReadableMap configuration, final int id){
List<PeerConnection.IceServer> iceServers = createIceServers(configuration.getArray("iceServers"));
PeerConnection peerConnection = mFactory.createPeerConnection(iceServers, pcConstraints, new PeerConnection.Observer() {
@Override
public void onSignalingChange(PeerConnection.SignalingState signalingState) {
WritableMap params = Arguments.createMap();
params.putInt("id", id);
params.putString("signalingState", signalingStateString(signalingState));
sendEvent("peerConnectionSignalingStateChanged", params);
}
@Override
public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
WritableMap params = Arguments.createMap();
params.putInt("id", id);
params.putString("iceConnectionState", iceConnectionStateString(iceConnectionState));
sendEvent("peerConnectionIceConnectionChanged", params);
}
@Override
public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {
Log.d(TAG, "onIceGatheringChangedwe" + iceGatheringState.name());
WritableMap params = Arguments.createMap();
params.putInt("id", id);
params.putString("iceGatheringState", iceGatheringStateString(iceGatheringState));
sendEvent("peerConnectionIceGatheringChanged", params);
}
@Override
public void onIceCandidate(final IceCandidate candidate) {
Log.d(TAG, "onIceCandidatewqerqwrsdfsd");
WritableMap params = Arguments.createMap();
params.putInt("id", id);
WritableMap candidateParams = Arguments.createMap();
candidateParams.putInt("sdpMLineIndex", candidate.sdpMLineIndex);
candidateParams.putString("sdpMid", candidate.sdpMid);
candidateParams.putString("candidate", candidate.sdp);
params.putMap("candidate", candidateParams);
sendEvent("peerConnectionGotICECandidate", params);
}
@Override
public void onAddStream(MediaStream mediaStream) {
mMediaStreamId++;
mMediaStreams.put(mMediaStreamId, mediaStream);
WritableMap params = Arguments.createMap();
params.putInt("id", id);
params.putInt("streamId", mMediaStreamId);
WritableArray tracks = Arguments.createArray();
for (int i = 0; i < mediaStream.videoTracks.size(); i++) {
VideoTrack track = mediaStream.videoTracks.get(i);
int mediaStreamTrackId = mMediaStreamTrackId++;
WritableMap trackInfo = Arguments.createMap();
trackInfo.putString("id", mediaStreamTrackId + "");
trackInfo.putString("label", "Video");
trackInfo.putString("kind", track.kind());
trackInfo.putBoolean("enabled", track.enabled());
trackInfo.putString("readyState", track.state().toString());
trackInfo.putBoolean("remote", true);
tracks.pushMap(trackInfo);
}
for (int i = 0; i < mediaStream.audioTracks.size(); i++) {
AudioTrack track = mediaStream.audioTracks.get(i);
int mediaStreamTrackId = mMediaStreamTrackId++;
WritableMap trackInfo = Arguments.createMap();
trackInfo.putString("id", mediaStreamTrackId + "");
trackInfo.putString("label", "Audio");
trackInfo.putString("kind", track.kind());
trackInfo.putBoolean("enabled", track.enabled());
trackInfo.putString("readyState", track.state().toString());
trackInfo.putBoolean("remote", true);
tracks.pushMap(trackInfo);
}
params.putArray("tracks", tracks);
sendEvent("peerConnectionAddedStream", params);
}
@Override
public void onRemoveStream(MediaStream mediaStream) {
if (mediaStream != null) {
int trackIndex;
int streamIndex;
for (int i = 0; i < mediaStream.videoTracks.size(); i++) {
VideoTrack track = mediaStream.videoTracks.get(i);
trackIndex = mMediaStreamTracks.indexOfValue(track);
while (trackIndex >= 0) {
mMediaStreamTracks.removeAt(trackIndex);
trackIndex = mMediaStreamTracks.indexOfValue(track);
}
}
for (int i = 0; i < mediaStream.audioTracks.size(); i++) {
AudioTrack track = mediaStream.audioTracks.get(i);
trackIndex = mMediaStreamTracks.indexOfValue(track);
while (trackIndex >= 0) {
mMediaStreamTracks.removeAt(trackIndex);
trackIndex = mMediaStreamTracks.indexOfValue(track);
}
}
streamIndex = mMediaStreams.indexOfValue(mediaStream);
if (streamIndex >= 0) {
mMediaStreams.removeAt(streamIndex);
}
}
}
@Override
public void onDataChannel(DataChannel dataChannel) {
}
@Override
public void onRenegotiationNeeded() {
WritableMap params = Arguments.createMap();
params.putInt("id", id);
sendEvent("peerConnectionOnRenegotiationNeeded", params);
}
@Override
public void onIceConnectionReceivingChange(boolean var1) {
}
});
mPeerConnections.put(id, peerConnection);
}
@ReactMethod
public void getUserMedia(ReadableMap constraints, Callback callback){
MediaStream mediaStream = mFactory.createLocalMediaStream("ARDAMS");
WritableArray tracks = Arguments.createArray();
if (constraints.hasKey("video")) {
ReadableType type = constraints.getType("video");
VideoSource videoSource = null;
MediaConstraints videoConstraints = new MediaConstraints();
switch (type) {
case Boolean:
boolean useVideo = constraints.getBoolean("video");
if (useVideo) {
String name = CameraEnumerationAndroid.getNameOfFrontFacingDevice();
VideoCapturerAndroid v = VideoCapturerAndroid.create(name, new VideoCapturerAndroid.CameraErrorHandler() {
@Override
public void onCameraError(String s) {
}
});
this.currentVideoCapturerAndroid = v;
videoSource = mFactory.createVideoSource(v, videoConstraints);
}
break;
case Map:
ReadableMap useVideoMap = constraints.getMap("video");
if (useVideoMap.hasKey("optional")) {
if (useVideoMap.getType("optional") == ReadableType.Array) {
ReadableArray options = useVideoMap.getArray("optional");
for (int i = 0; i < options.size(); i++) {
if (options.getType(i) == ReadableType.Map) {
ReadableMap option = options.getMap(i);
if (option.hasKey("sourceId") && option.getType("sourceId") == ReadableType.String) {
VideoCapturerAndroid v = getVideoCapturerById(Integer.parseInt(option.getString("sourceId")));
this.currentVideoCapturerAndroid = v;
videoSource = mFactory.createVideoSource(v, videoConstraints);
}
}
}
}
}
break;
}
// videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxHeight", Integer.toString(100)));
// videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxWidth", Integer.toString(100)));
// videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxFrameRate", Integer.toString(10)));
// videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("minFrameRate", Integer.toString(10)));
if (videoSource != null) {
VideoTrack videoTrack = mFactory.createVideoTrack("ARDAMSv0", videoSource);
int mediaStreamTrackId = mMediaStreamTrackId++;
mMediaStreamTracks.put(mediaStreamTrackId, videoTrack);
WritableMap trackInfo = Arguments.createMap();
trackInfo.putString("id", mediaStreamTrackId + "");
trackInfo.putString("label", "Video");
trackInfo.putString("kind", videoTrack.kind());
trackInfo.putBoolean("enabled", videoTrack.enabled());
trackInfo.putString("readyState", videoTrack.state().toString());
trackInfo.putBoolean("remote", false);
tracks.pushMap(trackInfo);
mediaStream.addTrack(videoTrack);
}
}
boolean useAudio = constraints.getBoolean("audio");
if (useAudio) {
MediaConstraints audioConstarints = new MediaConstraints();
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googNoiseSuppression", "true"));
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googEchoCancellation", "true"));
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("echoCancellation", "true"));
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googEchoCancellation2", "true"));
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googDAEchoCancellation", "true"));
AudioSource audioSource = mFactory.createAudioSource(audioConstarints);
AudioTrack audioTrack = mFactory.createAudioTrack("ARDAMSa0", audioSource);
int mediaStreamTrackId = mMediaStreamTrackId++;
mMediaStreamTracks.put(mediaStreamTrackId, audioTrack);
WritableMap trackInfo = Arguments.createMap();
trackInfo.putString("id", mediaStreamTrackId + "");
trackInfo.putString("label", "Audio");
trackInfo.putString("kind", audioTrack.kind());
trackInfo.putBoolean("enabled", audioTrack.enabled());
trackInfo.putString("readyState", audioTrack.state().toString());
trackInfo.putBoolean("remote", false);
tracks.pushMap(trackInfo);
mediaStream.addTrack(audioTrack);
}
Log.d(TAG, "mMediaStreamId: " + mMediaStreamId);
mMediaStreamId++;
mMediaStreams.put(mMediaStreamId, mediaStream);
callback.invoke(mMediaStreamId, tracks);
}
@ReactMethod
public void mediaStreamTrackGetSources(Callback callback){
WritableArray array = Arguments.createArray();
String[] names = new String[Camera.getNumberOfCameras()];
for(int i = 0; i < Camera.getNumberOfCameras(); ++i) {
WritableMap info = getCameraInfo(i);
if (info != null) {
array.pushMap(info);
}
}
WritableMap audio = Arguments.createMap();
audio.putString("label", "Audio");
audio.putString("id", "audio-1");
audio.putString("facing", "");
audio.putString("kind", "audio");
array.pushMap(audio);
callback.invoke(array);
}
@ReactMethod
public void mediaStreamTrackStop(final String id) {
final int trackId = Integer.parseInt(id);
MediaStreamTrack track = mMediaStreamTracks.get(trackId, null);
if (track == null) {
Log.d(TAG, "mediaStreamTrackStop() track is null");
return;
}
track.setEnabled(false);
track.setState(MediaStreamTrack.State.ENDED);
mMediaStreamTracks.remove(trackId);
// what exaclty `detached` means in doc?
// see: https://www.w3.org/TR/mediacapture-streams/#track-detached
}
@ReactMethod
public void mediaStreamTrackSetEnabled(final String id, final boolean enabled) {
final int trackId = Integer.parseInt(id);
MediaStreamTrack track = mMediaStreamTracks.get(trackId, null);
if (track == null) {
Log.d(TAG, "mediaStreamTrackSetEnabled() track is null");
return;
} else if (track.enabled() == enabled) {
return;
}
track.setEnabled(enabled);
}
@ReactMethod
public void mediaStreamTrackRelease(final int streamId, final String _trackId) {
// TODO: need to normalize streamId as a string ( spec wanted )
//final int streamId = Integer.parseInt(_streamId);
final int trackId = Integer.parseInt(_trackId);
MediaStream stream = mMediaStreams.get(streamId, null);
if (stream == null) {
Log.d(TAG, "mediaStreamTrackRelease() stream is null");
return;
}
MediaStreamTrack track = mMediaStreamTracks.get(trackId, null);
if (track == null) {
Log.d(TAG, "mediaStreamTrackRelease() track is null");
return;
}
track.setEnabled(false); // should we do this?
track.setState(MediaStreamTrack.State.ENDED); // should we do this?
mMediaStreamTracks.remove(trackId);
if (track.kind().equals("audio")) {
stream.removeTrack((AudioTrack)track);
} else if (track.kind().equals("video")) {
stream.removeTrack((VideoTrack)track);
}
}
public WritableMap getCameraInfo(int index) {
CameraInfo info = new CameraInfo();
try {
Camera.getCameraInfo(index, info);
} catch (Exception var3) {
Logging.e("CameraEnumerationAndroid", "getCameraInfo failed on index " + index, var3);
return null;
}
WritableMap params = Arguments.createMap();
String facing = info.facing == 1 ? "front" : "back";
params.putString("label", "Camera " + index + ", Facing " + facing + ", Orientation " + info.orientation);
params.putString("id", "" + index);
params.putString("facing", facing);
params.putString("kind", "video");
return params;
}
private VideoCapturerAndroid getVideoCapturerById(int id) {
String name = CameraEnumerationAndroid.getDeviceName(id);
if (name == null) {
name = CameraEnumerationAndroid.getNameOfFrontFacingDevice();
}
return VideoCapturerAndroid.create(name, new VideoCapturerAndroid.CameraErrorHandler() {
@Override
public void onCameraError(String s) {
}
});
}
private MediaConstraints defaultConstraints() {
MediaConstraints constraints = new MediaConstraints();
// TODO video media
constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"));
constraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
return constraints;
}
@ReactMethod
public void peerConnectionAddStream(final int streamId, final int id){
MediaStream mediaStream = mMediaStreams.get(streamId, null);
if (mediaStream == null) {
Log.d(TAG, "peerConnectionAddStream() mediaStream is null");
return;
}
PeerConnection peerConnection = mPeerConnections.get(id, null);
if (peerConnection != null) {
boolean result = peerConnection.addStream(mediaStream);
Log.d(TAG, "addStream" + result);
} else {
Log.d(TAG, "peerConnectionAddStream() peerConnection is null");
}
}
@ReactMethod
public void peerConnectionRemoveStream(final int streamId, final int id){
MediaStream mediaStream = mMediaStreams.get(streamId, null);
if (mediaStream == null) {
Log.d(TAG, "peerConnectionRemoveStream() mediaStream is null");
return;
}
PeerConnection peerConnection = mPeerConnections.get(id, null);
if (peerConnection != null) {
peerConnection.removeStream(mediaStream);
} else {
Log.d(TAG, "peerConnectionRemoveStream() peerConnection is null");
}
}
@ReactMethod
public void switchCameras() {
this.currentVideoCapturerAndroid.switchCamera(new VideoCapturerAndroid.CameraSwitchHandler() {
@Override
public void onCameraSwitchDone(boolean b) {
Log.d("SWITCHCAMERA", "Successfully Switched Cameras");
}
@Override
public void onCameraSwitchError(String s) {
Log.d("SWITCHCAMERA", "There was an error switching cameras");
}
});
}
@ReactMethod
public void toggleMute() {
Log.d("INTOGGLEMUTE", mMediaStreams.get(1).toString());
MediaStream mediaStream = mMediaStreams.get(1);
LinkedList<AudioTrack> audioTracks = mediaStream.audioTracks;
for (AudioTrack aAudioTrack : audioTracks) {
if (aAudioTrack.enabled()) {
aAudioTrack.setEnabled(false);
} else {
aAudioTrack.setEnabled(true);
}
}
}
@ReactMethod
public void toggleCamera() {
Log.d("INTOGGLECAMERA", mMediaStreams.get(1).toString());
MediaStream mediaStream = mMediaStreams.get(1);
LinkedList<VideoTrack> videoTracks = mediaStream.videoTracks;
boolean isCameraEnabled = false;
for (VideoTrack aVideoTrack : videoTracks) {
if (aVideoTrack.enabled()) {
aVideoTrack.setEnabled(false);
} else {
aVideoTrack.setEnabled(true);
}
}
}
*//*MediaConstraints mediaConstraints = new MediaConstraints();
peerConnection.createOffer();*//*
/*public static void testChangeBandwidthResolution(int bandWidth) {
if (mPeerConnections != null) {
final PeerConnection peerConnection = mPeerConnections.get(0);
if (peerConnection != null) {
SessionDescription oldLocalDescription = peerConnection.getLocalDescription();
SessionDescription oldRemoteDescription = peerConnection.getRemoteDescription();
StringBuilder sbLocal = null;
StringBuilder sbRemote = null;
if (oldLocalDescription != null) {
String stringOldLocalDescription = oldLocalDescription.description;
sbLocal = new StringBuilder(stringOldLocalDescription);
int indexOfLocalVideo = sbLocal.indexOf("m=video");
int indexOfLocalFirstA = sbLocal.indexOf("a=rtcp", indexOfLocalVideo);
if (!stringOldLocalDescription.contains("b=AS")) {
sbLocal.insert(indexOfLocalFirstA, "b=AS:" + bandWidth + "\n"
+ "b=RS:800 \n"
+ "b=RR:2400 \n");
}
}
if (oldRemoteDescription != null) {
Log.d("OLD_REMOTE_SDP", oldRemoteDescription.description);
String stringOldRemoteDescription = oldRemoteDescription.description;
sbRemote = new StringBuilder(stringOldRemoteDescription);
int indexOfRemoteVideo = sbRemote.indexOf("m=video");
int indexOfRemoteFirstA = sbRemote.indexOf("a=rtcp", indexOfRemoteVideo);
if (!stringOldRemoteDescription.contains("b=AS")) {
sbRemote.insert(indexOfRemoteFirstA, "b=AS:" + bandWidth + "\n"
+ "b=RS:800 \n"
+ "b=RR:2400 \n");
}
}
if (sbLocal != null && sbRemote != null) {
final SessionDescription newLocalDescription = new SessionDescription(SessionDescription.Type.OFFER, sbLocal.toString());
final SessionDescription newRemoteDescription = new SessionDescription(SessionDescription.Type.ANSWER, sbRemote.toString());
peerConnection.setLocalDescription(new SdpObserver() {
@Override
public void onCreateSuccess(SessionDescription sessionDescription) {
}
@Override
public void onSetSuccess() {
Log.d("NEW_AFTER_LOCAL_SDP", newLocalDescription.description);
peerConnection.setRemoteDescription(new SdpObserver() {
@Override
public void onCreateSuccess(SessionDescription sessionDescription) {
}
@Override
public void onSetSuccess() {
Log.d("NEW_AFTER_REMOTE_SDP", newRemoteDescription.description);
}
@Override
public void onCreateFailure(String s) {
}
@Override
public void onSetFailure(String s) {
}
}, newRemoteDescription);
}
@Override
public void onCreateFailure(String s) {
}
@Override
public void onSetFailure(String s) {
}
}, newLocalDescription);
}
}
}
mediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("audio",Boolean.toString(Boolean.TRUE)));
mediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("minHeight", Integer.toString(240)));
mediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxHeight", Integer.toString(1080)));
mediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("minWidth", Integer.toString(426)));
mediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxWidth", Integer.toString(1920)));
mediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("minFrameRate", Integer.toString(30)));
mediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxFrameRate", Integer.toString(30)));
}*/
@ReactMethod
public void peerConnectionCreateOffer(final int id, final Callback callback) {
PeerConnection peerConnection = mPeerConnections.get(id, null);
// MediaConstraints constraints = new MediaConstraints();
// constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
// constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
Log.d(TAG, "RTCPeerConnectionCreateOfferWithObjectID start");
if (peerConnection != null) {
peerConnection.createOffer(new SdpObserver() {
@Override
public void onCreateSuccess(final SessionDescription sdp) {
WritableMap params = Arguments.createMap();
params.putString("type", sdp.type.canonicalForm());
params.putString("sdp", sdp.description);
callback.invoke(true, params);
}
@Override
public void onSetSuccess() {}
@Override
public void onCreateFailure(String s) {
callback.invoke(false, s);
}
@Override
public void onSetFailure(String s) {}
}, pcConstraints);
} else {
Log.d(TAG, "peerConnectionCreateOffer() peerConnection is null");
callback.invoke(false, "peerConnection is null");
}
Log.d(TAG, "RTCPeerConnectionCreateOfferWithObjectID end");
}
@ReactMethod
public void peerConnectionCreateAnswer(final int id, final Callback callback) {
PeerConnection peerConnection = mPeerConnections.get(id, null);
// MediaConstraints constraints = new MediaConstraints();
// constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
// constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
Log.d(TAG, "RTCPeerConnectionCreateAnswerWithObjectID start");
if (peerConnection != null) {
peerConnection.createAnswer(new SdpObserver() {
@Override
public void onCreateSuccess(final SessionDescription sdp) {
WritableMap params = Arguments.createMap();
params.putString("type", sdp.type.canonicalForm());
params.putString("sdp", sdp.description);
callback.invoke(true, params);
}
@Override
public void onSetSuccess() {
}
@Override
public void onCreateFailure(String s) {
callback.invoke(false, s);
}
@Override
public void onSetFailure(String s) {
}
}, pcConstraints);
} else {
Log.d(TAG, "peerConnectionCreateAnswer() peerConnection is null");
callback.invoke(false, "peerConnection is null");
}
Log.d(TAG, "RTCPeerConnectionCreateAnswerWithObjectID end");
}
@ReactMethod
public void peerConnectionSetLocalDescription(ReadableMap sdpMap, final int id, final Callback callback) {
PeerConnection peerConnection = mPeerConnections.get(id, null);
Log.d(TAG, "peerConnectionSetLocalDescription() start");
if (peerConnection != null) {
SessionDescription sdp = new SessionDescription(
SessionDescription.Type.fromCanonicalForm(sdpMap.getString("type")),
sdpMap.getString("sdp")
);
peerConnection.setLocalDescription(new SdpObserver() {
@Override
public void onCreateSuccess(final SessionDescription sdp) {
}
@Override
public void onSetSuccess() {
callback.invoke(true);
}
@Override
public void onCreateFailure(String s) {
}
@Override
public void onSetFailure(String s) {
callback.invoke(false, s);
}
}, sdp);
} else {
Log.d(TAG, "peerConnectionSetLocalDescription() peerConnection is null");
callback.invoke(false, "peerConnection is null");
}
Log.d(TAG, "peerConnectionSetLocalDescription() end");
}
@ReactMethod
public void peerConnectionSetRemoteDescription(final ReadableMap sdpMap, final int id, final Callback callback) {
PeerConnection peerConnection = mPeerConnections.get(id, null);
// final String d = sdpMap.getString("type");
Log.d(TAG, "peerConnectionSetRemoteDescription() start");
if (peerConnection != null) {
SessionDescription sdp = new SessionDescription(
SessionDescription.Type.fromCanonicalForm(sdpMap.getString("type")),
sdpMap.getString("sdp")
);
peerConnection.setRemoteDescription(new SdpObserver() {
@Override
public void onCreateSuccess(final SessionDescription sdp) {
}
@Override
public void onSetSuccess() {
callback.invoke(true);
}
@Override
public void onCreateFailure(String s) {
}
@Override
public void onSetFailure(String s) {
callback.invoke(false, s);
}
}, sdp);
} else {
Log.d(TAG, "peerConnectionSetRemoteDescription() peerConnection is null");
callback.invoke(false, "peerConnection is null");
}
Log.d(TAG, "peerConnectionSetRemoteDescription() end");
}
@ReactMethod
public void peerConnectionAddICECandidate(ReadableMap candidateMap, final int id, final Callback callback) {
boolean result = false;
PeerConnection peerConnection = mPeerConnections.get(id, null);
Log.d(TAG, "peerConnectionAddICECandidate() start");
if (peerConnection != null) {
IceCandidate candidate = new IceCandidate(
candidateMap.getString("sdpMid"),
candidateMap.getInt("sdpMLineIndex"),
candidateMap.getString("candidate")
);
result = peerConnection.addIceCandidate(candidate);
} else {
Log.d(TAG, "peerConnectionAddICECandidate() peerConnection is null");
}
callback.invoke(result);
Log.d(TAG, "peerConnectionAddICECandidate() end");
}
@ReactMethod
public void peerConnectionClose(final int id) {
PeerConnection peerConnection = mPeerConnections.get(id, null);
if (peerConnection != null) {
peerConnection.close();
mPeerConnections.remove(id);
} else {
Log.d(TAG, "peerConnectionClose() peerConnection is null");
}
resetAudio();
}
@ReactMethod
public void mediaStreamRelease(final int id) {
MediaStream mediaStream = mMediaStreams.get(id, null);
if (mediaStream != null) {
int trackIndex;
for (int i = 0; i < mediaStream.videoTracks.size(); i++) {
VideoTrack track = mediaStream.videoTracks.get(i);
trackIndex = mMediaStreamTracks.indexOfValue(track);
while (trackIndex >= 0) {
mMediaStreamTracks.removeAt(trackIndex);
trackIndex = mMediaStreamTracks.indexOfValue(track);
}
}
for (int i = 0; i < mediaStream.audioTracks.size(); i++) {
AudioTrack track = mediaStream.audioTracks.get(i);
trackIndex = mMediaStreamTracks.indexOfValue(track);
while (trackIndex >= 0) {
mMediaStreamTracks.removeAt(trackIndex);
trackIndex = mMediaStreamTracks.indexOfValue(track);
}
}
mMediaStreams.remove(id);
} else {
Log.d(TAG, "mediaStreamRelease() mediaStream is null");
}
}
private void resetAudio() {
AudioManager audioManager = (AudioManager)getReactApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(true);
audioManager.setMode(AudioManager.MODE_NORMAL);
}
@ReactMethod
public void setAudioOutput(String output) {
AudioManager audioManager = (AudioManager)getReactApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(output.equals("speaker"));
}
@ReactMethod
public void setKeepScreenOn(final boolean isOn) {
UiThreadUtil.runOnUiThread(new Runnable() {
public void run() {
Window window = getCurrentActivity().getWindow();
if (isOn) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
});
}
@ReactMethod
public void setProximityScreenOff(boolean enabled) {
// TODO
/*
PowerManager powerManager = (PowerManager)getReactApplicationContext().getSystemService(Context.POWER_SERVICE);
if (powerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) {
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
wakeLock.setReferenceCounted(false);
} else {
}*/
}
@ReactMethod
public void dataChannelInit(final int peerConnectionId, final int dataChannelId, String label, ReadableMap config) {
PeerConnection peerConnection = mPeerConnections.get(peerConnectionId, null);
if (peerConnection != null) {
DataChannel.Init init = new DataChannel.Init();
init.id = dataChannelId;
if (config != null) {
if (config.hasKey("ordered")) {
init.ordered = config.getBoolean("ordered");
}
if (config.hasKey("maxRetransmitTime")) {
init.maxRetransmitTimeMs = config.getInt("maxRetransmitTime");
}
if (config.hasKey("maxRetransmits")) {
init.maxRetransmits = config.getInt("maxRetransmits");
}
if (config.hasKey("protocol")) {
init.protocol = config.getString("protocol");
}
if (config.hasKey("negotiated")) {
init.ordered = config.getBoolean("negotiated");
}
}
DataChannel dataChannel = peerConnection.createDataChannel(label, init);
mDataChannels.put(dataChannelId, dataChannel);
} else {
Log.d(TAG, "dataChannelInit() peerConnection is null");
}
}
@ReactMethod
public void dataChannelSend(final int dataChannelId, String data, String type) {
DataChannel dataChannel = mDataChannels.get(dataChannelId, null);
if (dataChannel != null) {
byte[] byteArray;
if (type.equals("text")) {
try {
byteArray = data.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.d(TAG, "Could not encode text string as UTF-8.");
return;
}
} else if (type.equals("binary")) {
byteArray = Base64.decode(data, Base64.NO_WRAP);
} else {
Log.e(TAG, "Unsupported data type: " + type);
return;
}
ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
DataChannel.Buffer buffer = new DataChannel.Buffer(byteBuffer, type.equals("binary"));
dataChannel.send(buffer);
} else {
Log.d(TAG, "dataChannelSend() dataChannel is null");
}
}
@ReactMethod
public void dataChannelClose(final int dataChannelId) {
DataChannel dataChannel = mDataChannels.get(dataChannelId, null);
if (dataChannel != null) {
dataChannel.close();
mDataChannels.remove(dataChannelId);
} else {
Log.d(TAG, "dataChannelClose() dataChannel is null");
}
}
@Nullable
public String iceConnectionStateString(PeerConnection.IceConnectionState iceConnectionState) {
switch (iceConnectionState) {
case NEW:
return "new";
case CHECKING:
return "checking";
case CONNECTED:
return "connected";
case COMPLETED:
return "completed";
case FAILED:
return "failed";
case DISCONNECTED:
return "disconnected";
case CLOSED:
return "closed";
}
return null;
}
@Nullable
public String signalingStateString(PeerConnection.SignalingState signalingState) {
switch (signalingState) {
case STABLE:
return "stable";
case HAVE_LOCAL_OFFER:
return "have-local-offer";
case HAVE_LOCAL_PRANSWER:
return "have-local-pranswer";
case HAVE_REMOTE_OFFER:
return "have-remote-offer";
case HAVE_REMOTE_PRANSWER:
return "have-remote-pranswer";
case CLOSED:
return "closed";
}
return null;
}
@Nullable
public String iceGatheringStateString(PeerConnection.IceGatheringState iceGatheringState) {
switch (iceGatheringState) {
case NEW:
return "new";
case GATHERING:
return "gathering";
case COMPLETE:
return "complete";
}
return null;
}
@Nullable
public String dataChannelStateString(DataChannel.State dataChannelState) {
switch (dataChannelState) {
case CONNECTING:
return "connecting";
case OPEN:
return "open";
case CLOSING:
return "closing";
case CLOSED:
return "closed";
}
return null;
}
} |
package com.pilloxa.dfu;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNNordicDfuPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new RNNordicDfuModule(reactContext));
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
} |
package org.anyline.util;
import org.anyline.entity.MapLocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
public class DistanceUtil {
private static final Logger log = LoggerFactory.getLogger(DistanceUtil.class);
private static double EARTH_RADIUS = 6378.137;
private static double rad(double d) {
return d * Math.PI / 180.0;
}
/**
* (:)
*
* @param lat1 lat1
* @param lon1 lon1
* @param lat2 lat2
* @param lon2 lon2
* @return distance
*/
public static double distance(double lon1, double lat1, double lon2, double lat2) {
try{
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lon1) - rad(lon2);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
+ Math.cos(radLat1) * Math.cos(radLat2)
* Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = Math.round(s * 10000d) / 10000d;
s = s * 1000;
BigDecimal decimal = new BigDecimal(s);
s = decimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
return s;
}catch(Exception e){
e.printStackTrace();
return -1;
}
}
public static String distanceFormat(double lon1, double lat1, double lon2, double lat2) {
double distance = distance(lon1, lat1, lon2, lat2);
return distanceFormat(distance);
}
public static String distanceFormatCn(double lon1, double lat1, double lon2, double lat2) {
double distance = distance(lon1, lat1, lon2, lat2);
return distanceFormatCn(distance);
}
public static double distance(String lon1, String lat1, String lon2, String lat2) {
double distance = -1;
try{
distance = distance(
BasicUtil.parseDouble(lon1, -1.0),
BasicUtil.parseDouble(lat1, -1.0),
BasicUtil.parseDouble(lon2, -1.0),
BasicUtil.parseDouble(lat2, -1.0)
);
}catch(Exception e){
e.printStackTrace();
}
return distance;
}
public static String distanceFormat(String lon1, String lat1, String lon2, String lat2) {
double distance = distance(lon1, lat1, lon2, lat2);
return distanceFormat(distance);
}
public static String distanceFormatCn(String lon1, String lat1, String lon2, String lat2) {
double distance = distance(lon1, lat1, lon2, lat2);
return distanceFormatCn(distance);
}
public static double distance(MapLocation loc1, MapLocation loc2) {
double distance = -1;
try{
distance = distance(
BasicUtil.parseDouble(loc1.getLng(), -1.0),
BasicUtil.parseDouble(loc1.getLat(), -1.0),
BasicUtil.parseDouble(loc2.getLng(), -1.0),
BasicUtil.parseDouble(loc2.getLat(), -1.0)
);
}catch(Exception e){
e.printStackTrace();
}
return distance;
}
public static String distanceFormat(MapLocation loc1, MapLocation loc2) {
double distance = distance(loc1.getLng(), loc1.getLat(), loc2.getLng(), loc2.getLat());
return distanceFormat(distance);
}
public static String distanceFormatCn(MapLocation loc1, MapLocation loc2) {
double distance = distance(loc1.getLng(), loc1.getLat(), loc2.getLng(), loc2.getLat());
return distanceFormatCn(distance);
}
public static String distanceFormat(double distance){
String result = distance+"m";
if(distance > 1000){
result = NumberUtil.format(distance/1000,"0.00") +"km";
}
return result;
}
public static String distanceFormatCn(double distance){
String result = distance+"";
if(distance > 1000){
result = NumberUtil.format(distance/1000,"0.00") +"";
}
return result;
}
/**
* gps
* @param gps gps
* @return String
*/
public static String parseGPS(String gps){
String result = null;
if(null == gps){
return null;
}
gps = gps.replaceAll("[^0-9.]", "");
String d = gps.substring(0, gps.indexOf("."));
String m = "";
int idx = d.length() - 2;
d = gps.substring(0,idx);
m = gps.substring(idx);
BigDecimal dd = BasicUtil.parseDecimal(d, 0d);
BigDecimal dm = BasicUtil.parseDecimal(m, 0d).divide(new BigDecimal(60), 7, BigDecimal.ROUND_UP);
result = dd.add(dm).toString();
return result;
}
} |
package com.intuit.karate.core;
import com.intuit.karate.StringUtils;
/**
* someday this will be part of the parser, but until then apologies for this
* monstrosity :|
*
* @author pthomas3
*/
public class MatchStep {
public final String name;
public final String path;
public final MatchType type;
public final String expected;
public MatchStep(String raw) {
boolean each = false;
raw = raw.trim();
if (raw.startsWith("each")) {
each = true;
raw = raw.substring(4).trim();
}
boolean contains = false;
boolean not = false;
boolean only = false;
boolean any = false;
int spacePos = raw.indexOf(' ');
int leftParenPos = raw.indexOf('(');
int rightParenPos = raw.indexOf(')');
int lhsEndPos = raw.indexOf(" contains");
if (lhsEndPos == -1) {
lhsEndPos = raw.indexOf(" !contains");
}
int searchPos = 0;
int eqPos = raw.indexOf("==");
if (eqPos == -1) {
eqPos = raw.indexOf("!=");
}
if (lhsEndPos != -1 && (eqPos == -1 || eqPos > lhsEndPos)) {
contains = true;
not = raw.charAt(lhsEndPos + 1) == '!';
searchPos = lhsEndPos + (not ? 10 : 9);
String anyOrOnly = raw.substring(searchPos).trim();
if (anyOrOnly.startsWith("only")) {
int onlyPos = raw.indexOf(" only", searchPos);
only = true;
searchPos = onlyPos + 5;
} else if (anyOrOnly.startsWith("any")) {
int anyPos = raw.indexOf(" any", searchPos);
any = true;
searchPos = anyPos + 4;
}
} else {
int equalPos = raw.indexOf(" ==", searchPos);
int notEqualPos = raw.indexOf(" !=", searchPos);
if (equalPos == -1 && notEqualPos == -1) {
throw new RuntimeException("syntax error, expected '==' for match");
}
lhsEndPos = min(equalPos, notEqualPos);
if (lhsEndPos > spacePos && rightParenPos != -1 && rightParenPos > lhsEndPos) {
equalPos = raw.indexOf(" ==", rightParenPos);
notEqualPos = raw.indexOf(" !=", rightParenPos);
if (equalPos == -1 && notEqualPos == -1) {
throw new RuntimeException("syntax error, expected '==' for match");
}
lhsEndPos = min(equalPos, notEqualPos);
}
not = lhsEndPos == notEqualPos;
searchPos = lhsEndPos + 3;
}
String lhs = raw.substring(0, lhsEndPos).trim();
if (leftParenPos == -1) {
leftParenPos = lhs.indexOf('[');
}
if (spacePos != -1 && (leftParenPos > spacePos || leftParenPos == -1)) {
name = lhs.substring(0, spacePos);
path = StringUtils.trimToNull(lhs.substring(spacePos));
} else {
name = lhs;
path = null;
}
expected = StringUtils.trimToNull(raw.substring(searchPos));
type = getType(each, not, contains, only, any);
}
private static int min(int a, int b) {
if (a == -1) {
return b;
}
if (b == -1) {
return a;
}
return Math.min(a, b);
}
private static MatchType getType(boolean each, boolean not, boolean contains, boolean only, boolean any) {
if (each) {
if (contains) {
if (only) {
return MatchType.EACH_CONTAINS_ONLY;
}
if (any) {
return MatchType.EACH_CONTAINS_ANY;
}
return not ? MatchType.EACH_NOT_CONTAINS : MatchType.EACH_CONTAINS;
}
return not ? MatchType.EACH_NOT_EQUALS : MatchType.EACH_EQUALS;
}
if (contains) {
if (only) {
return MatchType.CONTAINS_ONLY;
}
if (any) {
return MatchType.CONTAINS_ANY;
}
return not ? MatchType.NOT_CONTAINS : MatchType.CONTAINS;
}
return not ? MatchType.NOT_EQUALS : MatchType.EQUALS;
}
} |
package org.jgrapes.http.events;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Stack;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpProtocol;
import org.jdrupes.httpcodec.protocols.http.HttpRequest;
import org.jgrapes.core.Channel;
import org.jgrapes.core.CompletionEvent;
import org.jgrapes.core.Components;
import org.jgrapes.http.ResourcePattern;
import org.jgrapes.http.ResourcePattern.PathSpliterator;
import org.jgrapes.net.TcpChannel;
/**
* The base class for all HTTP requests such as {@link Request.In.Get},
* {@link Request.In.Post} etc.
*
* @param <R> the generic type
*/
public class Request<R> extends MessageReceived<R> {
/**
* @param channels
*/
protected Request(Channel... channels) {
super(channels);
}
/**
* The base class for all incoming HTTP requests. Incoming
* request flow downstream and are served by the framework.
*
* A result of `true` indicates that the request has been processed,
* i.e. a response has been sent or will sent.
*/
@SuppressWarnings("PMD.ShortClassName")
public static class In extends Request<Boolean> {
@SuppressWarnings("PMD.AvoidFieldNameMatchingTypeName")
private final HttpRequest request;
private final int matchLevels;
private final MatchValue matchValue;
private final URI resourceUri;
private URI uri;
/**
* Creates a new request event with the associated {@link Completed}
* event.
*
* @param protocol the protocol as reported by {@link #requestUri()}
* @param request the request data
* @param matchLevels the number of elements from the request path
* to use in the match value (see {@link #matchValue})
* @param channels the channels associated with this event
* @throws URISyntaxException
*/
@SuppressWarnings({ "PMD.UselessParentheses",
"PMD.ConstructorCallsOverridableMethod" })
public In(String protocol, HttpRequest request,
int matchLevels, Channel... channels)
throws URISyntaxException {
super(channels);
new Completed(this);
this.request = request;
this.matchLevels = matchLevels;
// Do any required request specific processing of the original
// request URI
URI requestUri = effectiveRequestUri(protocol, request);
// Clean the request URI's path, keeping the segments for matchValue
List<String> segs = pathToSegs(requestUri);
requestUri = new URI(requestUri.getScheme(),
requestUri.getUserInfo(), requestUri.getHost(),
requestUri.getPort(),
"/" + segs.stream().collect(Collectors.joining("/")),
requestUri.getQuery(), null);
setRequestUri(requestUri);
// The URI for handler selection ignores user info and query
resourceUri = new URI(requestUri.getScheme(), null,
requestUri.getHost(), requestUri.getPort(),
requestUri.getPath(), null, null);
@SuppressWarnings("PMD.InefficientStringBuffering")
StringBuilder matchPath = new StringBuilder("/" + segs.stream()
.limit(matchLevels).collect(Collectors.joining("/")));
if (segs.size() > matchLevels) {
if (!matchPath.toString().endsWith("/")) {
matchPath.append('/');
}
matchPath.append('…');
}
matchValue = new MatchValue(getClass(),
(requestUri.getScheme() == null ? ""
: (requestUri.getScheme() + ":
+ (requestUri.getHost() == null ? ""
: (requestUri.getHost()
+ (requestUri.getPort() == -1 ? ""
: (":" + requestUri.getPort()))))
+ matchPath);
}
private List<String> pathToSegs(URI requestUri)
throws URISyntaxException {
Iterator<String> origSegs = PathSpliterator.stream(
requestUri.getPath()).iterator();
// Path must not be empty and must be absolute
if (!origSegs.hasNext() || !origSegs.next().isEmpty()) {
throw new URISyntaxException(
requestUri().getPath(), "Must be absolute");
}
// Remove dot segments and check for "...//..."
Stack<String> segs = new Stack<>();
while (origSegs.hasNext()) {
if (!segs.isEmpty() && segs.peek().isEmpty()) {
// Empty segment followed by more means "//"
segs.clear();
}
String seg = origSegs.next();
if (".".equals(seg)) {
continue;
}
if ("..".equals(seg)) {
if (!segs.isEmpty()) {
segs.pop();
}
continue;
}
segs.push(seg);
}
return segs;
}
/**
* Builds the URI that represents this request. The default
* implementation checks that request URI in the HTTP request
* is directed at this server as specified in the "Host"-header
* and adds the protocol, host and port if not specified
* in the request URI.
*
* @param protocol the protocol
* @param request the request
* @return the URI
* @throws URISyntaxException if the request is not acceptable
*/
protected URI effectiveRequestUri(String protocol, HttpRequest request)
throws URISyntaxException {
URI serverUri = new URI(protocol, null,
request.host(), request.port(), "/", null, null);
URI origRequest = request.requestUri();
URI result = serverUri.resolve(new URI(null, null, null, -1,
origRequest.getPath(), origRequest.getQuery(), null));
if (!result.getScheme().equals(protocol)
|| !result.getHost().equals(request.host())
|| result.getPort() != request.port()) {
throw new URISyntaxException(origRequest.toString(),
"Scheme, host or port not allowed");
}
return result;
}
/**
* Creates the appropriate derived request event type from
* a given {@link HttpRequest}.
*
* @param request the HTTP request
* @param secure whether the request was received over a secure channel
* @param matchLevels the match levels
* @return the request event
* @throws URISyntaxException
*/
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public static In fromHttpRequest(
HttpRequest request, boolean secure, int matchLevels)
throws URISyntaxException {
switch (request.method()) {
case "OPTIONS":
return new Options(request, secure, matchLevels);
case "GET":
return new Get(request, secure, matchLevels);
case "HEAD":
return new Head(request, secure, matchLevels);
case "POST":
return new Post(request, secure, matchLevels);
case "PUT":
return new Put(request, secure, matchLevels);
case "DELETE":
return new Delete(request, secure, matchLevels);
case "TRACE":
return new Trace(request, secure, matchLevels);
case "CONNECT":
return new Connect(request, secure, matchLevels);
default:
return new In(secure ? "https" : "http", request, matchLevels);
}
}
/**
* Sets the request URI.
*
* @param uri the new request URI
*/
protected final void setRequestUri(URI uri) {
this.uri = uri;
}
/**
* Returns an absolute URI of the request. For incoming requests, the
* URI is built from the information provided by the decoder.
*
* @return the URI
*/
public final URI requestUri() {
return uri;
}
/**
* Returns the "raw" request as provided by the HTTP decoder.
*
* @return the request
*/
public HttpRequest httpRequest() {
return request;
}
/**
* The match value consists of the event class and a URI.
* The URI is similar to the request URI but its path elements
* are shortened as specified in the constructor.
*
* The match value is used as key in a map that speeds up
* the lookup of handlers. Having the complete URI in the match
* value would inflate this map.
*
* @return the object
* @see org.jgrapes.core.Event#defaultCriterion()
*/
@Override
public Object defaultCriterion() {
return matchValue;
}
/*
* (non-Javadoc)
*
* @see org.jgrapes.core.Event#isMatchedBy(java.lang.Object)
*/
@Override
public boolean isEligibleFor(Object value) {
if (!(value instanceof MatchValue)) {
return super.isEligibleFor(value);
}
MatchValue mval = (MatchValue) value;
if (!mval.type.isAssignableFrom(matchValue.type)) {
return false;
}
if (mval.resource instanceof ResourcePattern) {
return ((ResourcePattern) mval.resource).matches(resourceUri,
matchLevels) >= 0;
}
return mval.resource.equals(matchValue.resource);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
@SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(Components.objectName(this))
.append(" [\"");
String path = Optional.ofNullable(request.requestUri().getPath())
.orElse("");
if (path.length() > 15) {
builder.append("...")
.append(path.substring(path.length() - 12));
} else {
builder.append(path);
}
builder.append('\"');
if (channels().length > 0) {
builder.append(", channels=");
builder.append(Channel.toString(channels()));
}
builder.append(']');
return builder.toString();
}
/**
* Creates the match value.
*
* @param type the type
* @param resource the resource
* @return the object
*/
public static Object createMatchValue(
Class<?> type, ResourcePattern resource) {
return new MatchValue(type, resource);
}
/**
* Represents a match value.
*/
private static class MatchValue {
private final Class<?> type;
private final Object resource;
/**
* @param type
* @param resource
*/
public MatchValue(Class<?> type, Object resource) {
super();
this.type = type;
this.resource = resource;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public int hashCode() {
@SuppressWarnings("PMD.AvoidFinalLocalVariable")
final int prime = 31;
int result = 1;
result = prime * result
+ ((resource == null) ? 0 : resource.hashCode());
result
= prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MatchValue other = (MatchValue) obj;
if (resource == null) {
if (other.resource != null) {
return false;
}
} else if (!resource.equals(other.resource)) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
return true;
}
}
/**
* The associated completion event.
*/
public static class Completed extends CompletionEvent<In> {
/**
* Instantiates a new event.
*
* @param monitoredEvent the monitored event
* @param channels the channels
*/
public Completed(In monitoredEvent, Channel... channels) {
super(monitoredEvent, channels);
}
}
/**
* Represents a HTTP CONNECT request.
*/
public static class Connect extends In {
/**
* Create a new event.
*
* @param request the request data
* @param secure indicates whether the request was received on a
* secure channel
* @param matchLevels the number of elements from the request path
* to use in the match value
* @param channels the channels on which the event is to be
* fired (optional)
* @throws URISyntaxException
*/
public Connect(HttpRequest request, boolean secure, int matchLevels,
Channel... channels) throws URISyntaxException {
super(secure ? "https" : "http", request, matchLevels,
channels);
}
protected URI effectiveRequestUri(String protocol,
HttpRequest request) throws URISyntaxException {
URI req = request.requestUri();
return new URI(req.getScheme(), req.getUserInfo(),
req.getHost(), req.getPort(), null, null, null);
}
}
/**
* The Class Delete.
*/
public static class Delete extends In {
/**
* Create a new event.
*
* @param request the request data
* @param secure indicates whether the request was received on a
* secure channel
* @param matchLevels the number of elements from the request path
* to use in the match value
* @param channels the channels on which the event is to be
* fired (optional)
* @throws URISyntaxException
*/
public Delete(HttpRequest request, boolean secure, int matchLevels,
Channel... channels) throws URISyntaxException {
super(secure ? "https" : "http", request, matchLevels,
channels);
}
}
/**
* Represents a HTTP GET request.
*/
public static class Get extends In {
/**
* Create a new event.
*
* @param request the request data
* @param secure indicates whether the request was received on a
* secure channel
* @param matchLevels the number of elements from the request path
* to use in the match value
* @param channels the channels on which the event is to be
* fired (optional)
* @throws URISyntaxException
*/
public Get(HttpRequest request, boolean secure, int matchLevels,
Channel... channels) throws URISyntaxException {
super(secure ? "https" : "http", request, matchLevels,
channels);
}
}
/**
* Represents a HTTP HEAD request.
*/
public static class Head extends In {
/**
* Create a new event.
*
* @param request the request data
* @param secure indicates whether the request was received on a
* secure channel
* @param matchLevels the number of elements from the request path
* to use in the match value
* @param channels the channels on which the event is to be
* fired (optional)
* @throws URISyntaxException
*/
public Head(HttpRequest request, boolean secure, int matchLevels,
Channel... channels) throws URISyntaxException {
super(secure ? "https" : "http", request, matchLevels,
channels);
}
}
/**
* Represents a HTTP OPTIONS request.
*/
public static class Options extends In {
/**
* Create a new event.
*
* @param request the request data
* @param secure indicates whether the request was received on a
* secure channel
* @param matchLevels the number of elements from the request path
* to use in the match value
* @param channels the channels on which the event is to be
* fired (optional)
* @throws URISyntaxException
*/
public Options(HttpRequest request, boolean secure, int matchLevels,
Channel... channels) throws URISyntaxException {
super(secure ? "https" : "http", request, matchLevels,
channels);
}
}
/**
* Represents a HTTP POST request.
*/
public static class Post extends In {
/**
* Create a new event.
*
* @param request the request data
* @param secure indicates whether the request was received on a
* secure channel
* @param matchLevels the number of elements from the request path
* to use in the match value
* @param channels the channels on which the event is to be
* fired (optional)
* @throws URISyntaxException
*/
public Post(HttpRequest request, boolean secure, int matchLevels,
Channel... channels) throws URISyntaxException {
super(secure ? "https" : "http", request, matchLevels,
channels);
}
}
/**
* Represents a HTTP PUT request.
*/
public static class Put extends In {
/**
* Create a new event.
*
* @param request the request data
* @param secure indicates whether the request was received on a
* secure channel
* @param matchLevels the number of elements from the request path
* to use in the match value
* @param channels the channels on which the event is to be
* fired (optional)
* @throws URISyntaxException
*/
public Put(HttpRequest request, boolean secure, int matchLevels,
Channel... channels) throws URISyntaxException {
super(secure ? "https" : "http", request, matchLevels,
channels);
}
}
/**
* Represents a HTTP TRACE request.
*/
public static class Trace extends In {
/**
* Create a new event.
*
* @param request the request data
* @param secure indicates whether the request was received on a
* secure channel
* @param matchLevels the number of elements from the request path
* to use in the match value
* @param channels the channels on which the event is to be
* fired (optional)
* @throws URISyntaxException
*/
public Trace(HttpRequest request, boolean secure, int matchLevels,
Channel... channels) throws URISyntaxException {
super(secure ? "https" : "http", request, matchLevels,
channels);
}
}
}
/**
* The base class for all outgoing HTTP requests. Outgoing
* request flow upstream and are served externally.
*
* A result of `true` indicates that the request has been processed,
* i.e. a response has been sent or will sent.
*/
@SuppressWarnings("PMD.ShortClassName")
public static class Out extends Request<Void> {
private HttpRequest request;
private BiConsumer<Request.Out, TcpChannel> connectedCallback;
/**
* Instantiates a new request.
*
* @param method the method
* @param url the url
*/
public Out(String method, URL url) {
try {
request = new HttpRequest(method, url.toURI(),
HttpProtocol.HTTP_1_1, false);
} catch (URISyntaxException e) {
// This should not happen because every valid URL can be
// converted to a URI.
throw new IllegalArgumentException(e);
}
}
/**
* Sets a "connected callback". When the {@link Out} event is
* created, the network connection is not yet known. Some
* header fields' values, however, need e.g. the port information
* from the connection. Therefore a callback may be set which is
* invoked when the connection has been obtained that will be used
* to send the request.
*
* @param connectedCallback the connected callback
* @return the out
*/
public Out setConnectedCallback(
BiConsumer<Request.Out, TcpChannel> connectedCallback) {
this.connectedCallback = connectedCallback;
return this;
}
/**
* Returns the connected callback.
*
* @return the connected callback, if set
*/
public Optional<BiConsumer<Request.Out, TcpChannel>>
connectedCallback() {
return Optional.ofNullable(connectedCallback);
}
/**
* The HTTP request that will be sent by the event.
*
* @return the http request
*/
public HttpRequest httpRequest() {
return request;
}
/**
* Returns an absolute URI of the request.
*
* @return the URI
*/
public URI requestUri() {
return request.requestUri();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(Components.objectName(this))
.append(" [").append(request.toString());
if (channels().length > 0) {
builder.append(", channels=");
builder.append(Channel.toString(channels()));
}
builder.append(']');
return builder.toString();
}
/**
* Represents a HTTP CONNECT request.
*/
public static class Connect extends Out {
/**
* Instantiates a new request.
*
* @param uri the uri
*/
public Connect(URL uri) {
super("CONNECT", uri);
}
}
/**
* Represents a HTTP DELETE request.
*/
public static class Delete extends Out {
/**
* Instantiates a new request.
*
* @param uri the uri
*/
public Delete(URL uri) {
super("DELETE", uri);
}
}
/**
* Represents a HTTP GET request.
*/
public static class Get extends Out {
/**
* Instantiates a new request.
*
* @param uri the uri
*/
public Get(URL uri) {
super("GET", uri);
}
}
/**
* Represents a HTTP HEAD request.
*/
public static class Head extends Out {
/**
* Instantiates a new request.
*
* @param uri the uri
*/
public Head(URL uri) {
super("HEAD", uri);
}
}
/**
* Represents a HTTP OPTIONS request.
*/
public static class Options extends Out {
/**
* Instantiates a new request.
*
* @param uri the uri
*/
public Options(URL uri) {
super("OPTIONS", uri);
}
}
/**
* Represents a HTTP POST request.
*/
public static class Post extends Out {
/**
* Instantiates a new request.
*
* @param uri the uri
*/
public Post(URL uri) {
super("POST", uri);
}
}
/**
* Represents a HTTP PUT request.
*/
public static class Put extends Out {
/**
* Instantiates a new request.
*
* @param uri the uri
*/
public Put(URL uri) {
super("PUT", uri);
}
}
/**
* Represents a HTTP TRACE request.
*/
public static class Trace extends Out {
/**
* Instantiates a new request.
*
* @param uri the uri
*/
public Trace(URL uri) {
super("TRACE", uri);
}
}
}
} |
package org.jgrapes.http.events;
import java.net.URI;
import org.jdrupes.httpcodec.HttpRequest;
import org.jgrapes.core.Channel;
import org.jgrapes.core.CompletedEvent;
import org.jgrapes.core.Components;
import org.jgrapes.core.Event;
import org.jgrapes.core.internal.Common;
import org.jgrapes.io.Connection;
/**
* @author Michael N. Lipp
*
*/
public class Request extends Event<Void> {
public static class Completed extends CompletedEvent<Request> {
}
private HttpRequest request;
private Connection connection;
/**
* Creates a new request event with the associated {@link Completed}
* event.
*
* @param connection the connection the request is associated with
* @param request the request data
* @param channels the channels associated with this event
*/
public Request(Connection connection,
HttpRequest request, Channel... channels) {
super(new Completed(), channels);
this.connection = connection;
this.request = request;
}
/**
* Returns the connection.
*
* @return the connection
*/
public Connection getConnection() {
return connection;
}
/**
* Returns the request.
*
* @return the request
*/
public HttpRequest getRequest() {
return request;
}
/**
* Shortcut for getting the request URI from the request.
*
* @return the request URI
*/
public URI getRequestUri() {
return getRequest().getRequestUri();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(Components.objectName(this));
builder.append(" [\"");
String path = request.getRequestUri().getPath();
if (path.length() > 15) {
builder.append("...");
builder.append(path.substring(path.length() - 12));
} else {
builder.append(path);
}
builder.append("\"");
if (connection != null) {
builder.append(" (>>P");
builder.append(
Components.objectId(connection.getResponsePipeline()));
}
builder.append("), ");
if (channels != null) {
builder.append("channels=");
builder.append(Common.channelsToString(channels));
}
builder.append("]");
return builder.toString();
}
} |
package io.spine.security;
/**
* Provides information about the class calling a method.
*/
final class CallerProvider extends SecurityManager {
private static final CallerProvider INSTANCE = new CallerProvider();
/**
* Obtains the instance.
*/
static CallerProvider instance() {
return INSTANCE;
}
/**
* Obtains the class of the object which calls the method from which this method
* is being called.
*/
Class callerClass() {
Class[] context = getClassContext();
Class result = context[2];
return result;
}
/**
* Obtains the class preceding in call chain the class which calls the
* method from which this method is being called.
*/
Class previousCallerClass() {
Class[] context = getClassContext();
Class result = context[3];
return result;
}
} |
package MWC.GUI.ETOPO;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
import MWC.GUI.CanvasType;
import MWC.GUI.Editable;
import MWC.GUI.Chart.Painters.SpatialRasterPainter;
import MWC.GUI.Properties.LineWidthPropertyEditor;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldLocation;
public final class ETOPO_2_Minute extends SpatialRasterPainter
{
static public final class Etopo2Test extends junit.framework.TestCase
{
static public final String TEST_ALL_TEST_TYPE = "UNIT";
public String _etopoPath;
public Etopo2Test(final String val)
{
super(val);
final String pathFromProp = System.getProperty("etopoDir");
if (pathFromProp == null)
{
// are we in OS?
final String sys = System.getProperty("os.name");
if ("Mac OS X".equals(sys))
_etopoPath = "../deploy/";
else
_etopoPath = "C:\\Program Files\\Debrief 2003\\etopo";
}
else
_etopoPath = pathFromProp;
}
// TODO FIX-TEST
// check data
public void NtestFindData()
{
// String thefile = THE_PATH;
assertTrue("Failed to find the 2 minute dataset:" + _etopoPath,
ETOPO_2_Minute.dataFileExists(_etopoPath));
}
public void testConversions()
{
final ETOPO_2_Minute e2m = new ETOPO_2_Minute(_etopoPath);
WorldLocation loc = new WorldLocation(54, -3, 0);
int lat = e2m.getLatIndex(loc);
int lon = e2m.getLongIndex(loc);
double dLat = ETOPO_2_Minute.getLatitudeFor(lat);
double dLong = ETOPO_2_Minute.getLongitudeFor(lon);
WorldLocation loc2 = new WorldLocation(dLat, dLong, 0);
System.out.println("dist:" + loc2.subtract(loc).getRange());
assertTrue("points close enough, original: " + loc + " res:" + loc2, loc2
.subtract(loc).getRange() < 1);
loc = new WorldLocation(-54, -3, 0);
lat = e2m.getLatIndex(loc);
lon = e2m.getLongIndex(loc);
dLat = ETOPO_2_Minute.getLatitudeFor(lat);
dLong = ETOPO_2_Minute.getLongitudeFor(lon);
loc2 = new WorldLocation(dLat, dLong, 0);
assertTrue("points close enough, original: " + loc + " res:" + loc2, loc2
.subtract(loc).getRange() < 1);
loc = new WorldLocation(-54, 3, 0);
lat = e2m.getLatIndex(loc);
lon = e2m.getLongIndex(loc);
dLat = ETOPO_2_Minute.getLatitudeFor(lat);
dLong = ETOPO_2_Minute.getLongitudeFor(lon);
loc2 = new WorldLocation(dLat, dLong, 0);
assertTrue("points close enough, original: " + loc + " res:" + loc2, loc2
.subtract(loc).getRange() < 1);
loc = new WorldLocation(54, 3, 0);
lat = e2m.getLatIndex(loc);
lon = e2m.getLongIndex(loc);
dLat = ETOPO_2_Minute.getLatitudeFor(lat);
dLong = ETOPO_2_Minute.getLongitudeFor(lon);
loc2 = new WorldLocation(dLat, dLong, 0);
assertTrue("points close enough, original: " + loc + " res:" + loc2, loc2
.subtract(loc).getRange() < 1);
// assertEquals(loc, loc2);
}
public final void testMyParams()
{
ETOPO_2_Minute ed = new ETOPO_2_Minute(null);
ed.setName("blank");
editableTesterSupport.testParams(ed, this);
ed = null;
}
}
public final class MARTOPOInfo extends Editable.EditorType implements
java.io.Serializable
{
private static final long serialVersionUID = 1L;
public MARTOPOInfo(final ETOPO_2_Minute data)
{
super(data, data.getName(), "");
}
@Override
public final java.beans.PropertyDescriptor[] getPropertyDescriptors()
{
try
{
final java.beans.PropertyDescriptor[] res =
{prop("Visible", "whether this layer is visible", VISIBILITY),
displayLongProp("KeyLocation", "Key location",
"the current location of the color-key",
KeyLocationPropertyEditor.class, EditorType.FORMAT), prop(
"Color", "the color of the color-key", EditorType.FORMAT),
displayProp("ShowLand", "Show land", "whether to shade land-data",
EditorType.FORMAT), displayLongProp("LineThickness",
"Line thickness", "the thickness to plot the scale border",
LineWidthPropertyEditor.class, EditorType.FORMAT),
displayProp("BathyRes", "Bathy resolution",
"the size of the grid at which to plot the shaded bathy (larger blocks gives faster performance)",
EditorType.FORMAT), displayProp("BathyVisible", "Bathy visible",
"whether to show the gridded contours", VISIBILITY),
displayProp("ContourDepths", "Contour depths",
"the contour depths to plot", EditorType.FORMAT), displayProp(
"ContoursVisible", "Contours visible",
"whether to show the contours", VISIBILITY), displayProp(
"ContourGridInterval", "Contour grid interval",
"the interval at which to calculate the contours (larger interval leads to faster performance)",
EditorType.FORMAT), displayProp("ContourOptimiseGrid",
"Optimise grid interval",
"whether the grid interval should be optimised",
EditorType.FORMAT)};
return res;
}
catch (final java.beans.IntrospectionException e)
{
e.printStackTrace();
return super.getPropertyDescriptors();
}
}
}
private static final long serialVersionUID = 1L;
public static final String SHADE_AS_NATURAL_EARTH = "ShadeAsNaturalEarth";
/**
* the filename of our data-file
*/
private static final String fName = "ETOPO2.raw";
/**
* the file-reader we are using
*/
private static java.io.RandomAccessFile ra = null;
public static WorldArea theArea = null;
/** static accessor to see if our data-file is there
*
* @param etopo_path
* @return
*/
static public boolean dataFileExists(final String etopo_path)
{
boolean res = false;
final String thePath = etopo_path + "/" + fName;
final File testFile = new File(thePath);
if (testFile.exists())
res = true;
return res;
}
/* returns a color based on slope and elevation */
public static int getETOPOColor(final short elevation,
final double lowerLimit, final double upperLimit, final boolean showLand,
final SpatialRasterPainter.ColorConverter converter, final boolean useNE)
{
final int res;
if (useNE)
{
// see if we are above or beneath water level
if ((elevation > 0) && (showLand))
{
// ABOVE WATER
res = converter.convertColor(235, 219, 188);
}
else
{
// BELOW WATER
// switch to positive
double val = elevation;
if (val < lowerLimit)
val = lowerLimit;
final double x = val / lowerLimit;
final int red = (int) (169.0577 - 157.9448 * x + 19.64085 * Math.pow(x,
2));
final int green = (int) (197.4973 - 103.4937 * x - 2.004169 * Math.pow(
x, 2));
final int blue = (int) (227.4203 - (35.15651 * x) - (30.06253 * Math
.pow(x, 2)));
res = converter.convertColor(red, green, blue);
}
}
else
{
// see if we are above or beneath water level
if ((elevation > 0) && (showLand))
{
// ABOVE WATER
// switch to positive
double val = elevation;
if (val > upperLimit)
val = upperLimit;
final double proportion = val / upperLimit;
final double color_val = proportion * 125;
// limit the colour val to the minimum value
int green_tone = 255 - (int) color_val;
// just check we've got a valid colour
green_tone = Math.min(250, green_tone);
res = converter.convertColor(88, green_tone, 88);
}
else
{
// BELOW WATER
// switch to positive
double val = elevation;
if (val < lowerLimit)
val = lowerLimit;
final double proportion = val / lowerLimit;
final double color_val = proportion * ETOPOWrapper.BLUE_MULTIPLIER;
// limit the colour val to the minimum value
int blue_tone = 255 - (int) color_val;
// just check we've got a valid colour
blue_tone = Math.min(250, blue_tone);
final int green = (int) ETOPOWrapper.GREEN_BASE_VALUE + (int) (blue_tone
* ETOPOWrapper.GREEN_MULTIPLIER);
res = converter.convertColor(ETOPOWrapper.RED_COMPONENT, green,
blue_tone);
}
}
// so, just produce a shade of blue depending on how deep we are.
return res;
}
/**
* how many horizonal data points are in our data
*/
private static int getHorizontalNumber()
{
return 10800;
}
/**
* get the latitude for the indicated index
*/
static double getLatitudeFor(final int index)
{
double res;
res = index;
// convert to mins
res *= 2;
// add 1 for luck
res += 1;
// convert to degs
res /= 60;
// put in hemisphere
if (res > 90)
{
res = -(res - 90);
}
else
{
res = 90 - res;
}
return res;
}
/**
* get the longitude for the indicated index
*/
static double getLongitudeFor(final int index)
{
double res;
// convert to mins
res = index * 2;
// add 1 for luck
res += 1;
// convert to degs
res /= 60;
// put in hemisphere
res -= 180;
return res;
}
/**
* rescale the data-set, if necessary
*
* @param val
* the depth as read from file
* @return the rescaled depth (from feet to metres in this case)
*/
private static int rescaleValue(final int val)
{
// convert from feet to metres
// return (int)MWC.Algorithms.Conversions.ft2m(val);
return val;
}
/**
* whether to show land
*/
private boolean _showLand = true;
/**
* the path to the datafile
*/
private final String _thePath;
/**
* flag to ensure we only report missing data on the first occasion
*/
private boolean _reportedMissingData = false;
/**
* cache the values we read from file. At some resolutions we re-read the same depth cell many
* times.
*/
final Map<Integer, Integer> _pointCache = new HashMap<Integer, Integer>();
public ETOPO_2_Minute(final String etopo_path)
{
super("ETOPO (2 Minute)");
// store the path to the data file
_thePath = etopo_path;
_contourDepths = DEFAULT_CONTOUR_DEPTHS;
}
/**
* function to retrieve a data value at the indicated index
*/
@Override
protected final double contour_valAt(final int i, final int j)
{
final double res;
final int index;
index = 2 * (j * getHorizontalNumber() + i);
res = getValueAtIndex(index);
return res;
}
/**
* function to retrieve the x-location for a specific array index
*/
@Override
protected final double contour_xValAt(final int i)
{
return getLongitudeFor(i);
}
/**
* function to retrieve the x-location for a specific array index
*/
@Override
protected final double contour_yValAt(final int i)
{
return getLatitudeFor(i);
}
/* returns a color based on slope and elevation */
@Override
public final int getColor(final int elevation, final double lowerLimit,
final double upperLimit,
final SpatialRasterPainter.ColorConverter converter, final boolean useNE)
{
return getETOPOColor((short) elevation, lowerLimit, upperLimit, _showLand,
converter, useNE);
}
/**
* provide the delta for the data (in degrees)
*/
@Override
public double getGridDelta()
{
return 1d / 30d;
}
/**
* get the index for a particular point
*
* @param val
* the location we want the index for
* @return the index into the array for this position
*/
private int getIndex(final WorldLocation val)
{
final int res;
// and the res
res = 2 * ((getLatIndex(val) * getHorizontalNumber()) + getLongIndex(val));
return res;
}
@Override
public final Editable.EditorType getInfo()
{
if (_myEditor == null)
_myEditor = new MARTOPOInfo(this);
return _myEditor;
}
/**
* get the lat component of this location
*/
@Override
protected final int getLatIndex(final WorldLocation val)
{
// get the components
double lat = val.getLat();
final int lat_index;
// work out how far down the lat is
if (lat > 0)
{
// convert to down
lat = 90d - lat;
}
else
lat = 90 + Math.abs(lat);
// convert to mins
lat = lat * 60;
// convert to 2 mins intervals
lat = lat / 2;
lat_index = (int) lat;
return lat_index;
}
/**
* get the long component of this location
*/
@Override
protected final int getLongIndex(final WorldLocation val)
{
// get the components
double lon = val.getLong();
final int long_index;
// work out how far acrss the lat is
if (lon < 0)
{
lon = 180 + lon;
}
else
lon = 180 + lon;
// convert to secs
lon = lon * 60;
// convert to 2 sec intervals
lon = lon / 2;
long_index = (int) lon;
return long_index;
}
/**
* accessor for whether to show land
*/
public final boolean getShowLand()
{
return _showLand;
}
/**
* @param val
* the location to get the depth for
* @return the depth (in m)
*/
@Override
public final int getValueAt(final WorldLocation val)
{
final int res;
// is it valid
if (!val.isValid())
{
res = 0;
}
else
{
// now get it's index
final int index = getIndex(val);
// and get the value itself
res = getValueAtIndex(index);
}
return res;
}
private int getValueAtIndex(final int index)
{
// check the cache
final Integer cached = _pointCache.get(index);
if (cached != null)
{
return cached.intValue();
}
else
{
int res = 0;
// just check we have the file open
openFile();
// just check we have a +ve (valid) index
if (index >= 0)
{
// and retrieve the value
try
{
ra.seek(index);
res = ra.readShort();
// rescale as appropriate
res = rescaleValue(res);
}
catch (final IOException e)
{
e.printStackTrace(); // To change body of catch statement use
// Options |
// File Templates.
}
}
// cache the value
_pointCache.put(index, res);
return res;
}
}
/**
* we do want to double-buffer this layer - since it takes "so" long to create
*
*/
@Override
public boolean isBuffered()
{
return true;
}
/**
* whether the data has been loaded yet
*/
@Override
public boolean isDataLoaded()
{
// do an open, just to check
openFile();
return (ra != null);
}
/**
* open our datafile in random access mode
*/
private final void openFile()
{
if (ra == null)
{
String thePath = null;
// just do a check to see if we have just the file or the whole path
final File testF = new File(_thePath);
if (testF.isFile())
{
thePath = _thePath;
}
else if (testF.isDirectory())
{
thePath = _thePath + "//" + fName;
}
if (thePath != null)
{
try
{
ra = new RandomAccessFile(thePath, "r");
}
catch (final IOException e)
{
if (_reportedMissingData)
{
MWC.GUI.Dialogs.DialogFactory.showMessage("File missing",
"2 minute ETOPO data not found at:" + thePath);
_reportedMissingData = true;
}
}
}
}
}
/**
* override the parent paint method, so we can open/close the datafile
*
* @param dest
* where we're painting to
*/
@Override
public final void paint(final CanvasType dest)
{
if (getVisible())
{
final long start = System.currentTimeMillis();
// start the paint
openFile();
// hey, it's only worth plotting if we've got some data
if (!isDataLoaded())
return;
// clear the cache
// _pointCache.clear();
// remember width
final float oldWid = dest.getLineWidth();
// set our line width
dest.setLineWidth(this.getLineThickness());
super.paint(dest);
// and restore the old one
dest.setLineWidth(oldWid);
System.out.println("Elapsed:" + (System.currentTimeMillis() - start));
}
}
/**
* setter for whether to show land
*/
public final void setShowLand(final boolean val)
{
_showLand = val;
}
/**
* over-rideable method to constrain max value to zero (such as when not plotting land)
*
* @return yes/no
*/
@Override
protected final boolean zeroIsMax(final boolean useNE)
{
// if we are showing land, then we don't want zero to be the top value
return useNE || !_showLand;
}
} |
package oshi.software.os;
import oshi.annotation.concurrent.ThreadSafe;
/**
* A FileStore represents a storage pool, device, partition, volume, concrete
* file system or other implementation specific means of file storage. This
* object carries the same interpretation as core Java's
* {@link java.nio.file.FileStore} class, with additional information.
*/
@ThreadSafe
public interface OSFileStore {
/**
* Name of the File System. A human-readable label that does not necessarily
* correspond to a file system path.
*
* @return The file system name
*/
String getName();
/**
* Volume name of the File System. Generally a path representing the device
* (e.g., {@code /dev/foo} which is being mounted.
*
* @return The volume name of the file system
*/
String getVolume();
/**
* Label of the File System. An optional replacement for the name on Windows and
* Linux.
*
* @return The volume label of the file system. Only relevant on Windows and on
* Linux, if assigned; otherwise defaults to the FileSystem name. On
* other operating systems is redundant with the name.
*/
String getLabel();
/**
* Logical volume of the File System.
*
* Provides an optional alternative volume identifier for the file system. Only
* supported on Linux, provides symlink value via '/dev/mapper/' (used with LVM
* file systems).
*
* @return The logical volume of the file system
*/
String getLogicalVolume();
/**
* Mount point of the File System. The directory users will normally use to
* interface with the file store.
*
* @return The mountpoint of the file system
*/
String getMount();
/**
* Description of the File System.
*
* @return The file system description
*/
String getDescription();
/**
* Type of the File System (FAT, NTFS, etx2, ext4, etc.)
*
* @return The file system type
*/
String getType();
/**
* Filesystem options.
*
* @return A comma-deimited string of options
*/
String getOptions();
/**
* UUID/GUID of the File System.
*
* @return The file system UUID/GUID
*/
String getUUID();
long getFreeSpace();
/**
* Usable space on the drive. This is space available to unprivileged users.
*
* @return Usable space on the drive (in bytes)
*/
long getUsableSpace();
/**
* Total space/capacity of the drive.
*
* @return Total capacity of the drive (in bytes)
*/
long getTotalSpace();
/**
* Usable / free inodes on the drive. Not applicable on Windows.
*
* @return Usable / free inodes on the drive (count), or -1 if unimplemented
*/
long getFreeInodes();
/**
* Total / maximum number of inodes of the filesystem. Not applicable on
* Windows.
*
* @return Total / maximum number of inodes of the filesystem (count), or -1 if
* unimplemented
*/
long getTotalInodes();
/**
* Make a best effort to update all the statistics about the file store without
* needing to recreate the file store list. This method provides for more
* frequent periodic updates of file store statistics.
*
* @return True if the update was (probably) successful, false if the disk was
* not found
*/
boolean updateAttributes();
} |
package org.wikipedia.test;
import android.support.annotation.NonNull;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wikipedia.WikipediaApp;
import org.wikipedia.dataclient.WikiSite;
import org.wikipedia.editing.AbuseFilterEditResult;
import org.wikipedia.editing.CaptchaResult;
import org.wikipedia.editing.EditTask;
import org.wikipedia.editing.EditingResult;
import org.wikipedia.editing.SuccessEditResult;
import org.wikipedia.page.PageTitle;
import org.wikipedia.testlib.TestLatch;
import static android.support.test.InstrumentationRegistry.getTargetContext;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@SmallTest
@RunWith(AndroidJUnit4.class)
public class EditTaskTest {
private static final WikiSite TEST_WIKI = WikiSite.forLanguageCode("test");
private static final String ABUSE_FILTER_ERROR_PAGE_TITLE = "Test_page_for_app_testing/AbuseFilter";
@Before
public void setUp() {
// Cookies for a logged in session cannot be used with the anonymous edit token.
app().getCookieManager().clearAllCookies();
}
@Test
public void testEdit() {
PageTitle title = new PageTitle(null, "Test_page_for_app_testing/Section1", TEST_WIKI);
String wikitext = "== Section 2 ==\n\nEditing section INSERT RANDOM & HERE test at "
+ System.currentTimeMillis();
final int sectionId = 3;
EditingResult result = Subject.execute(title, wikitext, sectionId);
assertThat(result, instanceOf(SuccessEditResult.class));
}
@Test
public void testCaptcha() {
PageTitle title = new PageTitle(null, "Test_page_for_app_testing/Captcha", TEST_WIKI);
String wikitext = "== Section 2 ==\n\nEditing by inserting an external link https:
+ System.currentTimeMillis();
EditingResult result = Subject.execute(title, wikitext);
validateCaptcha(result);
}
@Test
public void testAbuseFilterTriggerWarn() {
PageTitle title = new PageTitle(null, "User:Yuvipandaaaaaaaa", TEST_WIKI);
// Rule 94 is only a warning so the initial attempt may be successful. The second is
// guaranteed to be a warning if different content is used. @FlakyTest(tolerance = 2)
// doesn't work with JUnit 4.
EditingResult result = null;
for (int i = 0; !(result instanceof AbuseFilterEditResult) && i < 2; ++i) {
String wikitext = "Testing Abusefilter by simply editing this page. Triggering rule 94 at "
+ System.nanoTime();
result = Subject.execute(title, wikitext);
}
assertThat(result, instanceOf(AbuseFilterEditResult.class));
//noinspection ConstantConditions
assertThat(((AbuseFilterEditResult) result).getType(), is(AbuseFilterEditResult.TYPE_WARNING));
}
@Test
public void testAbuseFilterTriggerStop() {
PageTitle title = new PageTitle(null, ABUSE_FILTER_ERROR_PAGE_TITLE, TEST_WIKI);
String wikitext = "== Section 2 ==\n\nTriggering AbuseFilter number 2 by saying poop many times at "
+ System.currentTimeMillis();
EditingResult result = Subject.execute(title, wikitext);
assertThat(result, instanceOf(AbuseFilterEditResult.class));
assertThat(((AbuseFilterEditResult) result).getType(), is(AbuseFilterEditResult.TYPE_ERROR));
}
@Test
public void testAbuseFilterTriggerStopOnArbitraryErrorCode() {
PageTitle title = new PageTitle(null, ABUSE_FILTER_ERROR_PAGE_TITLE, TEST_WIKI);
String wikitext = "== Section 2 ==\n\nTriggering AbuseFilter number 152 by saying appcrashtest many times at "
+ System.currentTimeMillis();
EditingResult result = Subject.execute(title, wikitext);
assertThat(result, instanceOf(AbuseFilterEditResult.class));
assertThat(((AbuseFilterEditResult) result).getType(), is(AbuseFilterEditResult.TYPE_ERROR));
}
private void validateCaptcha(EditingResult result) {
assertThat(result, instanceOf(CaptchaResult.class));
CaptchaResult captchaResult = (CaptchaResult) result;
String url = captchaResult.getCaptchaUrl(TEST_WIKI);
assertThat(isValidCaptchaUrl(url), is(true));
}
private boolean isValidCaptchaUrl(String url) {
return url.startsWith(getNetworkProtocol()
+ "://test.wikipedia.org/w/index.php?title=Special:Captcha/image");
}
private String getNetworkProtocol() {
return app().getWikiSite().scheme();
}
private WikipediaApp app() {
return WikipediaApp.getInstance();
}
private static class Subject extends EditTask {
private static final int DEFAULT_SECTION_ID = 0;
// https://www.mediawiki.org/wiki/Manual:Edit_token#The_edit_token_suffix
private static final String ANONYMOUS_TOKEN = "+\\";
private static final String DEFAULT_SUMMARY = "";
public static EditingResult execute(PageTitle title, String sectionWikitext) {
return execute(title, sectionWikitext, DEFAULT_SECTION_ID);
}
public static EditingResult execute(PageTitle title, String sectionWikitext, int sectionId) {
return execute(title, sectionWikitext, sectionId, ANONYMOUS_TOKEN);
}
public static EditingResult execute(PageTitle title, String sectionWikitext, int sectionId,
String token) {
Subject subject = new Subject(title, sectionWikitext, sectionId, token);
subject.execute();
return subject.await();
}
@NonNull private final TestLatch latch = new TestLatch();
private EditingResult result;
Subject(PageTitle title, String sectionWikitext, int sectionId, String token) {
super(getTargetContext(), title, sectionWikitext, sectionId, token, DEFAULT_SUMMARY,
false);
}
@Override
public void onFinish(EditingResult result) {
super.onFinish(result);
this.result = result;
latch.countDown();
}
public EditingResult await() {
latch.await();
return result;
}
}
} |
package com.example.android.sayhi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
Toast toast;
String choice,string;
Spinner spinner;
TextToSpeech tts;
Locale locale ;
Context context;
CharSequence mess;
int duration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(),R.array.langs, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);
Button button = (Button) findViewById(R.id.button);
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
if(i!= 0)
;
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
choice = adapterView.getItemAtPosition(i).toString();
switch(choice){
case "Japanese" :
locale = new Locale("ja");
break;
case "French" :
locale = new Locale("fr");
break;
case "English UK" :
locale = new Locale("en", "UK");
break;
case "Chinese" :
locale = new Locale("zh");
break;
case "German" :
locale = new Locale("de");
break;
case "Spanish" :
locale = new Locale("es");
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
locale = new Locale("en", "UK");
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText edit = (EditText) findViewById(R.id.text);
TextView text = (TextView) findViewById(R.id.textView);
string = edit.getText().toString();
text.setText(string);
tts.setLanguage(locale);
new MoveToBackGround().execute();
}
});
}
@Override
protected void onPause() {
super.onPause();
tts.stop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.feedback : Intent Email = new Intent(Intent.ACTION_SEND);
Email.setType("text/email");
Email.putExtra(Intent.EXTRA_EMAIL, new String[] { "amrits1408@gmail.com" });
Email.putExtra(Intent.EXTRA_SUBJECT, "Feedback");
Email.putExtra(Intent.EXTRA_TEXT, "Dear developer," + "");
startActivity(Intent.createChooser(Email, "Send Feedback:"));
break;
case R.id.about_app :
context = getApplicationContext();
mess = "Type it in Editable, select language and get the pronunciation. Make sure your phone has the required language pack in TTS downloaded.\n\n More to follow...";
duration = Toast.LENGTH_LONG;
toast = Toast.makeText(context, mess, duration);
toast.show();
break;
case R.id.about_me :
context = getApplicationContext();
mess = "Under Construction, but here is a quote to make your day. \n\n \"If the King doesn't lead, how can he expect his subordinates to follow?\"";
duration = Toast.LENGTH_LONG;
toast = Toast.makeText(context, mess, duration);
toast.show();
break;
}
return super.onOptionsItemSelected(item);
}
private class MoveToBackGround extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... voids) {
tts.speak( string, TextToSpeech.QUEUE_FLUSH,null);
return null;
}
}
} |
package com.google.android.libraries.gsa.d.a;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build.VERSION;
import android.util.Log;
import android.util.Property;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
public class r extends FrameLayout {
public static boolean DEBUG = true;//Todo: debug const is here
public static boolean uoK = false;
public static boolean uoL = false;
public static final Property uoz = new s(Integer.class, "panelX");
public float bdZ;
public float bea;
public int mActivePointerId = -1;
public float mDensity;
public int mFlingThresholdVelocity;
public boolean mIsPageMoving = false;
public final boolean mIsRtl;
public float mLastMotionX;
public int mMaximumVelocity;
public int mMinFlingVelocity;
public int mMinSnapVelocity;
public float mTotalMotionX;
public int mTouchSlop;
public int mTouchState = 0;
public VelocityTracker mVelocityTracker;
public View uoA;
public View uoB;
public int uoC;
public float uoD;
public float uoE;
public float uoF;
public u uoG;
public t uoH;
public boolean uoI = false;
public boolean uoJ;
public boolean uoM;
public DecelerateInterpolator uoN = new DecelerateInterpolator(3.0f);
public r(Context context) {
super(context);
ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext());
this.mTouchSlop = viewConfiguration.getScaledPagingTouchSlop();
this.mMaximumVelocity = viewConfiguration.getScaledMaximumFlingVelocity();
this.mDensity = getResources().getDisplayMetrics().density;
this.mFlingThresholdVelocity = (int) (500.0f * this.mDensity);
this.mMinFlingVelocity = (int) (250.0f * this.mDensity);
this.mMinSnapVelocity = (int) (1500.0f * this.mDensity);
this.uoG = new u(this);
this.mIsRtl = isRtl(getResources());
}
public final void el(View view) {
this.uoA = view;
super.addView(this.uoA);
}
final void BM(int i) {
if (i <= 1) {
i = 0;
}
int measuredWidth = getMeasuredWidth();
this.uoD = ((float) i) / ((float) measuredWidth);
this.uoC = Math.max(Math.min(i, measuredWidth), 0);
this.uoA.setTranslationX(this.mIsRtl ? (float) (-this.uoC) : (float) this.uoC);
if (uoK) {
this.uoA.setAlpha(Math.max(0.1f, this.uoN.getInterpolation(this.uoD)));
}
if (this.uoH != null) {
this.uoH.D(this.uoD);
}
}
final void fv(int i) {
cnF();
this.uoM = true;
this.uoG.dt(getMeasuredWidth(), i);
}
final void closePanel(int i) {
if (DEBUG) {
Log.d("wo.SlidingPanelLayout", "onPanelClosing");
}
this.mIsPageMoving = true;
if (this.uoH != null) {
boolean z;
t tVar = this.uoH;
if (this.mTouchState == 1) {
z = true;
} else {
z = false;
}
tVar.oc(z);
}
this.uoM = true;
this.uoG.dt(0, i);
}
public final void em(View view) {
if (this.uoB != null) {
super.removeView(this.uoB);
}
this.uoB = view;
super.addView(this.uoB, 0);
}
public boolean onInterceptTouchEvent(MotionEvent motionEvent) {
acquireVelocityTrackerAndAddMovement(motionEvent);
if (getChildCount() <= 0) {
return super.onInterceptTouchEvent(motionEvent);
}
int action = motionEvent.getAction();
if (action == 2 && this.mTouchState == 1) {
return true;
}
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
boolean z;
float x = motionEvent.getX();
float y = motionEvent.getY();
if (DEBUG) {
String valueOf = String.valueOf(motionEvent);
Log.d("wo.SlidingPanelLayout", new StringBuilder(String.valueOf(valueOf).length() + 22).append("Intercept touch down: ").append(valueOf).toString());
}
this.bdZ = x;
this.bea = y;
this.uoF = (float) this.uoC;
this.mLastMotionX = x;
this.mTotalMotionX = 0.0f;
this.mActivePointerId = motionEvent.getPointerId(0);
action = Math.abs(this.uoG.mFinalX - this.uoC);
if (this.uoG.isFinished() || action < this.mTouchSlop / 3) {
z = true;
} else {
z = false;
}
if (!z || this.uoJ) {
this.uoJ = false;
cnN();
this.uoE = x;
break;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
resetTouchState();
break;
case MotionEvent.ACTION_MOVE:
if (this.mActivePointerId != -1) {
determineScrollingStart(motionEvent, 1.0f);
break;
}
break;
case com.google.android.libraries.material.progress.u.uKQ :
onSecondaryPointerUp(motionEvent);
releaseVelocityTracker();
break;
}
if (this.mTouchState == 0) {
return false;
}
return true;
}
public boolean onTouchEvent(MotionEvent motionEvent) {
super.onTouchEvent(motionEvent);
if (this.uoA == null) {
return super.onTouchEvent(motionEvent);
}
acquireVelocityTrackerAndAddMovement(motionEvent);
float x;
float y;
int abs;
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
boolean z;
x = motionEvent.getX();
y = motionEvent.getY();
this.bdZ = x;
this.bea = y;
this.uoF = (float) this.uoC;
this.mLastMotionX = x;
this.mTotalMotionX = 0.0f;
this.mActivePointerId = motionEvent.getPointerId(0);
abs = Math.abs(this.uoG.mFinalX - this.uoC);
if (this.uoG.isFinished() || abs < this.mTouchSlop / 3) {
z = true;
} else {
z = false;
}
if (z && !this.uoJ) {
return true;
}
this.uoJ = false;
cnN();
this.uoE = x;
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (this.mTouchState != 1) {
return true;
}
this.mVelocityTracker.computeCurrentVelocity(1000, (float) this.mMaximumVelocity);
abs = (int) this.mVelocityTracker.getXVelocity(this.mActivePointerId);
boolean z2 = this.mTotalMotionX > 25.0f && Math.abs(abs) > this.mFlingThresholdVelocity;
if (z2) {
if (this.mIsRtl) {
abs = -abs;
}
if (Math.abs(abs) < this.mMinFlingVelocity) {
if (abs >= 0) {
fv(750);
} else {//Todo: this else was not there initially
closePanel(750);
}
} else {
float measuredWidth = ((float) (getMeasuredWidth() / 2)) + (((float) Math.sin((double) ((float) (((double) (Math.min(1.0f, (((float) (abs < 0 ? this.uoC : getMeasuredWidth() - this.uoC)) * 1.0f) / ((float) getMeasuredWidth())) - 0.5f)) * 0.4712389167638204d)))) * ((float) (getMeasuredWidth() / 2)));
if (abs > 0) {
z2 = true;
} else {
z2 = false;
}
abs = Math.round(Math.abs(measuredWidth / ((float) Math.max(this.mMinSnapVelocity, Math.abs(abs)))) * 1000.0f) * 4;
if (z2) {
fv(abs);
} else {
closePanel(abs);
}
}
} else {
if (this.uoC >= getMeasuredWidth() / 2) {
fv(750);
} else {//Todo: this else was not there initially
closePanel(750);
}
}
resetTouchState();
return true;
case MotionEvent.ACTION_MOVE:
if (this.mTouchState == 1) {
abs = motionEvent.findPointerIndex(this.mActivePointerId);
if (abs == -1) {
return true;
}
y = motionEvent.getX(abs);
this.mTotalMotionX += Math.abs(y - this.mLastMotionX);
this.mLastMotionX = y;
y -= this.uoE;
x = this.uoF;
if (this.mIsRtl) {
y = -y;
}
BM((int) (y + x));
return true;
}
determineScrollingStart(motionEvent, 1.0f);
return true;
case com.google.android.libraries.material.progress.u.uKQ :
onSecondaryPointerUp(motionEvent);
releaseVelocityTracker();
return true;
default:
return true;
}
}
private final void resetTouchState() {
releaseVelocityTracker();
this.uoJ = false;
this.mTouchState = 0;
this.mActivePointerId = -1;
}
private final void onSecondaryPointerUp(MotionEvent motionEvent) {
int action = (motionEvent.getAction() >> 8) & 255;
if (motionEvent.getPointerId(action) == this.mActivePointerId) {
action = action == 0 ? 1 : 0;
float x = motionEvent.getX(action);
this.uoE += x - this.mLastMotionX;
this.bdZ = x;
this.mLastMotionX = x;
this.mActivePointerId = motionEvent.getPointerId(action);
if (this.mVelocityTracker != null) {
this.mVelocityTracker.clear();
}
}
}
protected void determineScrollingStart(MotionEvent motionEvent, float f) {
int findPointerIndex = motionEvent.findPointerIndex(this.mActivePointerId);
if (findPointerIndex != -1) {
float x = motionEvent.getX(findPointerIndex);
if (((int) Math.abs(x - this.bdZ)) > Math.round(((float) this.mTouchSlop) * f)) {
this.mTotalMotionX += Math.abs(this.mLastMotionX - x);
this.uoE = x;
this.mLastMotionX = x;
cnN();
}
}
}
private final void acquireVelocityTrackerAndAddMovement(MotionEvent motionEvent) {
if (this.mVelocityTracker == null) {
this.mVelocityTracker = VelocityTracker.obtain();
this.mVelocityTracker.clear();
}
this.mVelocityTracker.addMovement(motionEvent);
}
private final void releaseVelocityTracker() {
if (this.mVelocityTracker != null) {
this.mVelocityTracker.clear();
this.mVelocityTracker.recycle();
this.mVelocityTracker = null;
}
}
protected void onMeasure(int i, int i2) {
int size = MeasureSpec.getSize(i);
int size2 = MeasureSpec.getSize(i2);
if (this.uoB != null) {
this.uoB.measure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size2, MeasureSpec.EXACTLY));//Todo: i modified them, there was ints before instead of constants
}
if (this.uoA != null) {
this.uoA.measure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size2, MeasureSpec.EXACTLY));
}
setMeasuredDimension(size, size2);
BM((int) (((float) size) * this.uoD));
}
protected void onLayout(boolean z, int i, int i2, int i3, int i4) {
if (this.uoB != null) {
this.uoB.layout(0, 0, this.uoB.getMeasuredWidth(), this.uoB.getMeasuredHeight());
}
if (this.uoA != null) {
int measuredWidth = this.uoA.getMeasuredWidth();
int measuredHeight = this.uoA.getMeasuredHeight();
int i5 = this.mIsRtl ? measuredWidth : -measuredWidth;
if (this.mIsRtl) {
measuredWidth *= 2;
} else {
measuredWidth = 0;
}
this.uoA.layout(i5, 0, measuredWidth, measuredHeight);
}
}
public static boolean isRtl(Resources resources) {
if (VERSION.SDK_INT < 17 || resources.getConfiguration().getLayoutDirection() != 1) {
return false;
}
return true;
}
private final void cnN() {
this.mTouchState = 1;
this.mIsPageMoving = true;
this.uoM = false;
this.uoG.cnP();
if (uoL) {
setLayerType(2, null);
}
if (DEBUG) {
Log.d("wo.SlidingPanelLayout", "onDragStarted");
}
if (this.uoH != null) {
this.uoH.cnE();
}
}
final void cnF() {
if (DEBUG) {
Log.d("wo.SlidingPanelLayout", "onPanelOpening");
}
this.mIsPageMoving = true;
if (this.uoH != null) {
this.uoH.cnF();
}
}
final void cnG() {
if (DEBUG) {
Log.d("wo.SlidingPanelLayout", "onPanelOpened");
}
cnO();
this.uoI = true;
this.mIsPageMoving = false;
if (this.uoH != null) {
this.uoH.cnG();
}
}
final void cnO() {
if (uoL) {
setLayerType(0, null);
}
}
} |
package com.ibm.mil.smartringer;
import android.content.Context;
import android.media.AudioManager;
import android.util.Log;
public final class VolumeAdjuster {
private static final String TAG = VolumeAdjuster.class.getName();
private static final int VOLUME_FLAGS = 0;
private AudioManager mAudioManager;
private final int mStreamType;
private final int mOriginalVolume;
private final int mMaxVolume;
private final int mAmpInterval;
public VolumeAdjuster(AudioManager audioManager, int streamType) {
mAudioManager = audioManager;
mStreamType = streamType;
mOriginalVolume = mAudioManager.getStreamVolume(mStreamType);
mMaxVolume = mAudioManager.getStreamMaxVolume(mStreamType);
mAmpInterval = NoiseMeter.METER_LIMIT / mMaxVolume;
}
public void adjustVolume(int noiseAmplitude, SensitivityLevel sensitivityLevel) {
int adjustedVolumeLevel = Math.max(1, noiseAmplitude / mAmpInterval);
if (sensitivityLevel == SensitivityLevel.LOW) {
adjustedVolumeLevel = Math.max(1, adjustedVolumeLevel - 1);
} else if (sensitivityLevel == SensitivityLevel.HIGH) {
adjustedVolumeLevel = Math.min(mMaxVolume, adjustedVolumeLevel + 1);
}
mAudioManager.setStreamVolume(mStreamType, adjustedVolumeLevel, VOLUME_FLAGS);
Log.d(TAG, "noise amplitude: " + noiseAmplitude);
Log.d(TAG, "volume level: " + adjustedVolumeLevel);
}
public void restoreVolume() {
mAudioManager.setStreamVolume(mStreamType, mOriginalVolume, VOLUME_FLAGS);
}
public void mute() {
mAudioManager.setStreamVolume(mStreamType, 0, VOLUME_FLAGS);
}
public enum SensitivityLevel {
LOW,
MEDIUM,
HIGH
}
public static final String SENSITIVITY_PREFS_NAME = "SensitivityPrefs";
public static final String SENSITIVITY_PREFS_KEY = "sensitivityLevel";
public static SensitivityLevel getUsersSensitivityLevel(Context context) {
String enumValueName = context
.getSharedPreferences(SENSITIVITY_PREFS_NAME, Context.MODE_PRIVATE)
.getString(SENSITIVITY_PREFS_KEY, VolumeAdjuster.SensitivityLevel.MEDIUM.name());
// enumValueName may be null, use MEDIUM as default in this case
SensitivityLevel sensitivityLevel = SensitivityLevel.MEDIUM;
if (enumValueName != null) {
sensitivityLevel = Enum.valueOf(VolumeAdjuster.SensitivityLevel.class, enumValueName);
}
return sensitivityLevel;
}
} |
package com.github.kevinsawicki.http;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_CREATED;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED;
import static java.net.HttpURLConnection.HTTP_OK;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.PrivilegedAction;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* A fluid interface for making HTTP requests using an underlying
* {@link HttpURLConnection} (or sub-class).
* <p>
* Each instance supports making a single request and cannot be reused for
* further requests.
*/
public class HttpRequest {
/**
* 'UTF-8' charset name
*/
public static final String CHARSET_UTF8 = "UTF-8";
/**
* 'Accept' header name
*/
public static final String HEADER_ACCEPT = "Accept";
/**
* 'Accept-Charset' header name
*/
public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset";
/**
* 'Accept-Encoding' header name
*/
public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
/**
* 'Authorization' header name
*/
public static final String HEADER_AUTHORIZATION = "Authorization";
/**
* 'Cache-Control' header name
*/
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
/**
* 'Content-Encoding' header name
*/
public static final String HEADER_CONTENT_ENCODING = "Content-Encoding";
/**
* 'Content-Length' header name
*/
public static final String HEADER_CONTENT_LENGTH = "Content-Length";
/**
* 'Content-Type' header name
*/
public static final String HEADER_CONTENT_TYPE = "Content-Type";
/**
* 'Date' header name
*/
public static final String HEADER_DATE = "Date";
/**
* 'ETag' header name
*/
public static final String HEADER_ETAG = "ETag";
/**
* 'Expires' header name
*/
public static final String HEADER_EXPIRES = "Expires";
/**
* 'If-None-Match' header name
*/
public static final String HEADER_IF_NONE_MATCH = "If-None-Match";
/**
* 'Last-Modified' header name
*/
public static final String HEADER_LAST_MODIFIED = "Last-Modified";
/**
* 'Location' header name
*/
public static final String HEADER_LOCATION = "Location";
/**
* 'Server' header name
*/
public static final String HEADER_SERVER = "Server";
/**
* 'User-Agent' header name
*/
public static final String HEADER_USER_AGENT = "User-Agent";
/**
* 'DELETE' request method
*/
public static final String METHOD_DELETE = "DELETE";
/**
* 'GET' request method
*/
public static final String METHOD_GET = "GET";
/**
* 'HEAD' request method
*/
public static final String METHOD_HEAD = "HEAD";
/**
* 'OPTIONS' options method
*/
public static final String METHOD_OPTIONS = "OPTIONS";
/**
* 'POST' request method
*/
public static final String METHOD_POST = "POST";
/**
* 'PUT' request method
*/
public static final String METHOD_PUT = "PUT";
/**
* 'TRACE' request method
*/
public static final String METHOD_TRACE = "TRACE";
/**
* 'charset' header value parameter
*/
public static final String PARAM_CHARSET = "charset";
private static final String BOUNDARY = "00content0boundary00";
private static final String CONTENT_TYPE_MULTIPART = "multipart/form-data; boundary="
+ BOUNDARY;
private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
private static final String CONTENT_TYPE_JSON = "application/json";
private static final String ENCODING_GZIP = "gzip";
private static final String[] EMPTY_STRINGS = new String[0];
private static String getValidCharset(final String charset) {
if (charset != null)
return charset;
else
return CHARSET_UTF8;
}
public static class Base64 {
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte) '=';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
/** The 64 valid Base64 values. */
private final static byte[] _STANDARD_ALPHABET = { (byte) 'A',
(byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
(byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K',
(byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
(byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
(byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
(byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e',
(byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
(byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o',
(byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
(byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y',
(byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
(byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8',
(byte) '9', (byte) '+', (byte) '/' };
/** Defeats instantiation. */
private Base64() {
}
/**
* <p>
* Encodes up to three bytes of the array <var>source</var> and writes
* the resulting four Base64 bytes to <var>destination</var>. The source
* and destination arrays can be manipulated anywhere along their length
* by specifying <var>srcOffset</var> and <var>destOffset</var>. This
* method does not check to make sure your arrays are large enough to
* accomodate <var>srcOffset</var> + 3 for the <var>source</var> array
* or <var>destOffset</var> + 4 for the <var>destination</var> array.
* The actual number of significant bytes in your array is given by
* <var>numSigBytes</var>.
* </p>
* <p>
* This is the lowest level of the encoding methods with all possible
* parameters.
* </p>
*
* @param source
* the array to convert
* @param srcOffset
* the index where conversion begins
* @param numSigBytes
* the number of significant bytes in your array
* @param destination
* the array to hold the conversion
* @param destOffset
* the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(byte[] source, int srcOffset,
int numSigBytes, byte[] destination, int destOffset) {
byte[] ALPHABET = _STANDARD_ALPHABET;
int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8)
: 0)
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16)
: 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24)
: 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
}
}
/**
* Encode string as a byte array in Base64 annotation.
*
* @param string
* @return The Base64-encoded data as a string
*/
public static String encode(String string) {
byte[] bytes;
try {
bytes = string.getBytes(PREFERRED_ENCODING);
} catch (UnsupportedEncodingException e) {
bytes = string.getBytes();
}
return encodeBytes(bytes);
}
public static String encodeBytes(byte[] source) {
return encodeBytes(source, 0, source.length);
}
public static String encodeBytes(byte[] source, int off, int len) {
byte[] encoded = encodeBytesToBytes(source, off, len);
try {
return new String(encoded, PREFERRED_ENCODING);
} catch (UnsupportedEncodingException uue) {
return new String(encoded);
}
}
public static byte[] encodeBytesToBytes(byte[] source, int off, int len) {
if (source == null)
throw new NullPointerException("Cannot serialize a null array.");
if (off < 0)
throw new IllegalArgumentException(
"Cannot have negative offset: " + off);
if (len < 0)
throw new IllegalArgumentException(
"Cannot have length offset: " + len);
if (off + len > source.length)
throw new IllegalArgumentException(
String.format(
"Cannot have offset of %d and length of %d with array of length %d",
off, len, source.length));
// Bytes needed for actual encoding
int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0);
byte[] outBuff = new byte[encLen];
int d = 0;
int e = 0;
int len2 = len - 2;
for (; d < len2; d += 3, e += 4)
encode3to4(source, d + off, 3, outBuff, e);
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e);
e += 4;
}
if (e <= outBuff.length - 1) {
byte[] finalOut = new byte[e];
System.arraycopy(outBuff, 0, finalOut, 0, e);
return finalOut;
} else
return outBuff;
}
}
/**
* HTTP request exception whose cause is always an {@link IOException}
*/
public static class HttpRequestException extends RuntimeException {
private static final long serialVersionUID = -1170466989781746231L;
/**
* @param cause
*/
protected HttpRequestException(final IOException cause) {
super(cause);
}
/**
* Get {@link IOException} that triggered this request exception
*
* @return {@link IOException} cause
*/
@Override
public IOException getCause() {
return (IOException) super.getCause();
}
}
/**
* Operation that handles executing a callback once complete and handling
* nested exceptions
*
* @param <V>
*/
protected static abstract class Operation<V> implements Callable<V> {
/**
* Run operation
*
* @return result
* @throws HttpRequestException
* @throws IOException
*/
protected abstract V run() throws HttpRequestException, IOException;
/**
* Operation complete callback
*
* @throws IOException
*/
protected abstract void done() throws IOException;
public V call() throws HttpRequestException {
boolean thrown = false;
try {
return run();
} catch (HttpRequestException e) {
thrown = true;
throw e;
} catch (IOException e) {
thrown = true;
throw new HttpRequestException(e);
} finally {
try {
done();
} catch (IOException e) {
if (!thrown)
throw new HttpRequestException(e);
}
}
}
}
/**
* Class that ensures a {@link Closeable} gets closed with proper exception
* handling.
*
* @param <V>
*/
protected static abstract class CloseOperation<V> extends Operation<V> {
private final Closeable closeable;
private final boolean ignoreCloseExceptions;
/**
* Create closer for operation
*
* @param closeable
* @param ignoreCloseExceptions
*/
protected CloseOperation(final Closeable closeable,
final boolean ignoreCloseExceptions) {
this.closeable = closeable;
this.ignoreCloseExceptions = ignoreCloseExceptions;
}
@Override
protected void done() throws IOException {
if (closeable instanceof Flushable)
((Flushable) closeable).flush();
if (ignoreCloseExceptions)
try {
closeable.close();
} catch (IOException e) {
// Ignored
}
else
closeable.close();
}
}
/**
* Class that and ensures a {@link Flushable} gets flushed with proper
* exception handling.
*
* @param <V>
*/
protected static abstract class FlushOperation<V> extends Operation<V> {
private final Flushable flushable;
/**
* Create flush operation
*
* @param flushable
*/
protected FlushOperation(final Flushable flushable) {
this.flushable = flushable;
}
@Override
protected void done() throws IOException {
flushable.flush();
}
}
/**
* Request output stream
*/
public static class RequestOutputStream extends BufferedOutputStream {
private final CharsetEncoder encoder;
/**
* Create request output stream
*
* @param stream
* @param charset
* @param bufferSize
*/
public RequestOutputStream(final OutputStream stream,
final String charset, final int bufferSize) {
super(stream, bufferSize);
encoder = Charset.forName(getValidCharset(charset)).newEncoder();
}
/**
* Write string to stream
*
* @param value
* @return this stream
* @throws IOException
*/
public RequestOutputStream write(final String value) throws IOException {
final ByteBuffer bytes = encoder.encode(CharBuffer.wrap(value));
super.write(bytes.array(), 0, bytes.limit());
return this;
}
}
/**
* Encode the given URL as an ASCII {@link String}
* <p>
* This method ensures the path and query segments of the URL are properly
* encoded such as ' ' characters being encoded to '%20' or any UTF-8
* characters that are non-ASCII. No encoding of URLs is done by default by
* the {@link HttpRequest} constructors and so if URL encoding is needed
* this method should be called before calling the {@link HttpRequest}
* constructor.
*
* @param url
* @return encoded URL
* @throws HttpRequestException
*/
public static String encode(final CharSequence url)
throws HttpRequestException {
URL parsed;
try {
parsed = new URL(url.toString());
} catch (IOException e) {
throw new HttpRequestException(e);
}
String protocol = parsed.getProtocol();
String host = parsed.getHost();
int port = parsed.getPort();
if (port != -1)
host = host + ':' + Integer.toString(port);
String path = parsed.getPath();
String query = parsed.getQuery();
URI uri;
try {
uri = new URI(protocol, host, path, query, null);
} catch (URISyntaxException e) {
IOException io = new IOException("Parsing URI failed");
io.initCause(e);
throw new HttpRequestException(io);
}
return uri.toASCIIString();
}
/**
* Append given parameters to base URL
*
* @param url
* @param params
* @return URL with query params
*/
@SuppressWarnings("unchecked")
public static String append(String url, final Map<String, ?> params) {
if (params == null || params.isEmpty())
return url;
StringBuilder result = new StringBuilder();
if (!url.endsWith("/"))
url += "/";
Entry<String, ?> entry;
Object value;
Iterator<?> iterator = params.entrySet().iterator();
entry = (Entry<String, ?>) iterator.next();
result.append(entry.getKey());
result.append('=');
value = entry.getValue();
if (value != null)
result.append(value);
while (iterator.hasNext()) {
result.append('&');
entry = (Entry<String, ?>) iterator.next();
result.append(entry.getKey());
result.append('=');
value = entry.getValue();
if (value != null)
result.append(value);
}
return url + '?' + result.toString();
}
/**
* Start a 'GET' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest get(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_GET);
}
/**
* Start a 'GET' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* The query parameters to include as part of the baseUrl
* @param encode
* True if the params need to be encoded, otherwise false
* @return request
*/
public static HttpRequest get(final String baseUrl,
Map<String, String> params, boolean encode) {
String url = append(baseUrl, params);
if (encode)
url = encode(url);
return HttpRequest.get(url);
}
/**
* Start a 'GET' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest get(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_GET);
}
/**
* Start a 'POST' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest post(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_POST);
}
/**
* Start a 'POST' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest post(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_POST);
}
/**
* Start a 'POST' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* The query parameters to include as part of the baseUrl
* @param encode
* True if the params need to be encoded, otherwise false
* @return request
*/
public static HttpRequest post(final String baseUrl,
Map<String, String> params, boolean encode) {
String url = append(baseUrl, params);
if (encode)
url = encode(url);
return HttpRequest.post(url);
}
/**
* Start a 'PUT' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest put(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_PUT);
}
/**
* Start a 'PUT' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest put(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_PUT);
}
/**
* Start a 'PUT' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* The query parameters to include as part of the baseUrl
* @param encode
* True if the params need to be encoded, otherwise false
* @return request
*/
public static HttpRequest put(final String baseUrl,
Map<String, String> params, boolean encode) {
String url = append(baseUrl, params);
if (encode)
url = encode(url);
return HttpRequest.put(url);
}
/**
* Start a 'DELETE' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest delete(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_DELETE);
}
/**
* Start a 'DELETE' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest delete(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_DELETE);
}
/**
* Start a 'DELETE' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* The query parameters to include as part of the baseUrl
* @param encode
* True if the params need to be encoded, otherwise false
* @return request
*/
public static HttpRequest delete(final String baseUrl,
Map<String, String> params, boolean encode) {
String url = append(baseUrl, params);
if (encode)
url = encode(url);
return HttpRequest.delete(url);
}
/**
* Start a 'HEAD' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest head(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_HEAD);
}
/**
* Start a 'HEAD' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest head(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_HEAD);
}
/**
* Start an 'OPTIONS' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest options(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_OPTIONS);
}
/**
* Start an 'OPTIONS' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest options(final URL url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_OPTIONS);
}
/**
* Start a 'TRACE' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest trace(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_TRACE);
}
/**
* Start a 'TRACE' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest trace(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_TRACE);
}
/**
* Set the 'http.keepAlive' property to the given value.
* <p>
* This setting will apply to requests.
*
* @param keepAlive
*/
public static void keepAlive(final boolean keepAlive) {
setProperty("http.keepAlive", Boolean.toString(keepAlive));
}
/**
* Set the 'http.proxyHost' & 'https.proxyHost' properties to the given host
* value.
* <p>
* This setting will apply to requests.
*
* @param host
*/
public static void proxyHost(final String host) {
setProperty("http.proxyHost", host);
setProperty("https.proxyHost", host);
}
/**
* Set the 'http.proxyPort' & 'https.proxyPort' properties to the given port
* number.
* <p>
* This setting will apply to requests.
*
* @param port
*/
public static void proxyPort(final int port) {
final String portValue = Integer.toString(port);
setProperty("http.proxyPort", portValue);
setProperty("https.proxyPort", portValue);
}
/**
* Set the 'http.nonProxyHosts' properties to the given host values. Hosts
* will be separated by a '|' character.
* <p>
* This setting will apply to requests.
*
* @param hosts
*/
public static void nonProxyHosts(String... hosts) {
if (hosts == null)
hosts = new String[0];
if (hosts.length > 0) {
StringBuilder separated = new StringBuilder();
int last = hosts.length - 1;
for (int i = 0; i < last; i++)
separated.append(hosts[i]).append('|');
separated.append(hosts[last]);
setProperty("http.nonProxyHosts", separated.toString());
} else
setProperty("http.nonProxyHosts", null);
}
/**
* Set property to given value.
* <p>
* Specifying a null value will cause the property to be cleared
*
* @param name
* @param value
* @return previous value
*/
private static final String setProperty(final String name,
final String value) {
if (value != null)
return AccessController
.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return System.setProperty(name, value);
}
});
else
return AccessController
.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return System.clearProperty(name);
}
});
}
private final HttpURLConnection connection;
private RequestOutputStream output;
private boolean multipart;
private boolean form;
private boolean ignoreCloseExceptions = true;
private boolean uncompress = false;
private int bufferSize = 8192;
/**
* Create HTTP connection wrapper
*
* @param url
* @param method
* @throws HttpRequestException
*/
public HttpRequest(final CharSequence url, final String method)
throws HttpRequestException {
try {
connection = (HttpURLConnection) new URL(url.toString())
.openConnection();
connection.setRequestMethod(method);
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Create HTTP connection wrapper
*
* @param url
* @param method
* @throws HttpRequestException
*/
public HttpRequest(final URL url, final String method)
throws HttpRequestException {
try {
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
@Override
public String toString() {
return connection.getRequestMethod() + ' ' + connection.getURL();
}
/**
* Get underlying connection
*
* @return connection
*/
public HttpURLConnection getConnection() {
return connection;
}
/**
* Set whether or not to ignore exceptions that occur from calling
* {@link Closeable#close()}
* <p>
* The default value of this setting is <code>true</code>
*
* @param ignore
* @return this request
*/
public HttpRequest ignoreCloseExceptions(final boolean ignore) {
ignoreCloseExceptions = ignore;
return this;
}
/**
* Get whether or not exceptions thrown by {@link Closeable#close()} are
* ignored
*
* @return true if ignoring, false if throwing
*/
public boolean ignoreCloseExceptions() {
return ignoreCloseExceptions;
}
/**
* Get the status code of the response
*
* @return the response code
* @throws HttpRequestException
*/
public int code() throws HttpRequestException {
try {
closeOutput();
return connection.getResponseCode();
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Set the value of the given {@link AtomicInteger} to the status code of
* the response
*
* @param output
* @return this request
* @throws HttpRequestException
*/
public HttpRequest code(final AtomicInteger output)
throws HttpRequestException {
output.set(code());
return this;
}
/**
* Is the response code a 200 OK?
*
* @return true if 200, false otherwise
* @throws HttpRequestException
*/
public boolean ok() throws HttpRequestException {
return HTTP_OK == code();
}
/**
* Is the response code a 201 Created?
*
* @return true if 201, false otherwise
* @throws HttpRequestException
*/
public boolean created() throws HttpRequestException {
return HTTP_CREATED == code();
}
/**
* Is the response code a 500 Internal Server Error?
*
* @return true if 500, false otherwise
* @throws HttpRequestException
*/
public boolean serverError() throws HttpRequestException {
return HTTP_INTERNAL_ERROR == code();
}
/**
* Is the response code a 400 Bad Request?
*
* @return true if 400, false otherwise
* @throws HttpRequestException
*/
public boolean badRequest() throws HttpRequestException {
return HTTP_BAD_REQUEST == code();
}
/**
* Is the response code a 404 Not Found?
*
* @return true if 404, false otherwise
* @throws HttpRequestException
*/
public boolean notFound() throws HttpRequestException {
return HTTP_NOT_FOUND == code();
}
/**
* Is the response code a 304 Not Modified?
*
* @return true if 304, false otherwise
* @throws HttpRequestException
*/
public boolean notModified() throws HttpRequestException {
return HTTP_NOT_MODIFIED == code();
}
/**
* Get status message of the response
*
* @return message
* @throws HttpRequestException
*/
public String message() throws HttpRequestException {
try {
closeOutput();
return connection.getResponseMessage();
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Disconnect the connection
*
* @return this request
*/
public HttpRequest disconnect() {
connection.disconnect();
return this;
}
/**
* Set chunked streaming mode to the given size
*
* @param size
* @return this request
*/
public HttpRequest chunk(final int size) {
connection.setChunkedStreamingMode(size);
return this;
}
/**
* Set the size used when buffering and copying between streams
* <p>
* This size is also used for send and receive buffers created for both char
* and byte arrays
* <p>
* The default buffer size is 8,192 bytes
*
* @param size
* @return this request
*/
public HttpRequest bufferSize(final int size) {
if (size < 1)
throw new IllegalArgumentException("Size must be greater than zero");
bufferSize = size;
return this;
}
/**
* Get the configured buffer size
* <p>
* The default buffer size is 8,192 bytes
*
* @return buffer size
*/
public int bufferSize() {
return bufferSize;
}
/**
* Set whether or not the response body should be automatically uncompressed
* when read from.
* <p>
* This will only affect requests that have the 'Content-Encoding' response
* header set to 'gzip'.
* <p>
* This causes all receive methods to use a {@link GZIPInputStream} when
* applicable so that higher level streams and readers can read the data
* uncompressed.
* <p>
* Setting this option does not cause any request headers to be set
* automatically so {@link #acceptGzipEncoding()} should be used in
* conjunction with this setting to tell the server to gzip the response.
*
* @param uncompress
* @return this request
*/
public HttpRequest uncompress(final boolean uncompress) {
this.uncompress = uncompress;
return this;
}
/**
* Create byte array output stream
*
* @return stream
*/
protected ByteArrayOutputStream byteStream() {
final int size = contentLength();
if (size > 0)
return new ByteArrayOutputStream(size);
else
return new ByteArrayOutputStream();
}
/**
* Get response as {@link String} in given character set
* <p>
* This will fall back to using the UTF-8 character set if the given charset
* is null
*
* @param charset
* @return string
* @throws HttpRequestException
*/
public String body(final String charset) throws HttpRequestException {
final ByteArrayOutputStream output = byteStream();
try {
copy(buffer(), output);
return output.toString(getValidCharset(charset));
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Get response as {@link String} using character set returned from
* {@link #charset()}
*
* @return string
* @throws HttpRequestException
*/
public String body() throws HttpRequestException {
return body(charset());
}
/**
* Get response as byte array
*
* @return byte array
* @throws HttpRequestException
*/
public byte[] bytes() throws HttpRequestException {
final ByteArrayOutputStream output = byteStream();
try {
copy(buffer(), output);
} catch (IOException e) {
throw new HttpRequestException(e);
}
return output.toByteArray();
}
/**
* Get response in a buffered stream
*
* @see #bufferSize(int)
* @return stream
* @throws HttpRequestException
*/
public BufferedInputStream buffer() throws HttpRequestException {
return new BufferedInputStream(stream(), bufferSize);
}
/**
* Get stream to response body
*
* @return stream
* @throws HttpRequestException
*/
public InputStream stream() throws HttpRequestException {
InputStream stream;
if (code() < HTTP_BAD_REQUEST)
try {
stream = connection.getInputStream();
} catch (IOException e) {
throw new HttpRequestException(e);
}
else {
stream = connection.getErrorStream();
if (stream == null)
try {
stream = connection.getInputStream();
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
if (!uncompress || !ENCODING_GZIP.equals(contentEncoding()))
return stream;
else
try {
return new GZIPInputStream(stream);
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Get reader to response body using given character set.
* <p>
* This will fall back to using the UTF-8 character set if the given charset
* is null
*
* @param charset
* @return reader
* @throws HttpRequestException
*/
public InputStreamReader reader(final String charset)
throws HttpRequestException {
try {
return new InputStreamReader(stream(), getValidCharset(charset));
} catch (UnsupportedEncodingException e) {
throw new HttpRequestException(e);
}
}
/**
* Get reader to response body using the character set returned from
* {@link #charset()}
*
* @return reader
* @throws HttpRequestException
*/
public InputStreamReader reader() throws HttpRequestException {
return reader(charset());
}
/**
* Get buffered reader to response body using the given character set r and
* the configured buffer size
*
*
* @see #bufferSize(int)
* @param charset
* @return reader
* @throws HttpRequestException
*/
public BufferedReader bufferedReader(final String charset)
throws HttpRequestException {
return new BufferedReader(reader(charset), bufferSize);
}
/**
* Get buffered reader to response body using the character set returned
* from {@link #charset()} and the configured buffer size
*
* @see #bufferSize(int)
* @return reader
* @throws HttpRequestException
*/
public BufferedReader bufferedReader() throws HttpRequestException {
return bufferedReader(charset());
}
/**
* Stream response body to file
*
* @param file
* @return this request
* @throws HttpRequestException
*/
public HttpRequest receive(final File file) throws HttpRequestException {
final OutputStream output;
try {
output = new BufferedOutputStream(new FileOutputStream(file),
bufferSize);
} catch (FileNotFoundException e) {
throw new HttpRequestException(e);
}
return new CloseOperation<HttpRequest>(output, ignoreCloseExceptions) {
@Override
protected HttpRequest run() throws HttpRequestException,
IOException {
return receive(output);
}
}.call();
}
/**
* Stream response to given output stream
*
* @param output
* @return this request
* @throws HttpRequestException
*/
public HttpRequest receive(final OutputStream output)
throws HttpRequestException {
try {
return copy(buffer(), output);
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Stream response to given print stream
*
* @param output
* @return this request
* @throws HttpRequestException
*/
public HttpRequest receive(final PrintStream output)
throws HttpRequestException {
return receive((OutputStream) output);
}
/**
* Receive response into the given appendable
*
* @param appendable
* @return this request
* @throws HttpRequestException
*/
public HttpRequest receive(final Appendable appendable)
throws HttpRequestException {
final BufferedReader reader = bufferedReader();
return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) {
@Override
public HttpRequest run() throws IOException {
final CharBuffer buffer = CharBuffer.allocate(bufferSize);
int read;
while ((read = reader.read(buffer)) != -1) {
buffer.rewind();
appendable.append(buffer, 0, read);
buffer.rewind();
}
return HttpRequest.this;
}
}.call();
}
/**
* Receive response into the given writer
*
* @param writer
* @return this request
* @throws HttpRequestException
*/
public HttpRequest receive(final Writer writer) throws HttpRequestException {
final BufferedReader reader = bufferedReader();
return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) {
@Override
public HttpRequest run() throws IOException {
return copy(reader, writer);
}
}.call();
}
/**
* Set read timeout on connection to given value
*
* @param timeout
* @return this request
*/
public HttpRequest readTimeout(final int timeout) {
connection.setReadTimeout(timeout);
return this;
}
/**
* Set connect timeout on connection to given value
*
* @param timeout
* @return this request
*/
public HttpRequest connectTimeout(final int timeout) {
connection.setConnectTimeout(timeout);
return this;
}
/**
* Set header name to given value
*
* @param name
* @param value
* @return this request
*/
public HttpRequest header(final String name, final String value) {
connection.setRequestProperty(name, value);
return this;
}
/**
* Set header name to given value
*
* @param name
* @param value
* @return this request
*/
public HttpRequest header(final String name, final Number value) {
return header(name, value != null ? value.toString() : null);
}
/**
* Set all headers found in given map where the keys are the header names
* and the values are the header values
*
* @param headers
* @return this request
*/
public HttpRequest headers(final Map<String, String> headers) {
for (Entry<String, String> header : headers.entrySet())
header(header);
return this;
}
/**
* Set header to have given entry's key as the name and value as the value
*
* @param header
* @return this request
*/
public HttpRequest header(final Entry<String, String> header) {
return header(header.getKey(), header.getValue());
}
/**
* Get a response header
*
* @param name
* @return response header
*/
public String header(final String name) {
return connection.getHeaderField(name);
}
/**
* Get all the response headers
*
* @return map of response header names to their value(s)
*/
public Map<String, List<String>> headers() {
return connection.getHeaderFields();
}
/**
* Get a date header from the response falling back to returning -1 if the
* header is missing or parsing fails
*
* @param name
* @return date, -1 on failures
*/
public long dateHeader(final String name) {
return dateHeader(name, -1L);
}
/**
* Get a date header from the response falling back to returning the given
* default value if the header is missing or parsing fails
*
* @param name
* @param defaultValue
* @return date, -1 on failures
*/
public long dateHeader(final String name, final long defaultValue) {
return connection.getHeaderFieldDate(name, defaultValue);
}
/**
* Get an integer header from the response falling back to returning -1 if
* the header is missing or parsing fails
*
* @param name
* @return header value as an integer, -1 when missing or parsing fails
*/
public int intHeader(final String name) {
return intHeader(name, -1);
}
/**
* Get an integer header value from the response falling back to the given
* default value if the header is missing or if parsing fails
*
* @param name
* @param defaultValue
* @return header value as an integer, default value when missing or parsing
* fails
*/
public int intHeader(final String name, final int defaultValue) {
return connection.getHeaderFieldInt(name, defaultValue);
}
/**
* Get all values of the given header from the response
*
* @param name
* @return non-null but possibly empty array of {@link String} header values
*/
public String[] headers(final String name) {
final Map<String, List<String>> headers = headers();
if (headers == null || headers.isEmpty())
return EMPTY_STRINGS;
final List<String> values = headers.get(name);
if (values != null && !values.isEmpty())
return values.toArray(new String[values.size()]);
else
return EMPTY_STRINGS;
}
/**
* Get parameter with given name from header value in response
*
* @param headerName
* @param paramName
* @return parameter value or null if missing
*/
public String parameter(final String headerName, final String paramName) {
return getParam(header(headerName), paramName);
}
/**
* Get all parameters from header value in response
* <p>
* This will be all key=value pairs after the first ';' that are separated
* by a ';'
*
* @param headerName
* @return non-null but possibly empty map of parameter headers
*/
public Map<String, String> parameters(final String headerName) {
return getParams(header(headerName));
}
/**
* Get parameter values from header value
*
* @param header
* @return parameter value or null if none
*/
protected Map<String, String> getParams(final String header) {
if (header == null || header.length() == 0)
return Collections.emptyMap();
final int headerLength = header.length();
int start = header.indexOf(';') + 1;
if (start == 0 || start == headerLength)
return Collections.emptyMap();
int end = header.indexOf(';', start);
if (end == -1)
end = headerLength;
Map<String, String> params = new LinkedHashMap<String, String>();
while (start < end) {
int nameEnd = header.indexOf('=', start);
if (nameEnd != -1 && nameEnd < end) {
String name = header.substring(start, nameEnd).trim();
if (name.length() > 0) {
String value = header.substring(nameEnd + 1, end).trim();
int length = value.length();
if (length != 0)
if (length > 2 && '"' == value.charAt(0)
&& '"' == value.charAt(length - 1))
params.put(name, value.substring(1, length - 1));
else
params.put(name, value);
}
}
start = end + 1;
end = header.indexOf(';', start);
if (end == -1)
end = headerLength;
}
return params;
}
/**
* Get parameter value from header value
*
* @param value
* @param paramName
* @return parameter value or null if none
*/
protected String getParam(final String value, final String paramName) {
if (value == null || value.length() == 0)
return null;
final int length = value.length();
int start = value.indexOf(';') + 1;
if (start == 0 || start == length)
return null;
int end = value.indexOf(';', start);
if (end == -1)
end = length;
while (start < end) {
int nameEnd = value.indexOf('=', start);
if (nameEnd != -1 && nameEnd < end
&& paramName.equals(value.substring(start, nameEnd).trim())) {
String paramValue = value.substring(nameEnd + 1, end).trim();
int valueLength = paramValue.length();
if (valueLength != 0)
if (valueLength > 2 && '"' == paramValue.charAt(0)
&& '"' == paramValue.charAt(valueLength - 1))
return paramValue.substring(1, valueLength - 1);
else
return paramValue;
}
start = end + 1;
end = value.indexOf(';', start);
if (end == -1)
end = length;
}
return null;
}
/**
* Get 'charset' parameter from 'Content-Type' response header
*
* @return charset or null if none
*/
public String charset() {
return parameter(HEADER_CONTENT_TYPE, PARAM_CHARSET);
}
/**
* Set the 'User-Agent' header to given value
*
* @param value
* @return this request
*/
public HttpRequest userAgent(final String value) {
return header(HEADER_USER_AGENT, value);
}
/**
* Set value of {@link HttpURLConnection#setUseCaches(boolean)}
*
* @param useCaches
* @return this request
*/
public HttpRequest useCaches(final boolean useCaches) {
connection.setUseCaches(useCaches);
return this;
}
/**
* Set the 'Accept-Encoding' header to given value
*
* @param value
* @return this request
*/
public HttpRequest acceptEncoding(final String value) {
return header(HEADER_ACCEPT_ENCODING, value);
}
/**
* Set the 'Accept-Encoding' header to 'gzip'
*
* @see #uncompress(boolean)
* @return this request
*/
public HttpRequest acceptGzipEncoding() {
return acceptEncoding(ENCODING_GZIP);
}
/**
* Set the 'Accept-Charset' header to given value
*
* @param value
* @return this request
*/
public HttpRequest acceptCharset(final String value) {
return header(HEADER_ACCEPT_CHARSET, value);
}
/**
* Get the 'Content-Encoding' header from the response
*
* @return this request
*/
public String contentEncoding() {
return header(HEADER_CONTENT_ENCODING);
}
/**
* Get the 'Server' header from the response
*
* @return server
*/
public String server() {
return header(HEADER_SERVER);
}
/**
* Get the 'Date' header from the response
*
* @return date value, -1 on failures
*/
public long date() {
return dateHeader(HEADER_DATE);
}
/**
* Get the 'Cache-Control' header from the response
*
* @return cache control
*/
public String cacheControl() {
return header(HEADER_CACHE_CONTROL);
}
/**
* Get the 'ETag' header from the response
*
* @return entity tag
*/
public String eTag() {
return header(HEADER_ETAG);
}
/**
* Get the 'Expires' header from the response
*
* @return expires value, -1 on failures
*/
public long expires() {
return dateHeader(HEADER_EXPIRES);
}
/**
* Get the 'Last-Modified' header from the response
*
* @return last modified value, -1 on failures
*/
public long lastModified() {
return dateHeader(HEADER_LAST_MODIFIED);
}
/**
* Get the 'Location' header from the response
*
* @return location
*/
public String location() {
return header(HEADER_LOCATION);
}
/**
* Set the 'Authorization' header to given value
*
* @param value
* @return this request
*/
public HttpRequest authorization(final String value) {
return header(HEADER_AUTHORIZATION, value);
}
/**
* Set the 'Authorization' header to given values in Basic authentication
* format
*
* @param name
* @param password
* @return this request
*/
public HttpRequest basic(final String name, final String password) {
return authorization("Basic " + Base64.encode(name + ':' + password));
}
/**
* Set the 'If-Modified-Since' request header to the given value
*
* @param value
* @return this request
*/
public HttpRequest ifModifiedSince(final long value) {
connection.setIfModifiedSince(value);
return this;
}
/**
* Set the 'If-None-Match' request header to the given value
*
* @param value
* @return this request
*/
public HttpRequest ifNoneMatch(final String value) {
return header(HEADER_IF_NONE_MATCH, value);
}
/**
* Set the 'Content-Type' request header to the given value
*
* @param value
* @return this request
*/
public HttpRequest contentType(final String value) {
return contentType(value, null);
}
/**
* Set the 'Content-Type' request header to the given value and charset
*
* @param value
* @param charset
* @return this request
*/
public HttpRequest contentType(final String value, final String charset) {
if (charset != null) {
final String separator = "; " + PARAM_CHARSET + '=';
return header(HEADER_CONTENT_TYPE, value + separator + charset);
} else
return header(HEADER_CONTENT_TYPE, value);
}
/**
* Get the 'Content-Type' header from the response
*
* @return response header value
*/
public String contentType() {
return header(HEADER_CONTENT_TYPE);
}
/**
* Get the 'Content-Type' header from the response
*
* @return response header value
*/
public int contentLength() {
return intHeader(HEADER_CONTENT_LENGTH);
}
/**
* Set the 'Content-Length' request header to the given value
*
* @param value
* @return this request
*/
public HttpRequest contentLength(final String value) {
return contentLength(Integer.parseInt(value));
}
/**
* Set the 'Content-Length' request header to the given value
*
* @param value
* @return this request
*/
public HttpRequest contentLength(final int value) {
connection.setFixedLengthStreamingMode(value);
return this;
}
/**
* Set the 'Accept' header to given value
*
* @param value
* @return this request
*/
public HttpRequest accept(final String value) {
return header(HEADER_ACCEPT, value);
}
/**
* Set the 'Accept' header to 'application/json'
*
* @return this request
*/
public HttpRequest acceptJson() {
return accept(CONTENT_TYPE_JSON);
}
/**
* Copy from input stream to output stream
*
* @param input
* @param output
* @return this request
* @throws IOException
*/
protected HttpRequest copy(final InputStream input,
final OutputStream output) throws IOException {
return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) {
@Override
public HttpRequest run() throws IOException {
final byte[] buffer = new byte[bufferSize];
int read;
while ((read = input.read(buffer)) != -1)
output.write(buffer, 0, read);
return HttpRequest.this;
}
}.call();
}
/**
* Copy from reader to writer
*
* @param input
* @param output
* @return this request
* @throws IOException
*/
protected HttpRequest copy(final Reader input, final Writer output)
throws IOException {
return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) {
@Override
public HttpRequest run() throws IOException {
final char[] buffer = new char[bufferSize];
int read;
while ((read = input.read(buffer)) != -1)
output.write(buffer, 0, read);
return HttpRequest.this;
}
}.call();
}
/**
* Close output stream
*
* @return this request
* @throws HttpRequestException
* @throws IOException
*/
protected HttpRequest closeOutput() throws IOException {
if (output == null)
return this;
if (multipart)
output.write("\r\n--" + BOUNDARY + "--\r\n");
if (ignoreCloseExceptions)
try {
output.close();
} catch (IOException ignored) {
// Ignored
}
else
output.close();
output = null;
return this;
}
/**
* Open output stream
*
* @return this request
* @throws IOException
*/
protected HttpRequest openOutput() throws IOException {
if (output != null)
return this;
connection.setDoOutput(true);
final String charset = getParam(
connection.getRequestProperty(HEADER_CONTENT_TYPE),
PARAM_CHARSET);
output = new RequestOutputStream(connection.getOutputStream(), charset,
bufferSize);
return this;
}
/**
* Start part of a multipart
*
* @return this request
* @throws IOException
*/
protected HttpRequest startPart() throws IOException {
if (!multipart) {
multipart = true;
contentType(CONTENT_TYPE_MULTIPART).openOutput();
output.write("--" + BOUNDARY + "\r\n");
} else
output.write("\r\n--" + BOUNDARY + "\r\n");
return this;
}
/**
* Write part header
*
* @param name
* @param filename
* @return this request
* @throws IOException
*/
protected HttpRequest writePartHeader(final String name,
final String filename) throws IOException {
final StringBuilder partBuffer = new StringBuilder();
partBuffer.append("form-data; name=\"").append(name);
if (filename != null)
partBuffer.append("\"; filename=\"").append(filename);
partBuffer.append('"');
return partHeader("Content-Disposition", partBuffer.toString());
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param part
* @return this request
*/
public HttpRequest part(final String name, final String part) {
return part(name, null, part);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param filename
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final String filename,
final String part) throws HttpRequestException {
try {
startPart();
writePartHeader(name, filename);
output.write(part);
} catch (IOException e) {
throw new HttpRequestException(e);
}
return this;
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final Number part)
throws HttpRequestException {
return part(name, null, part);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param filename
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final String filename,
final Number part) throws HttpRequestException {
return part(name, filename, part != null ? part.toString() : null);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final File part)
throws HttpRequestException {
return part(name, null, part);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param filename
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final String filename,
final File part) throws HttpRequestException {
final InputStream stream;
try {
stream = new BufferedInputStream(new FileInputStream(part));
} catch (IOException e) {
throw new HttpRequestException(e);
}
return part(name, filename, stream);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final InputStream part)
throws HttpRequestException {
return part(name, null, part);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param filename
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final String filename,
final InputStream part) throws HttpRequestException {
try {
startPart();
writePartHeader(name, filename);
copy(part, output);
} catch (IOException e) {
throw new HttpRequestException(e);
}
return this;
}
/**
* Write a multipart header to the response body
*
* @param name
* @param value
* @return this request
* @throws HttpRequestException
*/
public HttpRequest partHeader(final String name, final String value)
throws HttpRequestException {
return send(name).send(": ").send(value).send("\r\n\r\n");
}
/**
* Write contents of file to request body
*
* @param input
* @return this request
* @throws HttpRequestException
*/
public HttpRequest send(final File input) throws HttpRequestException {
final InputStream stream;
try {
stream = new BufferedInputStream(new FileInputStream(input));
} catch (FileNotFoundException e) {
throw new HttpRequestException(e);
}
return send(stream);
}
/**
* Write byte array to request body
*
* @param input
* @return this request
* @throws HttpRequestException
*/
public HttpRequest send(final byte[] input) throws HttpRequestException {
return send(new ByteArrayInputStream(input));
}
/**
* Write stream to request body
* <p>
* The given stream will be closed once sending completes
*
* @param input
* @return this request
* @throws HttpRequestException
*/
public HttpRequest send(final InputStream input)
throws HttpRequestException {
try {
openOutput();
copy(input, output);
} catch (IOException e) {
throw new HttpRequestException(e);
}
return this;
}
/**
* Write reader to request body
* <p>
* The given reader will be closed once sending completes
*
* @param input
* @return this request
* @throws HttpRequestException
*/
public HttpRequest send(final Reader input) throws HttpRequestException {
try {
openOutput();
} catch (IOException e) {
throw new HttpRequestException(e);
}
final Writer writer = new OutputStreamWriter(output,
output.encoder.charset());
return new FlushOperation<HttpRequest>(writer) {
@Override
protected HttpRequest run() throws IOException {
return copy(input, writer);
}
}.call();
}
/**
* Write char sequence to request body
* <p>
* The charset configured via {@link #contentType(String)} will be used and
* UTF-8 will be used if it is unset.
*
* @param value
* @return this request
* @throws HttpRequestException
*/
public HttpRequest send(final CharSequence value)
throws HttpRequestException {
try {
openOutput();
output.write(value.toString());
} catch (IOException e) {
throw new HttpRequestException(e);
}
return this;
}
/**
* Create writer to request output stream
*
* @return writer
* @throws HttpRequestException
*/
public OutputStreamWriter writer() throws HttpRequestException {
try {
openOutput();
return new OutputStreamWriter(output, output.encoder.charset());
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Write the values in the map as form data to the request body
* <p>
* The pairs specified will be URL-encoded in UTF-8 and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param values
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Map<?, ?> values) throws HttpRequestException {
return form(values, CHARSET_UTF8);
}
/**
* Write the key and value in the entry as form data to the request body
* <p>
* The pair specified will be URL-encoded in UTF-8 and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param entry
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Entry<?, ?> entry)
throws HttpRequestException {
return form(entry, CHARSET_UTF8);
}
/**
* Write the key and value in the entry as form data to the request body
* <p>
* The pair specified will be URL-encoded and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param entry
* @param charset
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Entry<?, ?> entry, final String charset)
throws HttpRequestException {
return form(entry.getKey(), entry.getValue(), charset);
}
/**
* Write the name/value pair as form data to the request body
* <p>
* The pair specified will be URL-encoded in UTF-8 and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param name
* @param value
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Object name, final Object value)
throws HttpRequestException {
return form(name, value, CHARSET_UTF8);
}
/**
* Write the name/value pair as form data to the request body
* <p>
* The values specified will be URL-encoded and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param name
* @param value
* @param charset
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Object name, final Object value,
final String charset) throws HttpRequestException {
final boolean first = !form;
if (first) {
contentType(CONTENT_TYPE_FORM, charset);
form = true;
}
try {
openOutput();
if (!first)
output.write('&');
output.write(URLEncoder.encode(name.toString(), charset));
output.write('=');
if (value != null)
output.write(URLEncoder.encode(value.toString(), charset));
} catch (IOException e) {
throw new HttpRequestException(e);
}
return this;
}
/**
* Write the values in the map as encoded form data to the request body
*
* @param values
* @param charset
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Map<?, ?> values, final String charset)
throws HttpRequestException {
if (!values.isEmpty())
for (Entry<?, ?> entry : values.entrySet())
form(entry, charset);
return this;
}
/**
* Configure HTTPS connection to trust all certificates
* <p>
* This method does nothing if the current request is not a HTTPS request
*
* @return this request
* @throws HttpRequestException
*/
public HttpRequest trustAllCerts() throws HttpRequestException {
if (!(connection instanceof HttpsURLConnection))
return this;
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) {
// Intentionally left blank
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) {
// Intentionally left blank
}
} };
final SSLContext context;
try {
context = SSLContext.getInstance("TLS");
context.init(null, trustAllCerts, new SecureRandom());
} catch (GeneralSecurityException e) {
IOException ioException = new IOException(
"Security exception configuring SSL context");
ioException.initCause(e);
throw new HttpRequestException(ioException);
}
((HttpsURLConnection) connection).setSSLSocketFactory(context
.getSocketFactory());
return this;
}
/**
* Configure HTTPS connection to trust all hosts using a custom
* {@link HostnameVerifier} that always returns <code>true</code> for each
* host verified
* <p>
* This method does nothing if the current request is not a HTTPS request
*
* @return this request
*/
public HttpRequest trustAllHosts() {
if (!(connection instanceof HttpsURLConnection))
return this;
((HttpsURLConnection) connection)
.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return this;
}
} |
package com.inaetics.demonstrator;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.inaetics.demonstrator.controller.DownloadTask;
import com.inaetics.demonstrator.controller.MyPagerAdapter;
import com.inaetics.demonstrator.model.BundleStatus;
import com.inaetics.demonstrator.model.Model;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import java.util.Scanner;
import apache.celix.Celix;
import apache.celix.model.CelixUpdate;
import apache.celix.model.Config;
public class MainActivity extends AppCompatActivity implements Observer {
private Model model;
private Config config;
private Button btn_start;
private ViewPager pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.pager_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
//Initiate celix
Celix celix = Celix.getInstance();
celix.addObserver(this);
pager = (ViewPager) findViewById(R.id.pager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(pager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
pager.setOffscreenPageLimit(2);
model = Model.getInstance();
model.setContext(this);
config = model.getConfig();
// Only one time!! After configuration change don't do it again.
if (!model.areBundlesMoved()) {
File dirLocation = getExternalFilesDir(null);
if (dirLocation == null) {
dirLocation = getCacheDir();
}
model.setBundleLocation(dirLocation.getAbsolutePath());
model.moveBundles(getResources().getAssets());
}
btn_start = (Button) findViewById(R.id.start_btn);
if (model.getCelixStatus() == BundleStatus.CELIX_RUNNING) {
setRunning();
} else {
setStopped();
}
}
@Override
protected void onStart() {
super.onStart();
registerReceiver(mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(mConnReceiver);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings_editProperties:
final EditText edittext = new EditText(this.getApplicationContext());
String props = config.propertiesToString();
showInputDialog(edittext, "Edit Properties", "", props, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
config.setProperties(edittext.getText().toString());
Toast.makeText(getBaseContext(), "properties changed", Toast.LENGTH_SHORT).show();
}
});
return true;
case R.id.action_startQR:
new IntentIntegrator(this)
.setCaptureActivity(ScanActivity.class)
.setOrientationLocked(false)
.initiateScan();
return true;
case R.id.action_download:
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.DialogTheme);
final EditText text = new EditText(this);
builder.setView(text);
builder.setPositiveButton("Download", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
download(text.getText().toString());
}
});
builder.setNegativeButton("Cancel", null);
builder.setTitle("Download bundle from URL");
AlertDialog realDialog = builder.create();
realDialog.getWindow().getAttributes().width = WindowManager.LayoutParams.MATCH_PARENT;
realDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
private void download(String url) {
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Downloading");
progress.setMessage("Wait while downloading");
progress.show();
DownloadTask task = new DownloadTask(this, progress);
task.execute(url);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
String content = result.getContents();
try {
URL url = new URL(content);
// Is a url!
download(content);
} catch (MalformedURLException e) {
//Not an url
Scanner sc = new Scanner(content);
boolean autostart = false;
while (sc.hasNextLine()) {
String[] keyValue = sc.nextLine().split("=");
if (keyValue[0].equals("cosgi.auto.start.1")) {
autostart = true;
String startBundles = "";
Scanner bscan = new Scanner(keyValue[1]);
while (bscan.hasNext()) {
startBundles += model.getBundleLocation() + "/" + bscan.next() + " ";
}
bscan.close();
config.putProperty(keyValue[0], startBundles);
} else {
try {
config.putProperty(keyValue[0], keyValue[1]);
} catch (ArrayIndexOutOfBoundsException ex) {
//Ignore property there is no key/value combination
Log.e("Scanner", "couldn't scan: " + Arrays.toString(keyValue));
}
}
}
sc.close();
if (autostart && model.getCelixStatus() != BundleStatus.CELIX_RUNNING) {
Celix.getInstance().startFramework(getFilesDir() + "/" + Config.CONFIG_PROPERTIES);
}
Toast.makeText(this, "Scanned QR", Toast.LENGTH_SHORT).show();
}
}
}
}
/**
* Dialog used to show the settings
*
* @param edittext Edittext which contains all the settings
* @param title Title of the dialog
* @param msg Message of the dialog
* @param text Text inside the edittext
* @param positiveListener Onclicklistener for the change button
*/
private void showInputDialog(final EditText edittext, String title, String msg, String text, DialogInterface.OnClickListener positiveListener) {
AlertDialog.Builder alert = new AlertDialog.Builder(this, R.style.DialogTheme);
if (text != null) {
edittext.setText(text);
edittext.setTextColor(ContextCompat.getColor(this,android.R.color.black));
edittext.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
}
alert.setTitle(title);
alert.setMessage(msg);
alert.setView(edittext);
alert.setPositiveButton("Save", positiveListener);
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
AlertDialog realDialog = alert.create();
realDialog.getWindow().getAttributes().width = WindowManager.LayoutParams.MATCH_PARENT;
realDialog.show();
}
/**
* Method triggered when celix is running.
* Changes button, onclicklistener to a stop button.
*/
private void setRunning() {
btn_start.setText("STOP");
btn_start.setBackgroundColor(ContextCompat.getColor(this, android.R.color.holo_red_light));
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Celix.getInstance().stopFramework();
btn_start.setEnabled(false);
}
});
btn_start.setEnabled(true);
}
/**
* Method triggered when celix is stopped (Not running)
* Changes button to a start button and the onclicklistener.
*/
private void setStopped() {
btn_start.setText("Start");
btn_start.setBackgroundColor(ContextCompat.getColor(this, R.color.celix_blue));
btn_start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = "";
config.putProperty("cosgi.auto.start.1", str);
btn_start.setEnabled(false);
Celix.getInstance().startFramework(getFilesDir() + "/" + Config.CONFIG_PROPERTIES);
}
});
btn_start.setEnabled(true);
}
// Used to determine if the ip has changed.
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("Network", "network changes detected");
String ip = config.getLocalIpAddress();
if (ip != null) {
if (!config.getProperty("RSA_IP").equals(ip)) {
Log.v("RSA_IP", "Putting new IP" + ip);
config.putProperty("RSA_IP", ip);
}
if (!config.getProperty("DISCOVERY_CFG_SERVER_IP").equals(ip)) {
Log.v("DISCOVERY_CFG_SERVER_IP", "Putting new IP" + ip);
config.putProperty("DISCOVERY_CFG_SERVER_IP", ip);
}
}
}
};
@Override
public void update(Observable observable, Object data) {
if(data == CelixUpdate.CELIX_CHANGED) {
if(Celix.getInstance().isCelixRunning()) {
setRunning();
} else {
setStopped();
}
}
}
} |
package com.liuyang.code.controllers;
import com.liuyang.code.R;
/**
* @author Liuyang 2016/2/9.
*/
public class AsyncTask extends BaseFragment {
private android.os.AsyncTask task;
@Override
protected int layoutId() {
return R.layout.async_task;
}
@Override
protected void init() {
task = new MockAsyncTask();
task.execute(new Object[]{"AsyncTask"});
}
@Override
protected void refresh() {
}
@Override
public void onDestroy() {
super.onDestroy();
if (task != null) task.cancel(true);
}
private class MockAsyncTask extends android.os.AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
show("pre execute");
}
@Override
protected String doInBackground(String... params) {
int i = 0;
try {
while (i++ < 5) {
Thread.sleep(3000);
publishProgress(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return params[0];
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
show(String.valueOf(values[0]));
}
@Override
protected void onPostExecute(String result) {
show("post execute " + result);
}
}
} |
package com.mattermost.mattermost;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebResourceRequest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.KeyEvent;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.mattermost.model.User;
import com.mattermost.service.IResultListener;
import com.mattermost.service.MattermostService;
import com.mattermost.service.Promise;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class MainActivity extends WebViewActivity {
WebView webView;
Uri appUri;
String senderID;
GoogleCloudMessaging gcm;
ProgressDialog dialog;
long timeAway;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appUri = Uri.parse(service.getBaseUrl());
webView = (WebView) findViewById(R.id.web_view);
initProgressBar(R.id.webViewProgress);
initWebView(webView);
}
protected void loadRootView() {
String url = service.getBaseUrl();
if (!url.endsWith("/"))
url += "/";
if (MattermostService.service.GetLastPath().length() > 0) {
Log.i("loadRootView", "loading " + MattermostService.service.GetLastPath());
url = MattermostService.service.GetLastPath();
}
webView.loadUrl(url);
dialog = new ProgressDialog(this);
dialog.setMessage(this.getText(R.string.loading));
dialog.setCancelable(false);
dialog.show();
}
@Override
protected void onPause() {
Log.i("MainActivity", "paused");
webView.onPause();
webView.pauseTimers();
timeAway = System.currentTimeMillis();
// We only set the last path if it was a channel view
if (webView.getUrl().contains("/channels/")) {
MattermostService.service.SetLastPath(webView.getUrl());
}
super.onPause();
}
@Override
protected void onResume() {
Log.i("MainActivity", "resumed");
webView.onResume();
webView.resumeTimers();
if ((System.currentTimeMillis() - timeAway) > 1000 * 60 * 5) {
loadRootView();
}
super.onResume();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Log.i("Back", webView.getUrl());
if (webView.getUrl().equals(MattermostService.service.getBaseUrl())) {
MattermostService.service.logout();
Intent intent = new Intent(this, SelectServerActivity.class);
startActivityForResult(intent, SelectServerActivity.START_CODE);
finish();
return true;
} else if (webView.getUrl().endsWith("/login")) {
MattermostService.service.logout();
Intent intent = new Intent(this, SelectServerActivity.class);
startActivityForResult(intent, SelectServerActivity.START_CODE);
finish();
return true;
} else if (webView.getUrl().endsWith("/select_team")) {
onLogout();
return true;
} else if (webView.canGoBack()) {
webView.goBack();
return true;
} else {
finish();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
protected void setWebViewClient(WebView view) {
view.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
dialog.hide();
Log.i("onPageFinished", "onPageFinished while loading");
Log.i("onPageFinished", url);
if (url.equals("about:blank")) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle(R.string.error_retry);
alert.setPositiveButton(R.string.error_logout, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
MainActivity.this.onLogout();
}
});
alert.setNegativeButton(R.string.error_refresh, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
MainActivity.this.loadRootView();
}
});
alert.show();
}
}
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
Log.e("onReceivedHttpError", "onReceivedHttpError while loading");
StringBuilder total = new StringBuilder();
if (errorResponse.getData() != null) {
BufferedReader r = new BufferedReader(new InputStreamReader(errorResponse.getData()));
String line;
try {
while ((line = r.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
total.append("failed to read data");
}
} else {
total.append("no data");
}
Log.e("onReceivedHttpError", total.toString());
}
@Override
public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
Log.e("onReceivedErrord", "onReceivedError while loading (d)");
Log.e("onReceivedErrord", errorCode + " " + description + " " + failingUrl);
webView.loadUrl("about:blank");
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (url.startsWith("mailto:")) {
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(i);
return true;
}
if (url.startsWith("tel:")) {
Intent i = new Intent(Intent.ACTION_DIAL, uri);
startActivity(i);
return true;
}
// Do not open in other browser if gitlab
if (uri.getPath().contains("/oauth/authorize")) {
return false;
}
// Do not open in other browser if gitlab
if (uri.getPath().contains("/oauth/token")) {
return false;
}
// Do not open in other browser if gitlab
if (uri.getPath().contains("/api/v3/user")) {
return false;
}
// Do not open in other browser if gitlab
if (uri.getPath().contains("/users/sign_in")) {
return false;
}
// Do not open in other browser if google, for v1 or v2
if (uri.getPath().contains("/oauth2/v2/auth") || uri.getPath().contains("/oauth2/auth")) {
return false;
}
// Do not open in other browser if google
if (uri.getPath().contains("/oauth2/v4/token")) {
return false;
}
// Do not open in other browser if google
if (uri.getPath().contains("/ServiceLogin")) {
return false;
}
// Do not open in other browser if google and multiple accounts or MFA
if (uri.getPath().contains("/AccountChooser") || uri.getPath().contains("/signin/challenge")) {
return false;
}
// Do not open in other browser if callback from google to gitlab
if (uri.getPath().contains("/users/auth/google_oauth2/callback")) {
return false;
}
// Do not open in other browser if office365
if (uri.getPath().contains("/oauth2/v2.0/authorize")) {
return false;
}
// Do not open in other browser if office365
if (uri.getPath().contains("/oauth2/v2.0/token")) {
return false;
}
// Do not open in other browser if office365
if (uri.getPath().contains("/oauth20_authorize.srf")) {
return false;
}
// Do not open in other browser if SAML
if (uri.getQuery() != null && uri.getQuery().contains("SAMLRequest")) {
return false;
}
if (!uri.getHost().equalsIgnoreCase(appUri.getHost())) {
openUrl(uri);
return true;
}
if (uri.getPath().startsWith("/static/help")) {
openUrl(uri);
return true;
}
if (uri.getPath().contains("/files/get/")) {
openUrl(uri);
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
// Check to see if we need to attach the device Id
if (url.toLowerCase().contains("/channels/")) {
if (!MattermostService.service.isAttached()) {
Log.i("MainActivity", "Attempting to attach device id");
MattermostService.service.init(MattermostService.service.getBaseUrl());
Promise<User> p = MattermostService.service.attachDevice();
if (p != null) {
p.then(new IResultListener<User>() {
@Override
public void onResult(Promise<User> promise) {
if (promise.getError() != null) {
Log.e("AttachDeviceId", promise.getError());
} else {
Log.i("AttachDeviceId", "Attached device_id to session");
MattermostService.service.SetAttached();
}
}
});
}
}
}
// Check if deviceID is missing
if (url.toLowerCase().contains("/login")) {
MattermostService.service.SetAttached(false);
}
// Check to see if the user was trying to logout
if (url.toLowerCase().endsWith("/logout")) {
MattermostApplication.handler.post(new Runnable() {
@Override
public void run() {
onLogout();
}
});
}
return super.shouldInterceptRequest(view, url);
}
});
}
private void openUrl(Uri uri) {
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
@Override
protected void onLogout() {
Log.i("MainActivity", "onLogout called");
super.onLogout();
MattermostService.service.logout();
super.onBackPressed();
}
} |
package in.testpress.testpress.ui;
import android.accounts.AccountsException;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.customtabs.CustomTabsIntent;
import android.support.design.widget.Snackbar;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.format.DateUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.theartofdev.edmodo.cropper.CropImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import in.testpress.core.TestpressCallback;
import in.testpress.core.TestpressException;
import in.testpress.core.TestpressSdk;
import in.testpress.exam.util.ImagePickerUtils;
import in.testpress.models.FileDetails;
import in.testpress.network.TestpressApiClient;
import in.testpress.testpress.Injector;
import in.testpress.testpress.R;
import in.testpress.testpress.TestpressApplication;
import in.testpress.testpress.TestpressServiceProvider;
import in.testpress.testpress.authenticator.LoginActivity;
import in.testpress.testpress.core.CommentsPager;
import in.testpress.testpress.core.Constants;
import in.testpress.testpress.core.TestpressService;
import in.testpress.testpress.models.CategoryDao;
import in.testpress.testpress.models.Comment;
import in.testpress.testpress.models.Post;
import in.testpress.testpress.models.PostDao;
import in.testpress.testpress.util.CommonUtils;
import in.testpress.testpress.util.SafeAsyncTask;
import in.testpress.testpress.util.ShareUtil;
import in.testpress.testpress.util.UIUtils;
import in.testpress.util.ViewUtils;
import in.testpress.util.WebViewUtils;
import static in.testpress.testpress.util.CommonUtils.getException;
public class PostActivity extends TestpressFragmentActivity implements
LoaderManager.LoaderCallbacks<List<Comment>> {
public static final String SHORT_WEB_URL = "shortWebUrl";
public static final String UPDATE_TIME_SPAN = "updateTimeSpan";
public static final int NEW_COMMENT_SYNC_INTERVAL = 10000; // 10 sec
private static final int PREVIOUS_COMMENTS_LOADER_ID = 0;
private static final int NEW_COMMENTS_LOADER_ID = 1;
String shortWebUrl;
PostDao postDao;
Post post;
CommentsPager previousCommentsPager;
CommentsPager newCommentsPager;
CommentsListAdapter commentsAdapter;
ProgressDialog progressDialog;
SimpleDateFormat simpleDateFormat;
boolean postedNewComment;
ImagePickerUtils imagePickerUtils;
@Inject protected TestpressService testpressService;
@Inject protected TestpressServiceProvider serviceProvider;
@InjectView(R.id.content) WebView content;
@InjectView(R.id.title) TextView title;
@InjectView(R.id.summary) TextView summary;
@InjectView(R.id.summary_layout) LinearLayout summaryLayout;
@InjectView(R.id.date) TextView date;
@InjectView(R.id.content_empty_view) TextView contentEmptyView;
@InjectView(R.id.postDetails) RelativeLayout postDetails;
@InjectView(R.id.pb_loading) ProgressBar progressBar;
@InjectView(R.id.empty_container) LinearLayout emptyView;
@InjectView(R.id.empty_title) TextView emptyTitleView;
@InjectView(R.id.empty_description) TextView emptyDescView;
@InjectView(R.id.retry_button) Button retryButton;
@InjectView(R.id.comments_layout) LinearLayout commentsLayout;
@InjectView(R.id.loading_previous_comments_layout) LinearLayout previousCommentsLoadingLayout;
@InjectView(R.id.loading_new_comments_layout) LinearLayout newCommentsLoadingLayout;
@InjectView(R.id.comments_list_view) RecyclerView listView;
@InjectView(R.id.load_previous_comments_layout) LinearLayout loadPreviousCommentsLayout;
@InjectView(R.id.load_previous_comments) TextView loadPreviousCommentsText;
@InjectView(R.id.load_new_comments_layout) LinearLayout loadNewCommentsLayout;
@InjectView(R.id.load_new_comments_text) TextView loadNewCommentsText;
@InjectView(R.id.comments_label) TextView commentsLabel;
@InjectView(R.id.comments_empty_view) TextView commentsEmptyView;
@InjectView(R.id.comment_box) EditText commentsEditText;
@InjectView(R.id.comment_box_layout) LinearLayout commentBoxLayout;
@InjectView(R.id.scroll_view) NestedScrollView scrollView;
@InjectView(android.R.id.content) View activityRootLayout;
@InjectView(R.id.new_comments_available_label) LinearLayout newCommentsAvailableLabel;
private Handler newCommentsHandler;
private Runnable runnable = new Runnable() {
@Override
public void run() {
//noinspection ArraysAsListWithZeroOrOneArgument
commentsAdapter.notifyItemRangeChanged(0, commentsAdapter.getItemCount(),
UPDATE_TIME_SPAN); // Update the time in comments
getNewCommentsPager().reset();
getSupportLoaderManager().restartLoader(NEW_COMMENTS_LOADER_ID, null, PostActivity.this);
}
};
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_details_layout);
Injector.inject(this);
ButterKnife.inject(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
postDetails.setVisibility(View.GONE);
progressBar.getIndeterminateDrawable().setColorFilter(getResources().getColor(R.color.primary), PorterDuff.Mode.SRC_IN);
postDao = ((TestpressApplication) getApplicationContext()).getDaoSession().getPostDao();
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
shortWebUrl = getIntent().getStringExtra(SHORT_WEB_URL);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getResources().getString(R.string.please_wait));
progressDialog.setCancelable(false);
in.testpress.util.UIUtils.setIndeterminateDrawable(this, progressDialog, 4);
ViewUtils.setTypeface(new TextView[] {loadPreviousCommentsText, commentsLabel,
loadNewCommentsText, title}, TestpressSdk.getRubikMediumFont(this));
ViewUtils.setTypeface(new TextView[] {date, summary, commentsEmptyView, commentsEditText},
TestpressSdk.getRubikRegularFont(this));
if(shortWebUrl != null) {
List<Post> posts = postDao.queryBuilder().where(PostDao.Properties.Short_web_url.eq(shortWebUrl)).list();
if (!posts.isEmpty()) {
post = posts.get(0);
if (post.getContentHtml() != null) {
displayPost(post);
return;
}
}
// If there is no post in this url in db or
// If it content_html is null then fetch the post
fetchPost();
} else {
setEmptyText(R.string.invalid_post, R.string.try_after_sometime, R.drawable.ic_error_outline_black_18dp);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.share, menu);
return true;
}
private void fetchPost() {
new SafeAsyncTask<Post>() {
@Override
public Post call() throws Exception {
Map<String, Boolean> queryParams = new LinkedHashMap<>();
queryParams.put("short_link", true);
Uri uri = Uri.parse(shortWebUrl);
return getService().getPostDetail(uri.getLastPathSegment(), queryParams);
}
@Override
protected void onException(final Exception e) throws RuntimeException {
super.onException(e);
progressBar.setVisibility(View.GONE);
if (e.getCause() instanceof IOException) {
setEmptyText(R.string.network_error, R.string.no_internet_try_again, R.drawable.ic_error_outline_black_18dp);
} else if (e.getMessage().equals("404 NOT FOUND")) {
setEmptyText(R.string.access_denied, R.string.post_authentication_failed, R.drawable.ic_error_outline_black_18dp);
} else {
setEmptyText(R.string.network_error, R.string.error_loading_content, R.drawable.ic_error_outline_black_18dp);
}
}
@Override
protected void onSuccess(final Post post) throws Exception {
PostActivity.this.post = post;
post.setPublished(simpleDateFormat.parse(post.getPublishedDate()).getTime());
if (postDao.queryBuilder().where(PostDao.Properties.Id.eq(post.getId())).count() != 0) {
post.setModifiedDate(simpleDateFormat.parse(post.getModified()).getTime());
if (post.category != null) {
post.setCategory(post.category);
CategoryDao categoryDao = ((TestpressApplication) getApplicationContext())
.getDaoSession().getCategoryDao();
categoryDao.insertOrReplace(post.category);
}
postDao.insertOrReplace(post);
}
displayPost(post);
}
}.execute();
}
class ImageHandler {
@JavascriptInterface
public void onClickImage(String url) {
Intent intent = new Intent(PostActivity.this, ZoomableImageActivity.class);
intent.putExtra("url", url);
startActivity(intent);
}
}
private void displayPost(Post post) {
postDetails.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
getSupportActionBar().setTitle(post.getTitle());
title.setText(post.getTitle());
if (post.getSummary().trim().isEmpty()) {
summaryLayout.setVisibility(View.GONE);
} else {
summary.setText(post.getSummary());
summaryLayout.setVisibility(View.VISIBLE);
}
date.setText(DateUtils.getRelativeTimeSpanString(post.getPublished()));
if (post.getContentHtml() != null) {
WebSettings settings = content.getSettings();
settings.setDefaultTextEncodingName("utf-8");
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
settings.setSupportZoom(true);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
content.addJavascriptInterface(new ImageHandler(), "ImageHandler");
content.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
progressBar.setVisibility(View.GONE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String javascript = "javascript:var images = document.getElementsByTagName(\"img\");" +
"for (i = 0; i < images.length; i++) {" +
" images[i].onclick = (" +
" function() {" +
" var src = images[i].src;" +
" return function() {" +
" ImageHandler.onClickImage(src);" +
" }" +
" }" +
" )();" +
"}";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
content.evaluateJavascript(javascript, null);
} else {
content.loadUrl(javascript, null);
}
progressBar.setVisibility(View.GONE);
displayComments();
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean wrongUrl = !url.startsWith("http:
Uri uri = Uri.parse(url);
if (url.endsWith(".pdf") && !uri.getHost().equals("docs.google.com")
&& !uri.getHost().equals("drive.google.com") && ! wrongUrl) {
uri = Uri.parse("https://docs.google.com/gview?embedded=true&url=" + url);
}
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setToolbarColor(ContextCompat.getColor(PostActivity.this, R.color.primary));
CustomTabsIntent customTabsIntent = builder.build();
try {
customTabsIntent.launchUrl(PostActivity.this, uri);
} catch (ActivityNotFoundException e) {
int message = wrongUrl ? R.string.wrong_url : R.string.browser_not_available;
UIUtils.getAlertDialog(PostActivity.this, R.string.not_supported, message)
.show();
}
return true;
}
});
content.loadDataWithBaseURL("file:///android_asset/", getHeader() + post.getContentHtml(), "text/html", "UTF-8", null);
} else {
content.setVisibility(View.GONE);
commentsLayout.setVisibility(View.GONE);
}
}
void displayComments() {
commentsAdapter = new CommentsListAdapter(this);
listView.setNestedScrollingEnabled(false);
listView.setLayoutManager(new LinearLayoutManager(this));
listView.setAdapter(commentsAdapter);
loadPreviousCommentsLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadPreviousCommentsLayout.setVisibility(View.GONE);
getSupportLoaderManager()
.restartLoader(PREVIOUS_COMMENTS_LOADER_ID, null, PostActivity.this);
}
});
loadNewCommentsLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadNewCommentsLayout.setVisibility(View.GONE);
getSupportLoaderManager()
.restartLoader(NEW_COMMENTS_LOADER_ID, null, PostActivity.this);
}
});
newCommentsAvailableLabel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newCommentsAvailableLabel.setVisibility(View.GONE);
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
});
scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY,
int oldScrollX, int oldScrollY) {
int scrollViewHeight = scrollView.getHeight();
int totalScrollViewChildHeight = scrollView.getChildAt(0).getHeight();
// Let's assume end has reached at 50 pixels before itself(on partial visible of last item)
boolean endHasBeenReached =
(scrollY + scrollViewHeight + 50) >= totalScrollViewChildHeight;
if (endHasBeenReached) {
newCommentsAvailableLabel.setVisibility(View.GONE);
}
}
});
imagePickerUtils = new ImagePickerUtils(activityRootLayout, this);
commentsLayout.setVisibility(View.VISIBLE);
getSupportLoaderManager().initLoader(PREVIOUS_COMMENTS_LOADER_ID, null, PostActivity.this);
}
@Override
public Loader<List<Comment>> onCreateLoader(int loaderId, Bundle args) {
switch (loaderId) {
case PREVIOUS_COMMENTS_LOADER_ID:
previousCommentsLoadingLayout.setVisibility(View.VISIBLE);
return new ThrowableLoader<List<Comment>>(this, null) {
@Override
public List<Comment> loadData() throws IOException {
getPreviousCommentsPager().clearResources().next();
return getPreviousCommentsPager().getResources();
}
};
case NEW_COMMENTS_LOADER_ID:
if (postedNewComment) {
newCommentsLoadingLayout.setVisibility(View.VISIBLE);
}
return new ThrowableLoader<List<Comment>>(this, null) {
@Override
public List<Comment> loadData() throws IOException {
do {
getNewCommentsPager().next();
} while (getNewCommentsPager().hasNext());
return getNewCommentsPager().getResources();
}
};
default:
//An invalid id was passed
return null;
}
}
@SuppressLint("SimpleDateFormat")
CommentsPager getPreviousCommentsPager() {
if (previousCommentsPager == null) {
previousCommentsPager = new CommentsPager(getService(), post.getId());
previousCommentsPager.queryParams.put(Constants.Http.ORDER, "-created");
previousCommentsPager.queryParams.put(Constants.Http.UNTIL,
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ").format(new Date()));
}
return previousCommentsPager;
}
CommentsPager getNewCommentsPager() {
if (newCommentsPager == null) {
newCommentsPager = new CommentsPager(getService(), post.getId());
}
List<Comment> comments = commentsAdapter.getComments();
if (newCommentsPager.queryParams.isEmpty() && comments.size() != 0) {
Comment latestComment = comments.get(comments.size() - 1);
//noinspection ConstantConditions
newCommentsPager.queryParams.put(Constants.Http.SINCE, latestComment.getCreated());
}
return newCommentsPager;
}
@Override
public void onLoadFinished(@NonNull Loader<List<Comment>> loader, List<Comment> comments) {
getSupportLoaderManager().destroyLoader(loader.getId());
switch (loader.getId()) {
case PREVIOUS_COMMENTS_LOADER_ID:
onPreviousCommentsLoadFinished(loader, comments);
break;
case NEW_COMMENTS_LOADER_ID:
onNewCommentsLoadFinished(loader, comments);
break;
}
}
void onPreviousCommentsLoadFinished(Loader<List<Comment>> loader, List<Comment> comments) {
//noinspection ThrowableResultOfMethodCallIgnored
final Exception exception = getException(loader);
if (previousCommentsPager == null || (exception == null && comments == null)) {
return;
}
if (exception != null) {
previousCommentsLoadingLayout.setVisibility(View.GONE);
if (post.getCommentsCount() == 0) {
commentBoxLayout.setVisibility(View.VISIBLE);
} else if (exception.getCause() instanceof IOException) {
loadPreviousCommentsText.setText(R.string.load_comments);
loadPreviousCommentsLayout.setVisibility(View.VISIBLE);
Snackbar.make(activityRootLayout, R.string.no_internet_connection,
Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(activityRootLayout, R.string.network_error,
Snackbar.LENGTH_SHORT).show();
}
return;
}
if (!comments.isEmpty()) {
commentsAdapter.addPreviousComments(comments);
} else {
commentsEmptyView.setVisibility(View.VISIBLE);
}
if (post.getCommentsCount() < getPreviousCommentsPager().getCommentsCount()) {
updateCommentsCount(getPreviousCommentsPager().getCommentsCount());
}
if (getPreviousCommentsPager().hasNext()) {
loadPreviousCommentsText.setText(R.string.load_previous_comments);
loadPreviousCommentsLayout.setVisibility(View.VISIBLE);
} else {
loadPreviousCommentsLayout.setVisibility(View.GONE);
}
if (commentBoxLayout.getVisibility() == View.GONE) {
commentBoxLayout.setVisibility(View.VISIBLE);
}
previousCommentsLoadingLayout.setVisibility(View.GONE);
if (newCommentsHandler == null) {
newCommentsHandler = new Handler();
newCommentsHandler.postDelayed(runnable, NEW_COMMENT_SYNC_INTERVAL);
}
}
void onNewCommentsLoadFinished(Loader<List<Comment>> loader, List<Comment> comments) {
//noinspection ThrowableResultOfMethodCallIgnored
final Exception exception = getException(loader);
if (exception != null) {
newCommentsLoadingLayout.setVisibility(View.GONE);
if (postedNewComment) {
if (exception.getCause() instanceof IOException) {
Snackbar.make(activityRootLayout, R.string.no_internet_connection,
Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(activityRootLayout, R.string.network_error,
Snackbar.LENGTH_SHORT).show();
}
loadNewCommentsLayout.setVisibility(View.VISIBLE);
} else {
newCommentsHandler.postDelayed(runnable, NEW_COMMENT_SYNC_INTERVAL);
}
return;
}
if (!comments.isEmpty()) {
commentsAdapter.addComments(comments);
int noOfComments = post.getCommentsCount() + getNewCommentsPager().getCommentsCount();
updateCommentsCount(noOfComments);
}
if (commentsAdapter.getItemCount() != 0 && commentsEmptyView.getVisibility() == View.VISIBLE) {
commentsEmptyView.setVisibility(View.GONE);
}
newCommentsLoadingLayout.setVisibility(View.GONE);
if (postedNewComment) {
// if user posted a comment scroll to the bottom
postedNewComment = false;
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
} else {
int scrollY = scrollView.getScrollY();
int scrollViewHeight = scrollView.getHeight();
int totalScrollViewChildHeight = scrollView.getChildAt(0).getHeight();
boolean endHasBeenReached = (scrollY + scrollViewHeight) >= totalScrollViewChildHeight;
if (!comments.isEmpty() && !endHasBeenReached) {
newCommentsAvailableLabel.setVisibility(View.VISIBLE);
}
}
newCommentsHandler.postDelayed(runnable, NEW_COMMENT_SYNC_INTERVAL);
}
@OnClick(R.id.send) void sendComment() {
final String comment = commentsEditText.getText().toString().trim();
if (comment.isEmpty()) {
return;
}
if (!CommonUtils.isUserAuthenticated(this)) {
showLoginScreen();
return;
}
if (!progressDialog.isShowing()) {
progressDialog.show();
}
UIUtils.hideSoftKeyboard(this);
//noinspection deprecation
postComment(Html.toHtml(new SpannableString(comment))); // Convert to html to support line breaks
}
void showLoginScreen() {
Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra(Constants.DEEP_LINK_TO, Constants.DEEP_LINK_TO_POST);
intent.putExtra(SHORT_WEB_URL, shortWebUrl);
startActivity(intent);
}
void postComment(final String comment) {
new SafeAsyncTask<Comment>() {
public Comment call() throws Exception {
return getService().sendComments(post.getId(), comment);
}
@Override
protected void onException(final Exception exception) throws RuntimeException {
super.onException(exception);
handleExceptionOnSendComment(exception);
}
@Override
public void onSuccess(final Comment comments) {
commentsEditText.setText("");
listView.requestLayout();
progressDialog.dismiss();
Snackbar.make(activityRootLayout, R.string.comment_posted,
Snackbar.LENGTH_SHORT).show();
if (newCommentsHandler != null) {
newCommentsHandler.removeCallbacks(runnable);
}
postedNewComment = true;
getNewCommentsPager().reset();
getSupportLoaderManager()
.restartLoader(NEW_COMMENTS_LOADER_ID, null, PostActivity.this);
}
}.execute();
}
@OnClick(R.id.image_comment_button) void pickImage() {
CropImage.startPickImageActivity(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
imagePickerUtils.onActivityResult(requestCode, resultCode, data,
new ImagePickerUtils.ImagePickerResultHandler() {
@Override
public void onSuccessfullyImageCropped(CropImage.ActivityResult result) {
uploadImage(result.getUri().getPath());
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
imagePickerUtils.permissionsUtils.onRequestPermissionsResult(requestCode, grantResults);
}
void uploadImage(String imagePath) {
if (!progressDialog.isShowing()) {
progressDialog.show();
}
if (!CommonUtils.isUserAuthenticated(this)) {
showLoginScreen();
return;
}
//noinspection ConstantConditions
new TestpressApiClient(this, TestpressSdk.getTestpressSession(this))
.upload(imagePath).enqueue(new TestpressCallback<FileDetails>() {
@Override
public void onSuccess(FileDetails fileDetails) {
postComment(WebViewUtils.appendImageTags(fileDetails.getUrl()));
}
@Override
public void onException(TestpressException exception) {
handleExceptionOnSendComment(exception);
}
});
}
/**
* Call this method only from async task
*
* @return TestpressService
*/
TestpressService getService() {
if (CommonUtils.isUserAuthenticated(this)) {
try {
testpressService = serviceProvider.getService(PostActivity.this);
} catch (IOException | AccountsException e) {
e.printStackTrace();
}
}
return testpressService;
}
@SuppressLint("DefaultLocale")
void updateCommentsCount(int count) {
List<Post> posts = postDao.queryBuilder()
.where(PostDao.Properties.Id.eq(post.getId())).list();
if (!posts.isEmpty()) {
Post post = posts.get(0);
post.setCommentsCount(count);
post.update();
}
post.setCommentsCount(count);
}
@Override
protected void onResume() {
super.onResume();
if (imagePickerUtils != null) {
imagePickerUtils.permissionsUtils.onResume();
}
}
String getHeader() {
return "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\" />" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"typebase.css\" />" +
"<style>img{display: inline;height: auto;max-width: 100%;}</style>";
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if(item.getItemId() == R.id.share) {
if (post != null) {
ShareUtil.shareUrl(this, post.getTitle(), post.getShort_web_url());
} else {
ShareUtil.shareUrl(this, "Check out this article", shortWebUrl);
}
return true;
}
return super.onOptionsItemSelected(item);
}
protected void setEmptyText(final int title, final int description, final int left) {
if (post != null) {
contentEmptyView.setText(description);
contentEmptyView.setVisibility(View.VISIBLE);
displayPost(post);
} else {
emptyView.setVisibility(View.VISIBLE);
emptyTitleView.setText(title);
emptyTitleView.setCompoundDrawablesWithIntrinsicBounds(left, 0, 0, 0);
emptyDescView.setText(description);
retryButton.setVisibility(View.GONE);
}
}
void handleExceptionOnSendComment(Exception exception) {
progressDialog.dismiss();
if (exception.getCause() instanceof IOException) {
Snackbar.make(activityRootLayout, R.string.testpress_no_internet_connection,
Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(activityRootLayout, R.string.testpress_network_error,
Snackbar.LENGTH_SHORT).show();
}
}
@Override
public void onDestroy () {
if (newCommentsHandler != null) {
newCommentsHandler.removeCallbacks(runnable);
}
super.onDestroy ();
}
@Override
public void onLoaderReset(Loader<List<Comment>> loader) {
}
} |
/**
* <b>{@link com.malhartech.lib.algo}</b> is a library of algorithmic modules<p>
* <br>
* <br>The modules are<br>
* <b>{@link com.malhartech.lib.algo.AllAfterMatchBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.AllAfterMatch}<br>
* <b>{@link com.malhartech.lib.algo.AllAfterMatchTest}</b>: Unit test for {@link com.malhartech.lib.stream.AllAfterMatch}<br>
* <b>{@link com.malhartech.lib.algo.AllAfterMatchStringValueBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.AllAfterMatchStringValue}<br>
* <b>{@link com.malhartech.lib.algo.AllAfterMatchStringValueTest}</b>: Unit test for {@link com.malhartech.lib.stream.AllAfterMatchStringValue}<br>
* <b>{@link com.malhartech.lib.algo.BottomNBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.BottomN}<br>
* <b>{@link com.malhartech.lib.algo.BottomNTest}</b>: Unit test for {@link com.malhartech.lib.stream.BottomN}<br>
* <b>{@link com.malhartech.lib.algo.BottomNUniqueBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.BottomNUnique}<br>
* <b>{@link com.malhartech.lib.algo.BottomNUniqueTest}</b>: Unit test for {@link com.malhartech.lib.stream.BottomNUnique}<br>
* <b>{@link com.malhartech.lib.algo.CompareCountBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.CompareCount}<br>
* <b>{@link com.malhartech.lib.algo.CompareCountTest}</b>: Unit test for {@link com.malhartech.lib.stream.CompareCount}<br>
* <b>{@link com.malhartech.lib.algo.CompareCountStringBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.CompareCountString}<br>
* <b>{@link com.malhartech.lib.algo.CompareCountStringTest}</b>: Unit test for {@link com.malhartech.lib.stream.CompareCountString}<br>
* <b>{@link com.malhartech.lib.algo.DistinctBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.Distinct}<br>
* <b>{@link com.malhartech.lib.algo.DistinctTest}</b>: Unit test for {@link com.malhartech.lib.stream.Distinct}<br>
* <b>{@link com.malhartech.lib.algo.FilterKeysBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.FilterKeys}<br>
* <b>{@link com.malhartech.lib.algo.FilterKeysTest}</b>: Unit test for {@link com.malhartech.lib.stream.FilterKeys}<br>
* <b>{@link com.malhartech.lib.algo.FilterValuesBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.FilterValues}<br>
* <b>{@link com.malhartech.lib.algo.FilterValuesTest}</b>: Unit test for {@link com.malhartech.lib.stream.FilterValues}<br>
* <b>{@link com.malhartech.lib.algo.FirstMatchBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.FirstMatch}<br>
* <b>{@link com.malhartech.lib.algo.FirstMatchTest}</b>: Unit test for {@link com.malhartech.lib.stream.FirstMatch}<br>
* <b>{@link com.malhartech.lib.algo.FirstMatchStringBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.FirstMatchString}<br>
* <b>{@link com.malhartech.lib.algo.FirstMatchStringTest}</b>: Unit test for {@link com.malhartech.lib.stream.FirstMatchString}<br>
* <b>{@link com.malhartech.lib.algo.FirstNBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.FirstN}<br>
* <b>{@link com.malhartech.lib.algo.FirstNTest}</b>: Unit test for {@link com.malhartech.lib.stream.FirstN}<br>
* <b>{@link com.malhartech.lib.algo.FirstTillMatchBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.FirstTillMatch}<br>
* <b>{@link com.malhartech.lib.algo.FirstTillMatchTest}</b>: Unit test for {@link com.malhartech.lib.stream.FirstTillMatch}<br>
* <b>{@link com.malhartech.lib.algo.FirstTillMatchStringBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.FirstTillMatchString}<br>
* <b>{@link com.malhartech.lib.algo.FirstTillMatchStringTest}</b>: Unit test for {@link com.malhartech.lib.stream.FirstTillMatchString}<br>
* <b>{@link com.malhartech.lib.algo.InvertIndexArrayBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.InvertIndexArray}<br>
* <b>{@link com.malhartech.lib.algo.InvertIndexArrayTest}</b>: Unit test for {@link com.malhartech.lib.stream.InvertIndexArray}<br>
* <b>{@link com.malhartech.lib.algo.InvertIndexBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.InvertIndex}<br>
* <b>{@link com.malhartech.lib.algo.InvertIndexTest}</b>: Unit test for {@link com.malhartech.lib.stream.InvertIndex}<br>
* <b>{@link com.malhartech.lib.algo.LastMatchBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.LastMatch}<br>
* <b>{@link com.malhartech.lib.algo.LastMatchTest}</b>: Unit test for {@link com.malhartech.lib.stream.LastMatch}<br>
* <b>{@link com.malhartech.lib.algo.LastMatchStringBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.LastMatchString}<br>
* <b>{@link com.malhartech.lib.algo.LastMatchStringTest}</b>: Unit test for {@link com.malhartech.lib.stream.LastMatchString}<br>
* <b>{@link com.malhartech.lib.algo.LeastFrequentKeyBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.LeastFrequentKey}<br>
* <b>{@link com.malhartech.lib.algo.LeastFrequentKeyTest}</b>: Unit test for {@link com.malhartech.lib.stream.LeastFrequentKey}<br>
* <b>{@link com.malhartech.lib.algo.LeastFrequentKeyInMapBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.LeastFrequentKeyInMap}<br>
* <b>{@link com.malhartech.lib.algo.LeastFrequentKeyInMapTest}</b>: Unit test for {@link com.malhartech.lib.stream.LeastFrequentKeyInMap}<br>
* <b>{@link com.malhartech.lib.algo.LeastFrequentKeyValueBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.LeastFrequentKeyValue}<br>
* <b>{@link com.malhartech.lib.algo.LeastFrequentKeyValueTest}</b>: Unit test for {@link com.malhartech.lib.stream.LeastFrequentKeyValue}<br>
* <b>{@link com.malhartech.lib.algo.MatchAllBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.MatchAll}<br>
* <b>{@link com.malhartech.lib.algo.MatchAllTest}</b>: Unit test for {@link com.malhartech.lib.stream.MatchAll}<br>
* <b>{@link com.malhartech.lib.algo.MatchAllStringBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.MatchAllString}<br>
* <b>{@link com.malhartech.lib.algo.MatchAllStringTest}</b>: Unit test for {@link com.malhartech.lib.stream.MatchAllString}<br>
* <b>{@link com.malhartech.lib.algo.MatchAnyBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.MatchAny}<br>
* <b>{@link com.malhartech.lib.algo.MatchAnyTest}</b>: Unit test for {@link com.malhartech.lib.stream.MatchAny}<br>
* <b>{@link com.malhartech.lib.algo.MatchAnyStringBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.MatchAnyString}<br>
* <b>{@link com.malhartech.lib.algo.MatchAnyString}</b>: Unit test for {@link com.malhartech.lib.stream.MatchAnyString}<br>
* <b>{@link com.malhartech.lib.algo.MatchBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.Match}<br>
* <b>{@link com.malhartech.lib.algo.Match}</b>: Unit test for {@link com.malhartech.lib.stream.Match}<br>
* <b>{@link com.malhartech.lib.algo.MatchStringBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.MatchString}<br>
* <b>{@link com.malhartech.lib.algo.MatchStringTest}</b>: Unit test for {@link com.malhartech.lib.stream.MatchString}<br>
* <b>{@link com.malhartech.lib.algo.MostFrequentKeyBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.MostFrequentKey}<br>
* <b>{@link com.malhartech.lib.algo.MostFrequentKeyTest}</b>: Unit test for {@link com.malhartech.lib.stream.MostFrequentKey}<br>
* <b>{@link com.malhartech.lib.algo.MostFrequentKeyInMapBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.MostFrequentKeyInMap}<br>
* <b>{@link com.malhartech.lib.algo.MostFrequentKeyInMapTest}</b>: Unit test for {@link com.malhartech.lib.stream.MostFrequentKeyInMap}<br>
* <b>{@link com.malhartech.lib.algo.MostFrequentKeyValueBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.MostFrequentKeyValue}<br>
* <b>{@link com.malhartech.lib.algo.MostFrequentKeyValueTes}</b>: Unit test for {@link com.malhartech.lib.stream.MostFrequentKeyValue}<br>
* <b>{@link com.malhartech.lib.algo.SamplerBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.Sampler}<br>
* <b>{@link com.malhartech.lib.algo.SamplerTest}</b>: Unit test for {@link com.malhartech.lib.stream.Sampler}<br>
* <b>{@link com.malhartech.lib.algo.TopNBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.TopN}<br>
* <b>{@link com.malhartech.lib.algo.TopNTest}</b>: Unit test for {@link com.malhartech.lib.stream.TopN}<br>
* <b>{@link com.malhartech.lib.algo.TopNUniqueBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.TopNUnique}<br>
* <b>{@link com.malhartech.lib.algo.TopNUniqueTest}</b>: Unit test for {@link com.malhartech.lib.stream.TopNUnique}<br>
* <b>{@link com.malhartech.lib.algo.TupleQueueTest}</b>: Performance test for {@link com.malhartech.lib.stream.TupleQueue}<br>
* <b>{@link com.malhartech.lib.algo.TupleQueue}</b>: Unit test for {@link com.malhartech.lib.stream.TupleQueue}<br>
* <b>{@link com.malhartech.lib.algo.UniqueCounterBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.UniqueCounter}<br>
* <b>{@link com.malhartech.lib.algo.UniqueCounter}</b>: Unit test for {@link com.malhartech.lib.stream.UniqueCounter}<br>
* <b>{@link com.malhartech.lib.algo.UniqueCounterEachBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.UniqueCounterEach}<br>
* <b>{@link com.malhartech.lib.algo.UniqueCounterEach}</b>: Unit test for {@link com.malhartech.lib.stream.UniqueCounterEach}<br>
* <b>{@link com.malhartech.lib.algo.UniqueKeyValCounterBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.UniqueKeyValCounter}<br>
* <b>{@link com.malhartech.lib.algo.UniqueKeyValCounter}</b>: Unit test for {@link com.malhartech.lib.stream.UniqueKeyValCounter}<br>
* <b>{@link com.malhartech.lib.algo.UniqueKeyValCounterEachBenchmark}</b>: Performance test for {@link com.malhartech.lib.stream.UniqueKeyValCounterEach}<br>
* <b>{@link com.malhartech.lib.algo.UniqueKeyValCounterEach}</b>: Unit test for {@link com.malhartech.lib.stream.UniqueKeyValCounterEach}<br> * <br>
* <br>
*/
package com.malhartech.lib.algo; |
package moe.minori.openxiaomiscale.objects;
import moe.minori.openxiaomiscale.BuildConfig;
public class Log
{
public static void d (String name, String content)
{
if (BuildConfig.DEBUG)
{
android.util.Log.d(name, content);
}
else
{
// Quieten
}
}
} |
package org.forestguardian.View;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Headers;
import retrofit2.adapter.rxjava2.Result;
import org.forestguardian.DataAccess.Local.SessionData;
import org.forestguardian.DataAccess.Local.User;
import org.forestguardian.DataAccess.WebServer.ForestGuardianService;
import org.forestguardian.Helpers.UserValidations;
import org.forestguardian.R;
import static junit.framework.Assert.assertEquals;
public class SignUpActivity extends AppCompatActivity {
@BindView(R.id.signup_btn) Button mSignUp;
@BindView(R.id.signup_user) EditText mUsername;
@BindView(R.id.signup_email) EditText mEmail;
@BindView(R.id.signup_pass) EditText mPassword;
@BindView(R.id.signup_pass_confirmation) EditText mPasswordConfirmation;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
ButterKnife.bind(this);
mSignUp.setOnClickListener(pView -> {
// Get data from form.
String email = mEmail.getText().toString();
String username = mUsername.getText().toString();
String pass = mPassword.getText().toString();
String confirmation = mPasswordConfirmation.getText().toString();
/* Check Local validations */
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(username) || TextUtils.isEmpty(pass)) {
String error = "Please fill all fields.";
Log.d(getLocalClassName(),error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return;
}
if (!UserValidations.isEmailValid(email)) {
String error = "Email is invalid.";
Log.d(getLocalClassName(),error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return;
}
if (!UserValidations.isPasswordValid(pass)) {
String error = "Password should have at least 8 characters.";
Log.d(getLocalClassName(),error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return;
}
if (!pass.equals(confirmation)) {
String error = "Password and confirmation should be equal.";
Log.d(getLocalClassName(),error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return;
}
// Create Model
User user = new User();
user.setEmail(email);
user.setUsername(username);
user.setPassword(pass);
user.setPasswordConfirmation(confirmation);
// Send Login Request
Observable<Result<SessionData>> sessionService = ForestGuardianService.global().service().signUp(user);
sessionService.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(pSessionDataResult -> {
/* Check web service response validations. */
if ( pSessionDataResult.isError() ){
/* TODO: Handle authentication error case. */
Log.e( getLocalClassName(), pSessionDataResult.error().getMessage() );
Toast.makeText(this, "Problems with online service..." , Toast.LENGTH_LONG ).show();
return;
}
if ( !pSessionDataResult.response().isSuccessful() ){
/* Check for error messages are ready for user viewing. */
Log.e( getLocalClassName(), "Problem processing request." );
Toast.makeText(this, "Problem processing request.", Toast.LENGTH_LONG ).show();
return;
}
// Save authentication headers for future requests.
Headers authHeaders = pSessionDataResult.response().headers();
String accessToken = authHeaders.get("Access-Token");
User authenticatedUser = pSessionDataResult.response().body().getUser();
authenticatedUser.setToken(accessToken);
ForestGuardianService.global().addAuthenticationHeaders(authenticatedUser.getEmail(), accessToken);
// Uncomment addApiAuthorizationHeader() when ApiAuthorization feature is enabled from backend.
// ForestGuardianService.global().addApiAuthorizationHeader();
Log.e("Authenticated User:", authenticatedUser.getEmail());
Toast.makeText(this, "Welcome!", Toast.LENGTH_SHORT).show();
// Load MapActivity.
Intent intent = new Intent(getApplicationContext(),MapActivity.class);
startActivity(intent);
finish();
});
});
}
} |
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 org.json.JSONObject;
import org.msf.records.App;
import org.msf.records.R;
import org.msf.records.net.Constants;
import org.msf.records.net.OdkDatabase;
import org.msf.records.net.OdkXformSyncTask;
import org.msf.records.net.OpenMrsXformIndexEntry;
import org.msf.records.net.OpenMrsXformsConnection;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.provider.FormsProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.tasks.DiskSyncTask;
import java.io.File;
import java.util.List;
import static org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns.INSTANCE_FILE_PATH;
/**
* 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;
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);
// Create a main screen shown when no patient is selected.
MainScreenFragment mainScreenFragment = new MainScreenFragment();
// Add the fragment to the container.
getSupportFragmentManager().beginTransaction()
.add(R.id.patient_detail_container, mainScreenFragment).commit();
// In two-pane mode, list items should be given the
// 'activated' state when touched.
((PatientListFragment) getSupportFragmentManager()
.findFragmentById(R.id.patient_list))
.setActivateOnItemClick(true);
setupCustomActionBar();
}
// TODO: If exposing deep links into your app, handle intents here.
}
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,
SEND_FORM_TO_SERVER,
}
private void startScanBracelet() {
ScanAction scanAction = ScanAction.PLAY_WITH_ODK;
switch (scanAction) {
case PLAY_WITH_ODK:
showFirstFormFromSdcard();
break;
case FAKE_SCAN:
showFakeScanProgress();
break;
case SEND_FORM_TO_SERVER:
sendFormToServer(Constants.makeNewPatientFormInstance("KH.31", "Fred", "West"));
break;
}
}
public void onButtonClicked(View view) {
switch (view.getId()) {
case R.id.new_patient_button:
fetchXforms(Constants.ADD_PATIENT_UUID);
break;
}
}
private Response.ErrorListener getErrorListenerForTag(final String tag) {
return new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(tag, error.toString());
}
};
}
private void fetchXforms(final String uuidToShow) {
final String tag = "fetchXforms";
Log.i(tag, "Fetching all forms");
App.getmOpenMrsXformsConnection().listXforms(
new Response.Listener<List<OpenMrsXformIndexEntry>>() {
@Override
public void onResponse(final List<OpenMrsXformIndexEntry> response) {
if (response.isEmpty()) {
Log.i(tag, "No forms found");
return;
}
// Cache all the forms into the ODK form cache
new OdkXformSyncTask(new OdkXformSyncTask.FormWrittenListener() {
@Override
public void formWritten(File path, String uuid) {
Log.i(tag, "wrote form " + path);
// Only show the requested form.
if (uuid.equals(uuidToShow)) {
Log.i(tag, "showing form " + uuid);
showOdkCollect(OdkDatabase.getFormIdForPath(path));
}
}
}).execute(response.toArray(new OpenMrsXformIndexEntry[response.size()]));
}
}, getErrorListenerForTag(tag));
}
private void showFirstFormFromSdcard() {
// Sync the local sdcard forms into the database
new DiskSyncTask().execute((Void[]) null);
showOdkCollect(1L);
}
private static final int ODK_COLLECT_REQUEST_CODE = 1;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != ODK_COLLECT_REQUEST_CODE) {
return;
}
Uri uri = data.getData();
if (!getContentResolver().getType(uri).equals(
InstanceProviderAPI.InstanceColumns.CONTENT_TYPE)) {
Log.e(TAG, "Tried to load a content URI of the wrong type: " + uri);
return;
}
Cursor instanceCursor = null;
try {
instanceCursor = getContentResolver().query(uri,
null, null, null, null);
if (instanceCursor.getCount() != 1) {
Log.e(TAG, "The form that we tried to load did not exist: " + uri);
return;
}
instanceCursor.moveToFirst();
String instancePath = instanceCursor.getString(
instanceCursor.getColumnIndex(INSTANCE_FILE_PATH));
if (instancePath == null) {
Log.e(TAG, "No file path for form instance: " + uri);
return;
}
sendFormToServer(readFromPath(instancePath));
} finally {
if (instanceCursor != null) {
instanceCursor.close();
}
}
}
private String readFromPath(String path) {
StringBuilder xml = new StringBuilder();
return xml.toString();
}
private void showOdkCollect(long formId) {
Intent intent = new Intent(this, FormEntryActivity.class);
Uri formUri = ContentUris.withAppendedId(FormsProviderAPI.FormsColumns.CONTENT_URI, formId);
intent.setData(formUri);
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, ODK_COLLECT_REQUEST_CODE);
}
private void showFakeScanProgress() {
final ProgressDialog progressDialog = ProgressDialog
.show(PatientListActivity.this, null, "Scanning for near by bracelets ...", true);
progressDialog.setCancelable(true);
progressDialog.show();
}
private void sendFormToServer(String xml) {
OpenMrsXformsConnection connection = App.getmOpenMrsXformsConnection();
connection.postXformInstance(xml,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Created new patient successfully" + response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Did not submit form to server successfully", error);
}
});
}
private void startActivity(Class<?> activityClass) {
Intent intent = new Intent(PatientListActivity.this, activityClass);
startActivity(intent);
}
} |
package org.commcare.dalvik.activities;
import android.annotation.TargetApi;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.Pair;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
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 org.commcare.android.models.Entity;
import org.commcare.android.models.NodeEntityFactory;
import org.commcare.android.util.AndroidInstanceInitializer;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.session.CommCareSession;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.SessionDatum;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.data.GeoPointData;
import org.javarosa.core.model.data.UncastData;
import org.javarosa.core.model.instance.TreeReference;
import java.util.HashMap;
import java.util.Vector;
/**
* @author ctsims
*/
@TargetApi(11)
public class EntityMapActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleMap.OnMarkerClickListener {
private static final String TAG = EntityMapActivity.class.getSimpleName();
private EvaluationContext entityEvaluationContext;
private CommCareSession session;
Vector<Entity<TreeReference>> entities;
Vector<Pair<Entity<TreeReference>, LatLng>> entityLocations;
HashMap<Marker, TreeReference> markerReferences = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entity_map_view);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
session = CommCareApplication._().getCurrentSession();
SessionDatum selectDatum = session.getNeededDatum();
Detail detail = session.getDetail(selectDatum.getShortDetail());
NodeEntityFactory factory = new NodeEntityFactory(detail, this.getEvaluationContext());
Vector<TreeReference> references = getEvaluationContext().expandReference(
selectDatum.getNodeset());
entities = new Vector<>();
for(TreeReference ref : references) {
entities.add(factory.getEntity(ref));
}
int bogusAddresses = 0;
entityLocations = new Vector<>();
for(Entity<TreeReference> entity : entities) {
for(int i = 0 ; i < detail.getHeaderForms().length; ++i ){
if("address".equals(detail.getTemplateForms()[i])) {
String address = entity.getFieldString(i).trim();
if(address != null && !"".equals(address)) {
LatLng location = getLatLngFromAddress(address);
if (location == null) {
bogusAddresses++;
} else {
entityLocations.add(new Pair<>(entity, location));
}
}
}
}
}
Log.d(TAG, "Loaded. " + entityLocations.size() +" addresses discovered, " + bogusAddresses + " could not be located");
}
private LatLng getLatLngFromAddress(String address) {
LatLng location = null;
try {
GeoPointData data = new GeoPointData().cast(new UncastData(address));
if(data != null) {
location = new LatLng(data.getLatitude(), data.getLongitude());
}
} catch(Exception ex) {
//We might not have a geopoint at all. Don't even trip
}
return location;
// boolean cached = false;
// try {
// GeocodeCacheModel record = geoCache.getRecordForValue(GeocodeCacheModel.META_LOCATION, address);
// cached = true;
// if(record.dataExists()){
// gp = record.getGeoPoint();
// } catch(NoSuchElementException nsee) {
// //no record!
// //If we don't have a geopoint, let's try to find our address
// if (!cached && location != null) {
// try {
// List<Address> addresses = mGeoCoder.getFromLocationName(address, 3, boundHints[0], boundHints[1], boundHints[2], boundHints[3]);
// for(Address a : addresses) {
// if(a.hasLatitude() && a.hasLongitude()) {
// int lat = (int) (a.getLatitude() * 1E6);
// int lng = (int) (a.getLongitude() * 1E6);
// gp = new GeoPoint(lat, lng);
// geoCache.write(new GeocodeCacheModel(address, lat, lng));
// legit++;
// break;
// //We didn't find an address, make a miss record
// if(gp == null) {
// geoCache.write(GeocodeCacheModel.NoHitRecord(address));
// } catch (StorageFullException | IOException e1) {
// e1.printStackTrace();
}
@Override
public void onMapReady(GoogleMap map) {
for (Pair<Entity<TreeReference>, LatLng> entityLocation: entityLocations) {
Marker marker = map.addMarker(new MarkerOptions()
.position(entityLocation.second)
.title(entityLocation.first.getFieldString(0)));
markerReferences.put(marker, entityLocation.first.getElement());
}
map.setOnMarkerClickListener(this);
}
@Override
public boolean onMarkerClick(Marker marker) {
return true;
}
private EvaluationContext getEvaluationContext() {
if(entityEvaluationContext == null) {
entityEvaluationContext = session.getEvaluationContext(getInstanceInit());
}
return entityEvaluationContext;
}
private AndroidInstanceInitializer getInstanceInit() {
return new AndroidInstanceInitializer(session);
}
} |
//FILE: XYPositionListDlg.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// Nico Stuurman, nico@cmp.ucsf.edu June 23, 2009
//This file is distributed in the hope that it will be useful,
//of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//CVS: $Id$
package org.micromanager.positionlist;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.prefs.Preferences;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableCellRenderer;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.StrVector;
import net.miginfocom.swing.MigLayout;
import org.micromanager.MMOptions;
import org.micromanager.MMStudio;
import org.micromanager.api.MultiStagePosition;
import org.micromanager.api.PositionList;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.StagePosition;
import org.micromanager.api.events.StagePositionChangedEvent;
import org.micromanager.api.events.XYStagePositionChangedEvent;
import org.micromanager.dialogs.AcqControlDlg;
import org.micromanager.events.EventManager;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.MMDialog;
import org.micromanager.utils.MMException;
import org.micromanager.utils.ReportingUtils;
public class PositionListDlg extends MMDialog implements MouseListener, ChangeListener {
private static final long serialVersionUID = 1L;
private String posListDir_;
private File curFile_;
private static final String POS = "pos";
private static final String POS_COL0_WIDTH = "posCol0WIDTH";
private static final String AXIS_COL0_WIDTH = "axisCol0WIDTH";
// @SuppressWarnings("unused")
private static final FileType POSITION_LIST_FILE =
new FileType("POSITION_LIST_FILE","Position list file",
System.getProperty("user.home") + "/PositionList.pos",
true, POS);
private Font arialSmallFont_;
private JTable posTable_;
private final JTable axisTable_;
private final AxisTableModel axisModel_;
private CMMCore core_;
private ScriptInterface studio_;
private AcqControlDlg acqControlDlg_;
private MMOptions opts_;
private Preferences prefs_;
private GUIColors guiColors_;
private AxisList axisList_;
private final JButton tileButton_;
private MultiStagePosition curMsp_;
public JButton markButton_;
private final PositionTableModel positionModel_;
private EventBus bus_;
@Subscribe
public void onTileUpdate(MoversChangedEvent event) {
setTileButtonEnabled();
}
private void setTileButtonEnabled() {
int n2DStages = 0;
for (int i = 0; i < axisList_.getNumberOfPositions(); i++) {
AxisData ad = axisList_.get(i);
if (ad.getUse()) {
if (ad.getType() == AxisData.AxisType.twoD) {
n2DStages++;
}
}
}
if (n2DStages == 1) {
tileButton_.setEnabled(true);
} else {
tileButton_.setEnabled(false);
}
}
/**
* Create the dialog
* @param core - MMCore
* @param gui - ScriptInterface
* @param posList - Position list to be displayed in this dialog
* @param acd - MDA window
* @param opts - MicroManager Options
*/
@SuppressWarnings("LeakingThisInConstructor")
public PositionListDlg(CMMCore core, ScriptInterface gui,
PositionList posList, AcqControlDlg acd, MMOptions opts) {
super();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
savePosition();
int posCol0Width = posTable_.getColumnModel().getColumn(0).getWidth();
prefs_.putInt(POS_COL0_WIDTH, posCol0Width);
int axisCol0Width = axisTable_.getColumnModel().getColumn(0).getWidth();
prefs_.putInt(AXIS_COL0_WIDTH, axisCol0Width);
}
});
core_ = core;
studio_ = gui;
bus_ = new EventBus();
bus_.register(this);
opts_ = opts;
acqControlDlg_ = acd;
guiColors_ = new GUIColors();
prefs_ = getPrefsNode();
setTitle("Stage Position List");
setLayout(new MigLayout("flowy, filly, insets 8", "[grow][]",
"[top]"));
setMinimumSize(new Dimension(275, 355));
loadPosition(100, 100, 362, 595);
arialSmallFont_ = new Font("Arial", Font.PLAIN, 10);
// getFontMetrics is deprecated, however, to use the preferred
// Font.getLineMetrics, we need an instance of the Graphics2D object,
// which is null until this window is visble...
@SuppressWarnings("deprecation")
FontMetrics smallArialMetrics = Toolkit.getDefaultToolkit().getFontMetrics(
arialSmallFont_);
final JScrollPane scrollPane = new JScrollPane();
add(scrollPane, "split, spany, growy, growx, bottom 1:push");
final JScrollPane axisPane = new JScrollPane();
// axisPanel should always be visible
axisPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
add(axisPane, "growx, wrap");
final TableCellRenderer firstRowRenderer = new FirstRowRenderer(arialSmallFont_);
posTable_ = new JTable() {
private static final long serialVersionUID = -3873504142761785021L;
@Override
public TableCellRenderer getCellRenderer(int row, int column) {
if (row == 0) {
return firstRowRenderer;
}
return super.getCellRenderer(row, column);
}
};
posTable_.setFont(arialSmallFont_);
positionModel_ = new PositionTableModel();
positionModel_.setData(posList);
posTable_.setModel(positionModel_);
scrollPane.setViewportView(posTable_);
CellEditor cellEditor_ = new CellEditor(arialSmallFont_);
cellEditor_.addListener();
posTable_.setDefaultEditor(Object.class, cellEditor_);
posTable_.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// set column divider location
int posCol0Width = prefs_.getInt(POS_COL0_WIDTH, 75);
posTable_.getColumnModel().getColumn(0).setWidth(posCol0Width);
posTable_.getColumnModel().getColumn(0).setPreferredWidth(posCol0Width);
posTable_.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
axisTable_ = new JTable();
axisTable_.setFont(arialSmallFont_);
axisList_ = new AxisList(core_, prefs_);
axisModel_ = new AxisTableModel(axisList_, axisTable_, bus_, prefs_);
axisTable_.setModel(axisModel_);
axisPane.setViewportView(axisTable_);
// make sure that the complete axis Table will always be visible
axisPane.setMaximumSize(new Dimension(5000, 30 + axisList_.getNumberOfPositions() *
smallArialMetrics.getHeight() ) );
axisPane.setMinimumSize(new Dimension(50, 30 + axisList_.getNumberOfPositions() *
smallArialMetrics.getHeight() ) );
// set divider location
int axisCol0Width = prefs_.getInt(AXIS_COL0_WIDTH, 75);
axisTable_.getColumnModel().getColumn(0).setWidth(axisCol0Width);
axisTable_.getColumnModel().getColumn(0).setPreferredWidth(axisCol0Width);
axisTable_.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
// Create buttons on the right side of the window
Dimension buttonSize = new Dimension(88, 21);
// mark / replace button:
markButton_ = posListButton(buttonSize, arialSmallFont_);
markButton_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
markPosition();
posTable_.clearSelection();
updateMarkButtonText();
}
});
markButton_.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/flag_green.png")));
markButton_.setText("Mark");
markButton_.setToolTipText("Adds point with coordinates of current stage position");
// Separate the layout of the buttons from the layout of the panels to
// their left.
add(markButton_, "split, spany, align left");
posTable_.addFocusListener(
new java.awt.event.FocusAdapter() {
@Override
public void focusLost(java.awt.event.FocusEvent evt) {
updateMarkButtonText();
}
@Override
public void focusGained(java.awt.event.FocusEvent evt) {
updateMarkButtonText();
}
});
// the re-ordering buttons:
Dimension arrowSize = new Dimension(40, buttonSize.height);
// There should be a way to do this without a secondary panel, but I
// couldn't figure one out, so whatever.
JPanel arrowPanel = new JPanel(new MigLayout("insets 0, fillx"));
// move selected row up one row
final JButton upButton = posListButton(arrowSize, arialSmallFont_);
upButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
incrementOrderOfSelectedPosition(-1);
}
});
upButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/arrow_up.png")));
upButton.setText("");
upButton.setToolTipText("Move currently selected position up list (positions higher on list are acquired earlier)");
arrowPanel.add(upButton, "dock west");
// move selected row down one row
final JButton downButton = posListButton(arrowSize, arialSmallFont_);
downButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
incrementOrderOfSelectedPosition(1);
}
});
downButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/arrow_down.png")));
downButton.setText(""); // "Down"
downButton.setToolTipText("Move currently selected position down list (lower positions on list are acquired later)");
arrowPanel.add(downButton, "dock east");
add(arrowPanel, "growx");
// from this point on, the top right button's positions are computed
final JButton mergeButton = posListButton(buttonSize, arialSmallFont_);
// We need to use addMouseListener instead of addActionListener because
// we'll need the mouse's position for generating a popup menu.
mergeButton.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent event) {
mergePositions(event);
}
});
mergeButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/asterisk_orange.png")));
mergeButton.setText("Merge");
mergeButton.setToolTipText("Select an axis, and set the selected positions' value along that axis to the current stage position.");
add(mergeButton);
// the Go To button:
final JButton gotoButton = posListButton(buttonSize, arialSmallFont_);
gotoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
goToCurrentPosition();
}
});
gotoButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/resultset_next.png")));
gotoButton.setText("Go to");
gotoButton.setToolTipText("Moves stage to currently selected position");
add(gotoButton);
final JButton refreshButton = posListButton(buttonSize, arialSmallFont_);
refreshButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
refreshCurrentPosition();
}
});
refreshButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/arrow_refresh.png")));
refreshButton.setText("Refresh");
add(refreshButton);
final JButton removeButton = posListButton(buttonSize, arialSmallFont_);
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
removeSelectedPositions();
}
});
removeButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/cross.png")));
removeButton.setText("Remove");
removeButton.setToolTipText("Removes currently selected position from list");
add(removeButton);
final JButton setOriginButton = posListButton(buttonSize, arialSmallFont_);
setOriginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
calibrate(); //setOrigin();
}
});
setOriginButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/empty.png")));
setOriginButton.setText("Set Origin");
setOriginButton.setToolTipText("Drives X and Y stages back to their original positions and zeros their position values");
add(setOriginButton);
final JButton offsetButton = posListButton(buttonSize, arialSmallFont_);
offsetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
offsetPositions();
}
});
offsetButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/empty.png")));
offsetButton.setText("Add Offset");
offsetButton.setToolTipText("Add an offset to the selected positions.");
add(offsetButton);
final JButton removeAllButton = posListButton(buttonSize, arialSmallFont_);
removeAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int ret = JOptionPane.showConfirmDialog(null, "Are you sure you want to erase\nall positions from the position list?", "Clear all positions?", JOptionPane.YES_NO_OPTION);
if (ret == JOptionPane.YES_OPTION) {
clearAllPositions();
}
}
});
removeAllButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/delete.png")));
removeAllButton.setText("Clear All");
removeAllButton.setToolTipText("Removes all positions from list");
add(removeAllButton);
final JButton loadButton = posListButton(buttonSize, arialSmallFont_);
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
loadPositionList();
}
});
loadButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/empty.png")));
loadButton.setText("Load...");
loadButton.setToolTipText("Load position list");
add(loadButton, "gaptop 4:push");
final JButton saveAsButton = posListButton(buttonSize, arialSmallFont_);
saveAsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
savePositionListAs();
}
});
saveAsButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/empty.png")));
saveAsButton.setText("Save As...");
saveAsButton.setToolTipText("Save position list as");
add(saveAsButton);
tileButton_ = posListButton(buttonSize, arialSmallFont_);
tileButton_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
showCreateTileDlg();
}
});
tileButton_.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/empty.png")));
tileButton_.setText("Create Grid");
tileButton_.setToolTipText("Open new window to create grid of equally spaced positions");
add(tileButton_);
setTileButtonEnabled();
final JButton closeButton = posListButton(buttonSize, arialSmallFont_);
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
closeButton.setIcon(new ImageIcon(MMStudio.class.getResource(
"/org/micromanager/icons/empty.png")));
closeButton.setText("Close");
add(closeButton, "wrap");
// Register to be informed when the current stage position changes.
EventManager.register(this);
refreshCurrentPosition();
}
private JButton posListButton(Dimension buttonSize, Font font) {
JButton button = new JButton();
button.setPreferredSize(buttonSize);
button.setMinimumSize(buttonSize);
button.setFont(font);
button.setMargin(new Insets(0, 0, 0, 0));
return button;
}
public void addListeners() {
axisTable_.addMouseListener(this);
posTable_.addMouseListener(this);
getPositionList().addChangeListener(this);
}
@Override
public void stateChanged(ChangeEvent e) {
try {
GUIUtils.invokeLater(new Runnable() {
@Override
public void run() {
posTable_.revalidate();
axisTable_.revalidate();
}
});
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
} catch (InvocationTargetException ex) {
ReportingUtils.logError(ex);
}
}
protected void updateMarkButtonText() {
PositionTableModel tm = (PositionTableModel) posTable_.getModel();
MultiStagePosition msp = tm.getPositionList().
getPosition(posTable_.getSelectedRow() - 1);
if (markButton_ != null) {
if (msp == null) {
markButton_.setText("Mark");
} else {
markButton_.setText("Replace");
}
}
}
public void addPosition(MultiStagePosition msp, String label) {
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
msp.setLabel(label);
ptm.getPositionList().addPosition(msp);
ptm.fireTableDataChanged();
}
public void addPosition(MultiStagePosition msp) {
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
msp.setLabel(ptm.getPositionList().generateLabel());
ptm.getPositionList().addPosition(msp);
ptm.fireTableDataChanged();
}
protected boolean savePositionListAs() {
File f = FileDialogs.save(this, "Save the position list", POSITION_LIST_FILE);
if (f != null) {
curFile_ = f;
String fileName = curFile_.getAbsolutePath();
int i = fileName.lastIndexOf('.');
int j = fileName.lastIndexOf(File.separatorChar);
if (i <= 0 || i < j) {
i = fileName.length();
}
fileName = fileName.substring(0, i);
fileName += "." + POS;
try {
getPositionList().save(fileName);
posListDir_ = curFile_.getParent();
} catch (MMException e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
return false;
}
protected void loadPositionList() {
File f = FileDialogs.openFile(this, "Load a position list", POSITION_LIST_FILE);
if (f != null) {
curFile_ = f;
try {
getPositionList().load(curFile_.getAbsolutePath());
posListDir_ = curFile_.getParent();
} catch (MMException e) {
ReportingUtils.showError(e);
} finally {
updatePositionData();
}
}
}
public void updatePositionData() {
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
ptm.fireTableDataChanged();
}
public void rebuildAxisList() {
axisList_ = new AxisList(core_, prefs_);
AxisTableModel axm = (AxisTableModel)axisTable_.getModel();
axm.fireTableDataChanged();
}
public void activateAxisTable(boolean state) {
axisModel_.setEditable(state);
axisTable_.setEnabled(state);
}
public void setPositionList(PositionList pl) {
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
ptm.setData(pl);
ptm.fireTableDataChanged();
}
protected void goToCurrentPosition() {
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
MultiStagePosition msp = ptm.getPositionList().getPosition(posTable_.getSelectedRow() - 1);
if (msp == null)
return;
try {
MultiStagePosition.goToPosition(msp, core_);
} catch (Exception e) {
ReportingUtils.showError(e);
}
refreshCurrentPosition();
}
protected void clearAllPositions() {
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
ptm.getPositionList().clearAllPositions();
ptm.fireTableDataChanged();
acqControlDlg_.updateGUIContents();
}
protected void incrementOrderOfSelectedPosition(int direction) {
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
int currentRow = posTable_.getSelectedRow() - 1;
int newEdittingRow = -1;
if (0 <= currentRow) {
int destinationRow = currentRow + direction;
{
if (0 <= destinationRow) {
if (destinationRow < posTable_.getRowCount()) {
PositionList pl = ptm.getPositionList();
MultiStagePosition[] mspos = pl.getPositions();
MultiStagePosition tmp = mspos[currentRow];
pl.replacePosition(currentRow, mspos[destinationRow]);
pl.replacePosition(destinationRow, tmp);
ptm.setData(pl);
if (destinationRow + 1 < ptm.getRowCount()) {
newEdittingRow = destinationRow + 1;
}
} else {
newEdittingRow = posTable_.getRowCount() - 1;
}
} else {
newEdittingRow = 1;
}
}
}
ptm.fireTableDataChanged();
if (-1 < newEdittingRow) {
posTable_.changeSelection(newEdittingRow, newEdittingRow, false, false);
posTable_.requestFocusInWindow();
}
updateMarkButtonText();
}
protected void removeSelectedPositions() {
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
int[] selectedRows = posTable_.getSelectedRows();
// Reverse the rows so that we delete from the end; if we delete from
// the front then the position list gets re-ordered as we go and we
// delete the wrong positions!
for (int i = selectedRows.length - 1; i >= 0; --i) {
ptm.getPositionList().removePosition(selectedRows[i] - 1);
}
ptm.fireTableDataChanged();
acqControlDlg_.updateGUIContents();
}
/**
* Store current xyPosition.
* Use data collected in refreshCurrentPosition()
*/
public void markPosition() {
refreshCurrentPosition();
MultiStagePosition msp = curMsp_;
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
MultiStagePosition selMsp =
ptm.getPositionList().getPosition(posTable_.getSelectedRow() -1);
if (selMsp == null) {
msp.setLabel(ptm.getPositionList().generateLabel());
ptm.getPositionList().addPosition(msp);
ptm.fireTableDataChanged();
acqControlDlg_.updateGUIContents();
} else { // replace instead of add
msp.setLabel(ptm.getPositionList().getPosition(
posTable_.getSelectedRow() - 1).getLabel() );
int selectedRow = posTable_.getSelectedRow();
ptm.getPositionList().replacePosition(
posTable_.getSelectedRow() -1, msp);
ptm.fireTableCellUpdated(selectedRow, 1);
// Not sure why this is here as we undo the selecion after
// this functions exits...
posTable_.setRowSelectionInterval(selectedRow, selectedRow);
}
}
/**
* Displays a popup menu to let the user select an axis, which will then
* invoke mergePositionsAlongAxis, below.
* @param event - Mouse Event that gives X and Y coordinates
*/
public void mergePositions(MouseEvent event) {
MergeStageDevicePopupMenu menu = new MergeStageDevicePopupMenu(this, core_);
menu.show(event.getComponent(), event.getX(), event.getY());
}
/**
* Given a device name, change all currently-selected positions so that
* their positions for that device match the current stage position for
* that device.
* @param deviceName name of device name
*/
public void mergePositionsWithDevice(String deviceName) {
int[] selectedRows = posTable_.getSelectedRows();
double x = 0, y = 0, z = 0;
// Find the current position for that device in curMsp_
for (int posIndex = 0; posIndex < curMsp_.size(); ++posIndex) {
StagePosition subPos = curMsp_.get(posIndex);
if (!subPos.stageName.equals(deviceName)) {
continue;
}
x = subPos.x;
y = subPos.y;
z = subPos.z;
}
for (int row : selectedRows) {
// Find the appropriate StagePosition in this MultiStagePosition and
// update its values.
MultiStagePosition listPos = positionModel_.getPositionList().getPosition(row - 1);
for (int posIndex = 0; posIndex < listPos.size(); ++posIndex) {
StagePosition subPos = listPos.get(posIndex);
if (!subPos.stageName.equals(deviceName)) {
continue;
}
subPos.x = x;
subPos.y = y;
subPos.z = z;
}
}
positionModel_.fireTableDataChanged();
acqControlDlg_.updateGUIContents();
}
// The stage position changed; update curMsp_.
@Subscribe
public void onStagePositionChanged(StagePositionChangedEvent event) {
// Do the update on the EDT (1) to prevent data races and (2) to prevent
// deadlock by calling back into the stage device adapter.
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
refreshCurrentPosition();
}
});
}
// The stage position changed; update curMsp_.
@Subscribe
public void onXYStagePositionChanged(XYStagePositionChangedEvent event) {
// Do the update on the EDT (1) to prevent data races and (2) to prevent
// deadlock by calling back into the stage device adapter.
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
refreshCurrentPosition();
}
});
}
/**
* Update display of the current stage position.
*/
private void refreshCurrentPosition() {
StringBuilder sb = new StringBuilder();
MultiStagePosition msp = new MultiStagePosition();
msp.setDefaultXYStage(core_.getXYStageDevice());
msp.setDefaultZStage(core_.getFocusDevice());
// read 1-axis stages
try {
StrVector stages = core_.getLoadedDevicesOfType(DeviceType.StageDevice);
for (int i=0; i<stages.size(); i++) {
if (axisList_.use(stages.get(i))) {
StagePosition sp = new StagePosition();
sp.stageName = stages.get(i);
sp.numAxes = 1;
sp.x = core_.getPosition(stages.get(i));
msp.add(sp);
sb.append(sp.getVerbose()).append("\n");
}
}
// read 2-axis stages
StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice);
for (int i=0; i<stages2D.size(); i++) {
if (axisList_.use(stages2D.get(i))) {
StagePosition sp = new StagePosition();
sp.stageName = stages2D.get(i);
sp.numAxes = 2;
sp.x = core_.getXPosition(stages2D.get(i));
sp.y = core_.getYPosition(stages2D.get(i));
msp.add(sp);
sb.append(sp.getVerbose()).append("\n");
}
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
curMsp_ = msp;
positionModel_.setCurrentMSP(curMsp_);
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
int selectedRow = posTable_.getSelectedRow();
ptm.fireTableCellUpdated(0, 1);
if (selectedRow > 0)
posTable_.setRowSelectionInterval(selectedRow, selectedRow);
posTable_.revalidate();
axisTable_.revalidate();
}
public boolean useDrive(String drive) {
return axisList_.use(drive);
}
/**
* Returns the first selected drive of the specified type
* @param type
* @return
*/
private String getAxis(AxisData.AxisType type) {
for (int i = 0; i < axisList_.getNumberOfPositions(); i++) {
AxisData axis = axisList_.get(i);
if (axis.getUse() && axis.getType() == type) {
return axis.getAxisName();
}
}
return null;
}
/**
* Returns the first selected XYDrive or null when none is selected
* @return
*/
public String get2DAxis() {
return getAxis(AxisData.AxisType.twoD);
}
/**
* Returns the first selected Drive or null when none is selected
* @return
*/
public String get1DAxis() {
return getAxis(AxisData.AxisType.oneD);
}
protected void showCreateTileDlg() {
TileCreatorDlg tileCreatorDlg = new TileCreatorDlg(core_, opts_, this);
studio_.addMMBackgroundListener(tileCreatorDlg);
studio_.addMMListener(tileCreatorDlg);
tileCreatorDlg.setBackground(guiColors_.background.get(opts_.displayBackground_));
tileCreatorDlg.setVisible(true);
}
private PositionList getPositionList() {
PositionTableModel ptm = (PositionTableModel) posTable_.getModel();
return ptm.getPositionList();
}
/**
* Calibrate the XY stage.
*/
private void calibrate() {
JOptionPane.showMessageDialog(this, "ALERT! Please REMOVE objectives! It may damage lens!",
"Calibrate the XY stage", JOptionPane.WARNING_MESSAGE);
Object[] options = { "Yes", "No"};
if (JOptionPane.YES_OPTION != JOptionPane.showOptionDialog(this, "Really calibrate your XY stage?", "Are you sure?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]))
return ;
// calibrate xy-axis stages
try {
// read 2-axis stages
StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice);
for (int i=0; i<stages2D.size(); i++) {
String deviceName = stages2D.get(i);
double [] x1 = new double[1];
double [] y1 = new double[1];
core_.getXYPosition(deviceName,x1,y1);
StopCalThread stopThread = new StopCalThread();
CalThread calThread = new CalThread();
stopThread.setPara(calThread, this, deviceName, x1, y1);
calThread.setPara(stopThread, this, deviceName, x1, y1);
stopThread.start();
Thread.sleep(100);
calThread.start();
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
class StopCalThread extends Thread {
double [] x1;
double [] y1;
String deviceName;
MMDialog d;
Thread otherThread;
public void setPara(Thread calThread, MMDialog d, String deviceName, double [] x1, double [] y1) {
this.otherThread = calThread;
this.d = d;
this.deviceName = deviceName;
this.x1 = x1;
this.y1 = y1;
}
@Override
public void run() {
try {
// popup a dialog that says stop the calibration
Object[] options = { "Stop" };
int option = JOptionPane.showOptionDialog(d, "Stop calibration?", "Calibration",
JOptionPane.CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (option==0) {//stop the calibration
otherThread.interrupt();
otherThread = null;
if (isInterrupted())return;
Thread.sleep(50);
core_.stop(deviceName);
if (isInterrupted())return;
boolean busy = core_.deviceBusy(deviceName);
while (busy){
if (isInterrupted())return;
core_.stop(deviceName);
if (isInterrupted())return;
busy = core_.deviceBusy(deviceName);
}
Object[] options2 = { "Yes", "No" };
option = JOptionPane.showOptionDialog(d, "RESUME calibration?", "Calibration",
JOptionPane.OK_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options2, options2[0]);
if (option==1) return; // not to resume, just stop
core_.home(deviceName);
StopCalThread sct = new StopCalThread();
sct.setPara(this, d, deviceName, x1, y1);
busy = core_.deviceBusy(deviceName);
if ( busy ) sct.start();
if (isInterrupted())return;
busy = core_.deviceBusy(deviceName);
while (busy){
if (isInterrupted())return;
Thread.sleep(100);
if (isInterrupted())return;
busy = core_.deviceBusy(deviceName);
}
sct.interrupt();
//calibrate_(deviceName, x1, y1);
double [] x2 = new double[1];
double [] y2 = new double[1];
// check if the device busy?
busy = core_.deviceBusy(deviceName);
int delay=500; //500 ms
int period=600000;//600 sec
int elapse = 0;
while (busy && elapse<period){
Thread.sleep(delay);
busy = core_.deviceBusy(deviceName);
elapse+=delay;
}
// now the device is not busy
core_.getXYPosition(deviceName,x2,y2);
// zero the coordinates
core_.setOriginXY(deviceName);
BackThread bt = new BackThread();
bt.setPara(d);
bt.start();
core_.setXYPosition(deviceName, x1[0]-x2[0], y1[0]-y2[0]);
if (isInterrupted())
return;
busy = core_.deviceBusy(deviceName);
while (busy){
if (isInterrupted())return;
Thread.sleep(100);
if (isInterrupted())return;
busy = core_.deviceBusy(deviceName);
}
bt.interrupt();
}
} catch (InterruptedException e) { ReportingUtils.logError(e);}
catch (Exception e) {
ReportingUtils.showError(e);
}
}
} // End StopCalThread class
class CalThread extends Thread {
double [] x1;
double [] y1;
String deviceName;
MMDialog d;
Thread stopThread;
public void setPara(Thread stopThread, MMDialog d, String deviceName, double [] x1, double [] y1) {
this.stopThread = stopThread;
this.d = d;
this.deviceName = deviceName;
this.x1 = x1;
this.y1 = y1;
}
@Override
public void run() {
try {
core_.home(deviceName);
// check if the device busy?
boolean busy = core_.deviceBusy(deviceName);
int delay = 500; //500 ms
int period = 600000;//600 sec
int elapse = 0;
while (busy && elapse < period) {
Thread.sleep(delay);
busy = core_.deviceBusy(deviceName);
elapse += delay;
}
stopThread.interrupt();
stopThread = null;
double[] x2 = new double[1];
double[] y2 = new double[1];
core_.getXYPosition(deviceName, x2, y2);
// zero the coordinates
core_.setOriginXY(deviceName);
BackThread bt = new BackThread();
bt.setPara(d);
bt.start();
core_.setXYPosition(deviceName, x1[0] - x2[0], y1[0] - y2[0]);
if (isInterrupted()) {
return;
}
busy = core_.deviceBusy(deviceName);
while (busy) {
if (isInterrupted()) {
return;
}
Thread.sleep(100);
if (isInterrupted()) {
return;
}
busy = core_.deviceBusy(deviceName);
}
bt.interrupt();
} catch (InterruptedException e) {
ReportingUtils.logError(e);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
} // End CalThread class
class BackThread extends Thread {
MMDialog d;
public void setPara(MMDialog d) {
this.d = d;
}
@Override
public void run() {
JOptionPane.showMessageDialog(d, "Going back to the original position!");
}
} // End BackThread class
/*
* Implementation of MouseListener
* Sole purpose is to be able to unselect rows in the positionlist table
*/
@Override
public void mousePressed (MouseEvent e) {}
@Override
public void mouseReleased (MouseEvent e) {}
@Override
public void mouseEntered (MouseEvent e) {}
@Override
public void mouseExited (MouseEvent e) {}
/*
* This event is fired after the table sets its selection
* Remember where was clicked previously so as to allow for toggling the selected row
*/
private static int lastRowClicked_;
@Override
public void mouseClicked (MouseEvent e) {
java.awt.Point p = e.getPoint();
int rowIndex = posTable_.rowAtPoint(p);
if (rowIndex >= 0) {
if (rowIndex == posTable_.getSelectedRow() && rowIndex == lastRowClicked_) {
posTable_.clearSelection();
lastRowClicked_ = -1;
} else
lastRowClicked_ = rowIndex;
}
updateMarkButtonText();
}
/**
* Generate a dialog that will call our offsetSelectedSites() function
* with a set of X/Y/Z offsets to apply.
*/
@SuppressWarnings("ResultOfObjectAllocationIgnored")
private void offsetPositions() {
new OffsetPositionsDialog(this, core_);
}
/**
* Given a device (either a StageDevice or XYStageDevice) and a Vector
* of floats, apply the given offsets to all selected positions for that
* particular device.
* @param deviceName
* @param offsets
*/
public void offsetSelectedSites(String deviceName, ArrayList<Float> offsets) {
PositionList positions = positionModel_.getPositionList();
for (int rowIndex : posTable_.getSelectedRows()) {
MultiStagePosition multiPos = positions.getPosition(rowIndex - 1);
for (int posIndex = 0; posIndex < multiPos.size(); ++posIndex) {
StagePosition subPos = multiPos.get(posIndex);
if (subPos.stageName.equals(deviceName)) {
// This is the one to modify.
if (subPos.numAxes >= 3) {
// With the current definition of StagePosition axis fields,
// I don't think this can ever happen, but hey, future-
// proofing.
subPos.z += offsets.get(2);
}
if (subPos.numAxes >= 2) {
subPos.y += offsets.get(1);
}
// Assume every stage device has at least one axis, because
// if they don't, then oh dear...
subPos.x += offsets.get(0);
}
}
}
positionModel_.fireTableDataChanged();
acqControlDlg_.updateGUIContents();
}
} |
package GuitarView;
import processing.core.PApplet;
import processing.core.PFont;
//import processing.core.PFont;
import processing.core.PGraphics;
import processing.core.PImage;
import processing.core.PConstants;
import java.io.File;
import controlP5.*;
import java.util.ArrayList;
import java.util.List;
import javax.sound.midi.Sequencer;
public class GuitarView extends PApplet {
private static final long serialVersionUID = 3036968534111084926L;
public static final int NUM_STRINGS = 6; // number of strings on guitar
public static final int NUM_FRETS = 13; // number of frets shown on fret board
public static final int NUM_CHANNELS = 16; // max number of channels in sequence
public static int[] fretLines = new int[NUM_FRETS]; // x locations of all frets
public static GuitarString[] strings = new GuitarString[6];;
public static int guitarX, guitarY, guitarH; // parameters for the guitar
public static int dX, dY; // grid to put controls on
public final int copper = color(100, 80, 30);
public final int brass = color(181, 166, 66);
private final int ivory = color(0xFFEEEBB0);
private static PGraphics guitarImage; // for keeping the drawn image of the guitar.
private PImage img;
private MidiEngine me;
private static Slider progSlide;
public static FingerMarker[][] fm = new FingerMarker[NUM_STRINGS][NUM_FRETS]; //pre-made markers for each string and fret
private PFont pfont; // use true/false for smooth/no-smooth
private ControlFont font;
public static ControlP5 cp5;
//private static controlP5.Toggle[] tracTog; // track filter switches
private static Toggle traceTog; // enable/disable tracing
private static Toggle pauseTog;
public static Textarea myTextarea;
public static long loopTickMax, loopTickMin; // looping end points
public static boolean loopState = false;
private static controlP5.RadioButton octaveRadioButton;
private static MultiList tuneList; // selects various guitar tunings
private static MultiListButton regular;
private static MultiListButton instrumental;
private static MultiListButton open;
// String tunings in Midi note numbers
// regular tunings
private final static int[] standard = { 40, 45, 50, 55, 59, 64}; // e a d g b e
private final static int[] majorThird = { 48, 52, 56, 60, 64, 68}; // c e g# c e g#
private final static int[] allFourths = { 40, 45, 50, 55, 60, 65}; // e a d g c f
private final static int[] augmentedFourths = { 36, 42, 48, 54, 60, 66}; // c f# c f# c f#
private final static int[] mandoGuitar = { 26, 43, 50, 57, 64, 71}; // c g d a e b
// instrumental tunings
private final static int[] dobro = { 43, 47, 50, 55, 59, 62}; // g b d g b d
private final static int[] overtone = { 48, 52, 55, 58, 60, 62}; // c e g a# c d
private final static int[] pentatonic = { 45, 48, 50, 52, 55, 57}; // a c d e g a
// open tunings
private final static int[] openC = { 36, 43, 48, 55, 60, 64}; // c g c g c e
private final static int[] openD = { 38, 45, 50, 54, 57, 62}; // d a d f# a d
private final static int[] openG = { 38, 43, 50, 55, 59, 62}; // d g d g b d
private final static int[] openDMinor = { 38, 45, 50, 53, 57, 62}; // d a d f a d
private final static int[] openA = { 40, 45, 49, 52, 57, 64}; // e a c# e a e
// private static int[] Tuning; // open tuning of the six strings
private static int[] noteNumbers; // fret board mapping
private final static String[] noteNames = { "C ", "C#", "D ", "D#", "E ", "F ", "F#",
"G ", "G#", "A ", "A#", "B " };
private static String filename = " ";
// set up the open string tuning
// private void setTuning(int[] t) {
// Tuning = new int[NUM_STRINGS];
// for (int s = 0; s < NUM_STRINGS; s++) {
// Tuning[s] = t[s];
// set up fret board note mapping
private void initNotes(int[] t) {
// Tuning = new int[NUM_STRINGS];
// for (int s = 0; s < NUM_STRINGS; s++) {
// Tuning[s] = t[s];
noteNumbers = new int[NUM_STRINGS * NUM_FRETS];
int i = 0;
int n = 0;
for (int s = 0; s < NUM_STRINGS; s++) {
n = t[s];
for (int f = 0; f < NUM_FRETS; f++) {
noteNumbers[i++] = n++;
}
}
}
// return the note name produced by string s and fret f
public static String getNoteName(int note) {
return noteNames[note % 12] + ((note / 12) - 1);
// return String.valueOf(noteNumbers[note]);
}
// return the note name produced by string s and fret f
private static String getNoteString(int s, int f) {
return getNoteName(noteNumbers[(s * NUM_FRETS) + f]);
// return String.valueOf(noteNumbers[(s * NUM_FRETS) + f]);
}
// print the note produced by string s and fret f at location x y
private void printNote(int s, int f, int x, int y) {
guitarImage.text(getNoteString(s, f), x, y);
}
// return where note may be found on fret board. There may be up to 3 matches
public static List<Integer> noteToStringFrets(byte n) {
List<Integer> finger = new ArrayList<Integer>();
int match = 0;
// scan fret board for a match on n scanned lowest to highest pitch
for (int f = 0; f < NUM_FRETS; f++) {
for (int s = 0; s < NUM_STRINGS; s++) {
if (noteNumbers[(s * NUM_FRETS) + f] == n) {
// add the marker that was found to the array
finger.add(match, s);
finger.add(match + 1, f);
match = match + 2;
break; // take first match, there is only one per string
}
}
}
return finger;
}
// create a cache of pre made finger markers
private void initFingerMarkers() {
for (int s = 0; s < NUM_STRINGS; s++) {
for (int f = 0; f < NUM_FRETS; f++) {
// Initialize each object
fm[s][f] = new FingerMarker(this, guitarImage, strings[s], f);
}
}
}
private void clearTracers() {
for (int s = 0; s < NUM_STRINGS; s++) {
for (int f = 0; f < NUM_FRETS; f++) {
fm[s][f].setInUse(false);
}
}
}
public static controlP5.Toggle getTraceTog() {
return traceTog;
}
public static controlP5.RadioButton getOctaveRadioButton() {
return octaveRadioButton;
}
private void drawGuitar() {
// figure out where the frets should go
float d = (float) (1.47 * width / fretLines.length);
for (int i = 0; i < fretLines.length; ++i) {
fretLines[i] = (int) (i * d + guitarX);
d -= (width * .003); // the frets get closer together as we move up the board
}
guitarImage.beginDraw();
// draw fret board
guitarImage.noStroke();
guitarImage.beginShape();
guitarImage.textureMode(PConstants.NORMAL);
guitarImage.texture(img);
guitarImage.vertex(guitarX, guitarY, 0, 0);
guitarImage.vertex(width, guitarY, 1, 0);
guitarImage.vertex(width, guitarY + guitarH, 1, 1);
guitarImage.vertex(guitarX, guitarY + guitarH, 0, 1);
guitarImage.endShape(PConstants.CLOSE);
// erase background left of neck
guitarImage.fill(ivory);
guitarImage.beginShape();
guitarImage.vertex(0, guitarY);
guitarImage.vertex(guitarX, guitarY);
guitarImage.vertex(guitarX, guitarY + guitarH);
guitarImage.vertex(0, guitarY + guitarH);
guitarImage.endShape(PConstants.CLOSE);
// draw frets, and fret markers
for (int i = 0; i < fretLines.length; ++i) {
guitarImage.strokeWeight(6);
// draw fret shadows
guitarImage.stroke(18, 16, 6);
guitarImage.fill(18, 16, 6);
guitarImage.line(fretLines[i] + 4, guitarY, fretLines[i] + 4, guitarY
+ guitarH);
// then draw frets
guitarImage.stroke(brass);
guitarImage.fill(brass);
guitarImage.line(fretLines[i], guitarY, fretLines[i], guitarY
+ guitarH);
// draw note names
guitarImage.fill(255, 255, 127, 100);
for (int s = 0; s < NUM_STRINGS; s++) {
printNote(s, i, fretLines[i] - 26, strings[s].getY() - 5);
}
// draw markers
guitarImage.fill(0, 0, 0);
guitarImage.noStroke();
if (i == 3 || i == 5 || i == 7 || i == 9)
guitarImage.ellipse((fretLines[i] + fretLines[i - 1]) / 2,
guitarY + guitarH / 2, 18, 18);
else if (i == 12) {
guitarImage.ellipse((fretLines[i] + fretLines[i - 1]) / 2,
guitarY + guitarH / 6, 18, 18);
guitarImage.ellipse((fretLines[i] + fretLines[i - 1]) / 2,
guitarY + 5 * guitarH / 6, 18, 18);
}
}
// draw strings
for (GuitarString s : strings) {
s.draw(guitarImage, copper);
}
image(guitarImage, 0, 0); // render guitar image from buffer
guitarImage.endDraw();
}
public void setup() {
size(1200, 600, P2D);
// size(displayWidth, displayHeight, P2D);
if (frame != null) {
frame.setResizable(true);
}
background(200,50);
initNotes(standard);
guitarImage = createGraphics(width, height, P2D);
img = loadImage("woodgrain3.jpg");
guitarX = height / 20;
guitarY = height / 2 + 20;
guitarH = height / 3 + 60;
dX = width / 30;
dY = height / 18;
int inc = guitarH / 22; // for string y-positions
// initialize strings
strings[0] = new GuitarString(this, guitarY + inc * 21);
strings[1] = new GuitarString(this, guitarY + inc * 17);
strings[2] = new GuitarString(this, guitarY + inc * 13);
strings[3] = new GuitarString(this, guitarY + inc * 9);
strings[4] = new GuitarString(this, guitarY + inc * 5);
strings[5] = new GuitarString(this, guitarY + inc);
me = new MidiEngine();
drawGuitar(); // setup guitar image in buffer
initFingerMarkers();
configureUI();
frameRate(20);
}
private void configureUI() {
cp5 = new ControlP5(this);
cp5.setColorCaptionLabel(0xFF000000);
pfont = createFont("Arial",13,true);
font = new ControlFont(pfont);
ControlFont.sharp();
configFont(cp5.addButton("load_file")
.setPosition(dX, dY)
.setSize(55, 20))
;
cp5.addTextlabel("labelvisual")
.setText("visual display controls")
.setPosition(dX,2 * dY)
.setColorValueLabel(copper)
.setFont(createFont("arial",18))
;
traceTog = cp5.addToggle("trace")
.setPosition(dX, 3 * dY)
.setSize(35, 20).setValue(false)
;
configFont(traceTog);
configFont(cp5.addButton("all")
.setPosition(2 * dX, 3 * dY)
.setSize(35, 20))
;
configFont(cp5.addButton("none")
.setPosition(3 * dX, 3 * dY)
.setSize(35, 20))
;
cp5.addTextlabel("labelplay")
.setText("play controls")
.setPosition(dX, 4 * dY)
.setColorValueLabel(copper)
.setFont(createFont("arial",18))
;
cp5.addTextlabel("labelauthor")
.setText("v0.01 R. Sampson 2015")
.setPosition(25 * dX + 1, 26)
.setColorValueLabel(copper)
.setFont(createFont("arial",11))
;
pauseTog = cp5.addToggle("pause")
.setPosition(6 * dX, 5 * dY)
.setSize(35, 20)
.setValue(false)
;
pauseTog.getCaptionLabel()
.setFont(font)
.toUpperCase(false)
.setSize(13)
;
configFont(cp5.addButton("reset")
.setPosition(7 * dX, 5 * dY)
.setSize(35, 20))
;
configFont(cp5.addButton("fwd")
.setPosition(8 * dX, 5 * dY)
.setSize(35, 20))
;
configFont(cp5.addButton("rev")
.setPosition(9 * dX, 5 * dY)
.setSize(35, 20))
;
configFont(cp5.addButton("Loop")
.setPosition(10 * dX, 5 * dY)
.setSize(35, 20))
;
cp5.addSlider("tempo")
.setRange((float).25,(float)1.5)
.setValue((float).75)
.setPosition(dX, 5 * dY)
.setSize(150, 20)
.getCaptionLabel()
.setFont(font)
.toUpperCase(false)
.setSize(13)
;
progSlide = cp5.addSlider("progress")
.setRange((float)0,(float)0)
.setValue((float)0)
.setPosition(11 * dX, 5 * dY)
.setSize(150, 20)
.setDecimalPrecision(0)
;
progSlide.getCaptionLabel()
.setFont(font)
.toUpperCase(false)
.setSize(13);
myTextarea = cp5.addTextarea("txt")
.setPosition(width / 2 + 2 * dX,2 * dY)
.setSize(200,200)
.setFont(createFont("arial",14))
.setLineHeight(16)
.setColor(color(128))
.setColorBackground(color(255,100))
.setColorForeground(color(255,100))
;
// add list of tuning selections
tuneList = cp5.addMultiList("tunings",width / 2 + 8 * dX,2 * dY,130, 25);
regular = tuneList.add("regular_tunings",1);
configFont(regular);
instrumental = tuneList.add("instrumental_tunings",2);
configFont(instrumental);
open = tuneList.add("open_tunings",3);
configFont(open);
configFont(regular.add("Standard",11).setCaptionLabel("Standard Tuning"));
configFont(regular.add("MajorThird",12).setCaptionLabel("Major Third"));
configFont(regular.add("AllFourths",13).setCaptionLabel("All Fourths"));
configFont(regular.add("AugmentedFourths",14).setCaptionLabel("Augmented Fourths"));
configFont(regular.add("MandoGuitar",15).setCaptionLabel("Mando Guitar"));
configFont(instrumental.add("Dobro",21).setCaptionLabel("Dobro Tuning"));
configFont(instrumental.add("Overtone",22).setCaptionLabel("Overtone Tuning"));
configFont(instrumental.add("Pentatonic",23).setCaptionLabel("Pentatonic Tuning"));
configFont(open.add("OpenA",35).setCaptionLabel("Open A"));
configFont(open.add("OpenC",31).setCaptionLabel("Open C"));
configFont(open.add("OpenD",32).setCaptionLabel("Open D"));
configFont(open.add("OpenDMinor",33).setCaptionLabel("Open D Minor"));
configFont(open.add("OpenG",34).setCaptionLabel("Open G"));
cp5.getTooltip().register("load_file","Browse midi files to play");
cp5.getTooltip().register("all","Enable display of all channels (voices)");
cp5.getTooltip().register("none","Supress display off all channels");
cp5.getTooltip().register("pause","Pause music play");
cp5.getTooltip().register("fwd","bump play position forward in time");
cp5.getTooltip().register("rev","bump play position backwards in time");
cp5.getTooltip().register("Loop","loop play between the last two pause points");
cp5.getTooltip().register("progress","Slide with mouse to change play position");
cp5.getTooltip().register("tempo","Slide with mouse to change tempo");
cp5.getTooltip().register("reset","Play music from te begining");
cp5.getTooltip().register("trace","Turn on visual indication of which notes have been played");
cp5.getTooltip().register("tunings","Configure special guitar tunings");
//cp5.loadProperties(("properties"));
myTextarea.clear();
}
@SuppressWarnings("rawtypes")
private void configFont(controlP5.Controller cc) {
cc.getCaptionLabel()
.setFont(font)
.toUpperCase(false)
.setSize(13).setColor(0xffffffff);
}
// handle gui events
public void controlEvent(ControlEvent theEvent) {
if (theEvent.isController()) {
print("control event from : " + theEvent.getName());
switch (theEvent.getName()) {
case "Standard":
initNotes(standard);
clearFretboard();
break;
case "MajorThird":
initNotes(majorThird);
clearFretboard();
break;
case "AllFourths":
initNotes(allFourths);
clearFretboard();
break;
case "AugmentedFourths":
initNotes(augmentedFourths);
clearFretboard();
break;
case "MandoGuitar":
initNotes(mandoGuitar);
clearFretboard();
break;
case "Dobro":
initNotes(dobro);
clearFretboard();
break;
case "Overtone":
initNotes(overtone);
clearFretboard();
break;
case "Pentatonic":
initNotes(pentatonic);
clearFretboard();
break;
case "OpenC":
initNotes(openC);
clearFretboard();
break;
case "OpenD":
initNotes(openD);
clearFretboard();
break;
case "OpenG":
initNotes(openG);
clearFretboard();
break;
case "OpenDMinor":
initNotes(openDMinor);
clearFretboard();
break;
case "OpenA":
initNotes(openA);
clearFretboard();
break;
}
}
}
public static Slider getProgSlide() {
return progSlide;
}
public void fileSelected(File selection) {
if (selection == null) {
println("Window was closed or the user hit cancel.");
}
else {
filename = selection.getAbsolutePath();
println("User selected " + filename);
this.reset();
me.loadSequenceFromFile( selection);
}
clearFretboard();
}
@SuppressWarnings("unused")
private void tempo(float theTempo) { // change tempo with slider
if (me.sequencer != null) {
me.sequencer.setTempoFactor(theTempo);
}
}
@SuppressWarnings("unused")
private void progress(float thePosition) { // change position in sequence
Sequencer seq = me.sequencer;
// update the progress slider when under human control
if (seq != null && seq.getSequence() != null && mouseButton == LEFT ) {
seq.stop();
seq.setTickPosition((long)thePosition);
seq.start();
}
}
@SuppressWarnings("unused")
private void pause(boolean theValue) { // start and stop sequencer with
// save pause points for looping
Sequencer seq = me.sequencer;
if (seq != null && me.sequence != null) {
if (theValue == false) {
seq.start();
} else {
seq.stop();
if (loopState != true) {
loopTickMin = loopTickMax;
loopTickMax = seq.getTickPosition();
loopTickMin = (long) min(loopTickMax, loopTickMin);
loopTickMax = (long) max(loopTickMax, loopTickMin);
}
loopState = false;
}
}
}
private void reset() { // reset sequencer button
if (me.sequencer != null) {
me.sequencer.setTickPosition(0);
}
getProgSlide().setValue(0);
loopTickMax = 0;
loopTickMin = 0; // looping end points
loopState = false;
pauseTog.setValue(false);
clearFretboard();
}
@SuppressWarnings("unused")
private void Loop() { // reset sequencer button
if (me.sequencer != null) {
me.sequencer.setTickPosition(loopTickMin);
}
if (loopTickMax != 0) {
loopState = true;
pauseTog.setValue(false);
}
clearFretboard();
}
@SuppressWarnings("unused")
private void fwd() { // reset sequencer button
Sequencer seq = me.sequencer;
if (seq != null) {
seq.setTickPosition(seq.getTickPosition() + 5000);
}
clearFretboard();
}
@SuppressWarnings("unused")
private void rev() { // reset sequencer button
Sequencer seq = me.sequencer;
if (seq != null) {
seq.setTickPosition(seq.getTickPosition() - 5000);
}
clearFretboard();
}
@SuppressWarnings("unused")
private void load_file() { // load midi file button
if (me.sequencer != null) {
me.sequencer.stop();
// enable all channels
for (controlP5.Toggle t : MidiEngine.chanTog) {
t.setValue(true);
}
}
clearFretboard();
selectInput("Select a Midi file to play:", "fileSelected");
}
@SuppressWarnings("unused")
private void all() { // turn all channel toggles on
for (controlP5.Toggle t : MidiEngine.chanTog) {
t.setValue(true);
}
clearFretboard();
}
@SuppressWarnings("unused")
private void none() { // turn all channel toggles on
for (controlP5.Toggle t : MidiEngine.chanTog) {
t.setValue(false);
}
clearFretboard();
}
private void clearFretboard() {
if (me.sequencer != null) {
me.clearFingerMarkers();
if (guitarImage != null) {
guitarImage.beginDraw();
drawGuitar();
image(guitarImage, 0, 0);
guitarImage.endDraw();
}
}
clearTracers();
}
@SuppressWarnings("unused")
private void trace() {
clearFretboard();
}
public void draw() {
background(200,50);
guitarImage.beginDraw();
image(guitarImage, 0, 0); // render image of guitar from buffer
guitarImage.endDraw();
textSize(25);
fill(0xFF000000);
text("Guitar View", dX + 1, 26);
fill(brass);
text("Guitar View", dX, 25);
textSize(16);
fill(brass);
text(filename, 3 * dX, height / 11);
// draw finger markers on fret board
for (GuitarChannel c : MidiEngine.gchannels) {
for (int s = 0; s < NUM_STRINGS; s++) {
FingerMarker fm = c.getStringStates().get(s);
if (fm != null) {
fm.draw();
fm.drawTracer();
}
}
}
}
public static void main(String _args[]) {
PApplet.main(new String[] { GuitarView.class.getName() });
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
// GuitarChannel.killChannels(MidiEngine.gchannels, MidiEngine.chanTog);
// // call garbage collector to purge channel properties
// System.gc();
// cp5.saveProperties(("properties"));
}
}, "Shutdown-thread"));
}
} |
package org.openhab.habdroid.ui;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewDatabase;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.larswerkman.holocolorpicker.ColorPicker;
import com.larswerkman.holocolorpicker.SaturationBar;
import com.larswerkman.holocolorpicker.ValueBar;
import okhttp3.HttpUrl;
import org.openhab.habdroid.R;
import org.openhab.habdroid.core.connection.Connection;
import org.openhab.habdroid.model.Item;
import org.openhab.habdroid.model.LabeledValue;
import org.openhab.habdroid.model.ParsedState;
import org.openhab.habdroid.model.Widget;
import org.openhab.habdroid.ui.widget.DividerItemDecoration;
import org.openhab.habdroid.ui.widget.ExtendedSpinner;
import org.openhab.habdroid.ui.widget.SegmentedControlButton;
import org.openhab.habdroid.ui.widget.WidgetImageView;
import org.openhab.habdroid.util.Constants;
import org.openhab.habdroid.util.MjpegStreamer;
import org.openhab.habdroid.util.Util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import static org.openhab.habdroid.util.Constants.PREFERENCE_CHART_HQ;
/**
* This class provides openHAB widgets adapter for list view.
*/
public class WidgetAdapter extends RecyclerView.Adapter<WidgetAdapter.ViewHolder>
implements View.OnClickListener, View.OnLongClickListener {
private static final String TAG = WidgetAdapter.class.getSimpleName();
public interface ItemClickListener {
void onItemClicked(Widget item);
void onItemLongClicked(Widget item);
}
private static final int TYPE_GENERICITEM = 0;
private static final int TYPE_FRAME = 1;
private static final int TYPE_GROUP = 2;
private static final int TYPE_SWITCH = 3;
private static final int TYPE_TEXT = 4;
private static final int TYPE_SLIDER = 5;
private static final int TYPE_IMAGE = 6;
private static final int TYPE_SELECTION = 7;
private static final int TYPE_SECTIONSWITCH = 8;
private static final int TYPE_ROLLERSHUTTER = 9;
private static final int TYPE_SETPOINT = 10;
private static final int TYPE_CHART = 11;
private static final int TYPE_VIDEO = 12;
private static final int TYPE_WEB = 13;
private static final int TYPE_COLOR = 14;
private static final int TYPE_VIDEO_MJPEG = 15;
private static final int TYPE_LOCATION = 16;
private final ArrayList<Widget> mItems = new ArrayList<>();
private final LayoutInflater mInflater;
private ItemClickListener mItemClickListener;
private CharSequence mChartTheme;
private int mSelectedPosition = -1;
private Connection mConnection;
private ColorMapper mColorMapper;
public WidgetAdapter(Context context, Connection connection,
ItemClickListener itemClickListener) {
super();
mInflater = LayoutInflater.from(context);
mItemClickListener = itemClickListener;
mConnection = connection;
mColorMapper = new ColorMapper(context);
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(R.attr.chartTheme, tv, true);
mChartTheme = tv.string;
}
public void update(List<Widget> widgets, boolean forceFullUpdate) {
boolean compatibleUpdate = true;
if (widgets.size() != mItems.size() || forceFullUpdate) {
compatibleUpdate = false;
} else {
for (int i = 0; i < widgets.size(); i++) {
if (getItemViewType(mItems.get(i)) != getItemViewType(widgets.get(i))) {
compatibleUpdate = false;
break;
}
}
}
if (compatibleUpdate) {
for (int i = 0; i < widgets.size(); i++) {
if (!mItems.get(i).equals(widgets.get(i))) {
mItems.set(i, widgets.get(i));
notifyItemChanged(i);
}
}
} else {
mItems.clear();
mItems.addAll(widgets);
notifyDataSetChanged();
}
}
public void updateWidget(Widget widget) {
for (int i = 0; i < mItems.size(); i++) {
if (mItems.get(i).id().equals(widget.id())) {
mItems.set(i, widget);
notifyItemChanged(i);
break;
}
}
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final ViewHolder holder;
switch (viewType) {
case TYPE_GENERICITEM:
holder = new GenericViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_FRAME:
holder = new FrameViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_GROUP:
holder = new GroupViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_SWITCH:
holder = new SwitchViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_TEXT:
holder = new TextViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_SLIDER:
holder = new SliderViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_IMAGE:
holder = new ImageViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_SELECTION:
holder = new SelectionViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_SECTIONSWITCH:
holder = new SectionSwitchViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_ROLLERSHUTTER:
holder = new RollerShutterViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_SETPOINT:
holder = new SetpointViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_CHART:
holder = new ChartViewHolder(mInflater, parent,
mChartTheme, mConnection, mColorMapper);
break;
case TYPE_VIDEO:
holder = new VideoViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_WEB:
holder = new WebViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_COLOR:
holder = new ColorViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_VIDEO_MJPEG:
holder = new MjpegVideoViewHolder(mInflater, parent, mConnection, mColorMapper);
break;
case TYPE_LOCATION:
holder = MapViewHelper.createViewHolder(mInflater, parent,
mConnection, mColorMapper);
break;
default:
throw new IllegalArgumentException("View type " + viewType + " is not known");
}
holder.itemView.setTag(holder);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.stop();
holder.bind(mItems.get(position));
if (holder instanceof FrameViewHolder) {
((FrameViewHolder) holder).setShownAsFirst(position == 0);
}
holder.itemView.setActivated(mSelectedPosition == position);
holder.itemView.setOnClickListener(mItemClickListener != null ? this : null);
holder.itemView.setOnLongClickListener(mItemClickListener != null ? this : null);
holder.itemView.setClickable(mItemClickListener != null);
}
@Override
public void onViewAttachedToWindow(ViewHolder holder) {
super.onViewAttachedToWindow(holder);
holder.start();
}
@Override
public void onViewDetachedFromWindow(ViewHolder holder) {
super.onViewDetachedFromWindow(holder);
holder.stop();
}
@Override
public int getItemCount() {
return mItems.size();
}
public Widget getItem(int position) {
return mItems.get(position);
}
@Override
public int getItemViewType(int position) {
return getItemViewType(mItems.get(position));
}
private int getItemViewType(Widget widget) {
switch (widget.type()) {
case Frame:
return TYPE_FRAME;
case Group:
return TYPE_GROUP;
case Switch:
if (widget.hasMappings()) {
return TYPE_SECTIONSWITCH;
} else {
Item item = widget.item();
if (item != null && item.isOfTypeOrGroupType(Item.Type.Rollershutter)) {
return TYPE_ROLLERSHUTTER;
}
return TYPE_SWITCH;
}
case Text:
return TYPE_TEXT;
case Slider:
return TYPE_SLIDER;
case Image:
return TYPE_IMAGE;
case Selection:
return TYPE_SELECTION;
case Setpoint:
return TYPE_SETPOINT;
case Chart:
return TYPE_CHART;
case Video:
if ("mjpeg".equalsIgnoreCase(widget.encoding())) {
return TYPE_VIDEO_MJPEG;
}
return TYPE_VIDEO;
case Webview:
return TYPE_WEB;
case Colorpicker:
return TYPE_COLOR;
case Mapview:
return TYPE_LOCATION;
default:
return TYPE_GENERICITEM;
}
}
public boolean setSelectedPosition(int position) {
if (mSelectedPosition == position) {
return false;
}
if (mSelectedPosition >= 0) {
notifyItemChanged(mSelectedPosition);
}
mSelectedPosition = position;
if (position >= 0) {
notifyItemChanged(position);
}
return true;
}
@Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
int position = holder.getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mItemClickListener.onItemClicked(mItems.get(position));
}
}
@Override
public boolean onLongClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
int position = holder.getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mItemClickListener.onItemLongClicked(mItems.get(position));
}
return false;
}
public abstract static class ViewHolder extends RecyclerView.ViewHolder {
protected final Connection mConnection;
private final ColorMapper mColorMapper;
ViewHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutResId,
Connection conn, ColorMapper colorMapper) {
super(inflater.inflate(layoutResId, parent, false));
mConnection = conn;
mColorMapper = colorMapper;
}
public abstract void bind(Widget widget);
public void start() {}
public void stop() {}
protected void updateTextViewColor(TextView view, String colorName) {
ColorStateList origColor = (ColorStateList) view.getTag(R.id.originalColor);
Integer color = mColorMapper.mapColor(colorName);
if (color != null) {
if (origColor == null) {
view.setTag(R.id.originalColor, view.getTextColors());
}
view.setTextColor(color);
} else if (origColor != null) {
view.setTextColor(origColor);
view.setTag(R.id.originalColor, null);
}
}
protected void updateIcon(WidgetImageView iconView, Widget widget) {
if (widget.icon() == null) {
iconView.setImageDrawable(null);
return;
}
// This is needed to escape possible spaces and everything according to rfc2396
String iconUrl = Uri.encode(widget.iconPath(), "/?=&");
iconView.setImageUrl(mConnection, iconUrl, iconView.getResources()
.getDimensionPixelSize(R.dimen.notificationlist_icon_size));
Integer iconColor = mColorMapper.mapColor(widget.iconColor());
if (iconColor != null) {
iconView.setColorFilter(iconColor);
} else {
iconView.clearColorFilter();
}
}
}
public abstract static class LabeledItemBaseViewHolder extends ViewHolder {
protected final TextView mLabelView;
protected final TextView mValueView;
protected final WidgetImageView mIconView;
LabeledItemBaseViewHolder(LayoutInflater inflater, ViewGroup parent,
@LayoutRes int layoutResId, Connection conn, ColorMapper colorMapper) {
super(inflater, parent, layoutResId, conn, colorMapper);
mLabelView = itemView.findViewById(R.id.widgetlabel);
mValueView = itemView.findViewById(R.id.widgetvalue);
mIconView = itemView.findViewById(R.id.widgeticon);
}
@Override
public void bind(Widget widget) {
String[] splitString = widget.label().split("\\[|\\]");
mLabelView.setText(splitString.length > 0 ? splitString[0] : null);
updateTextViewColor(mLabelView, widget.labelColor());
if (mValueView != null) {
mValueView.setText(splitString.length > 1 ? splitString[1] : null);
mValueView.setVisibility(splitString.length > 1 ? View.VISIBLE : View.GONE);
updateTextViewColor(mValueView, widget.valueColor());
}
updateIcon(mIconView, widget);
}
}
public static class GenericViewHolder extends ViewHolder {
private final TextView mLabelView;
private final WidgetImageView mIconView;
GenericViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_genericitem, conn, colorMapper);
mLabelView = itemView.findViewById(R.id.widgetlabel);
mIconView = itemView.findViewById(R.id.widgeticon);
}
@Override
public void bind(Widget widget) {
mLabelView.setText(widget.label());
updateTextViewColor(mLabelView, widget.labelColor());
updateIcon(mIconView, widget);
}
}
public static class FrameViewHolder extends ViewHolder {
private final View mDivider;
private final View mSpacer;
private final TextView mLabelView;
FrameViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_frameitem, conn, colorMapper);
mLabelView = itemView.findViewById(R.id.widgetlabel);
mDivider = itemView.findViewById(R.id.divider);
mSpacer = itemView.findViewById(R.id.spacer);
itemView.setClickable(false);
}
@Override
public void bind(Widget widget) {
mLabelView.setText(widget.label());
updateTextViewColor(mLabelView, widget.valueColor());
// hide empty frames
itemView.setVisibility(widget.label().isEmpty() ? View.GONE : View.VISIBLE);
}
public void setShownAsFirst(boolean shownAsFirst) {
mDivider.setVisibility(shownAsFirst ? View.GONE : View.VISIBLE);
mSpacer.setVisibility(shownAsFirst ? View.VISIBLE : View.GONE);
}
}
public static class GroupViewHolder extends LabeledItemBaseViewHolder {
private final ImageView mRightArrow;
GroupViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_groupitem, conn, colorMapper);
mRightArrow = itemView.findViewById(R.id.right_arrow);
}
@Override
public void bind(Widget widget) {
super.bind(widget);
mRightArrow.setVisibility(widget.linkedPage() != null ? View.VISIBLE : View.GONE);
}
}
public static class SwitchViewHolder extends LabeledItemBaseViewHolder
implements View.OnTouchListener {
private final SwitchCompat mSwitch;
private Item mBoundItem;
SwitchViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_switchitem, conn, colorMapper);
mSwitch = itemView.findViewById(R.id.toggle);
mSwitch.setOnTouchListener(this);
}
@Override
public void bind(Widget widget) {
super.bind(widget);
mBoundItem = widget.item();
ParsedState state = mBoundItem != null ? mBoundItem.state() : null;
mSwitch.setChecked(state != null && state.asBoolean());
}
@Override
public boolean onTouch(View v, MotionEvent motionEvent) {
if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
Util.sendItemCommand(mConnection.getAsyncHttpClient(), mBoundItem,
mSwitch.isChecked() ? "OFF" : "ON");
}
return false;
}
}
public static class TextViewHolder extends LabeledItemBaseViewHolder {
private final ImageView mRightArrow;
TextViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_textitem, conn, colorMapper);
mRightArrow = itemView.findViewById(R.id.right_arrow);
}
@Override
public void bind(Widget widget) {
super.bind(widget);
mRightArrow.setVisibility(widget.linkedPage() != null ? View.VISIBLE : View.GONE);
}
}
public static class SliderViewHolder extends LabeledItemBaseViewHolder
implements SeekBar.OnSeekBarChangeListener {
private final SeekBar mSeekBar;
private Widget mBoundWidget;
SliderViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_slideritem, conn, colorMapper);
mSeekBar = itemView.findViewById(R.id.seekbar);
mSeekBar.setOnSeekBarChangeListener(this);
}
@Override
public void bind(Widget widget) {
super.bind(widget);
mBoundWidget = widget;
float stepCount = (widget.maxValue() - widget.minValue()) / widget.step();
mSeekBar.setMax((int) Math.ceil(stepCount));
mSeekBar.setProgress(0);
Item item = widget.item();
ParsedState state = item != null ? item.state() : null;
if (item == null || state == null) {
return;
}
if (item.isOfTypeOrGroupType(Item.Type.Color)) {
Integer brightness = state.asBrightness();
if (brightness != null) {
mSeekBar.setMax(100);
mSeekBar.setProgress(brightness);
}
} else {
ParsedState.NumberState number = state.asNumber();
if (number != null) {
float progress =
(number.mValue.floatValue() - widget.minValue()) / widget.step();
mSeekBar.setProgress(Math.round(progress));
}
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.d(TAG, "onStartTrackingTouch position = " + seekBar.getProgress());
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress = seekBar.getProgress();
Log.d(TAG, "onStopTrackingTouch position = " + progress);
Item item = mBoundWidget.item();
if (item == null) {
return;
}
float newValue = mBoundWidget.minValue() + (mBoundWidget.step() * progress);
final ParsedState.NumberState previousState =
item.state() != null ? item.state().asNumber() : null;
Util.sendItemCommand(mConnection.getAsyncHttpClient(), item,
ParsedState.NumberState.withValue(previousState, newValue));
}
}
public static class ImageViewHolder extends ViewHolder {
private final WidgetImageView mImageView;
private final View mParentView;
private int mRefreshRate;
ImageViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_imageitem, conn, colorMapper);
mImageView = itemView.findViewById(R.id.image);
mParentView = parent;
}
@Override
public void bind(Widget widget) {
ParsedState state = widget.state();
final String value = state != null ? state.asString() : null;
// Make sure images fit into the content frame by scaling
// them at max 90% of the available height
int maxHeight = mParentView.getHeight() > 0
? Math.round(0.9f * mParentView.getHeight()) : Integer.MAX_VALUE;
mImageView.setMaxHeight(maxHeight);
if (value != null && value.matches("data:image/.*;base64,.*")) {
final String dataString = value.substring(value.indexOf(",") + 1);
byte[] data = Base64.decode(dataString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
mImageView.setImageBitmap(bitmap);
mRefreshRate = 0;
} else {
mImageView.setImageUrl(mConnection, widget.url(), mParentView.getWidth());
mRefreshRate = widget.refresh();
}
}
@Override
public void start() {
if (mRefreshRate > 0) {
mImageView.setRefreshRate(mRefreshRate);
} else {
mImageView.cancelRefresh();
}
}
@Override
public void stop() {
mImageView.cancelRefresh();
}
}
public static class SelectionViewHolder extends LabeledItemBaseViewHolder
implements ExtendedSpinner.OnSelectionUpdatedListener {
private final ExtendedSpinner mSpinner;
private Item mBoundItem;
private List<LabeledValue> mBoundMappings;
SelectionViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_selectionitem, conn, colorMapper);
mSpinner = itemView.findViewById(R.id.spinner);
mSpinner.setOnSelectionUpdatedListener(this);
}
@Override
public void bind(Widget widget) {
super.bind(widget);
mBoundItem = widget.item();
mBoundMappings = widget.getMappingsOrItemOptions();
int spinnerSelectedIndex = -1;
ArrayList<String> spinnerArray = new ArrayList<>();
ParsedState state = mBoundItem != null ? mBoundItem.state() : null;
String stateString = state != null ? state.asString() : null;
for (LabeledValue mapping : mBoundMappings) {
String command = mapping.value();
spinnerArray.add(mapping.label());
if (command != null && command.equals(stateString)) {
spinnerSelectedIndex = spinnerArray.size() - 1;
}
}
if (spinnerSelectedIndex == -1) {
spinnerArray.add(" ");
spinnerSelectedIndex = spinnerArray.size() - 1;
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(itemView.getContext(),
android.R.layout.simple_spinner_item, spinnerArray);
spinnerAdapter.setDropDownViewResource(R.layout.select_dialog_singlechoice);
mSpinner.setPrompt(mLabelView.getText());
mSpinner.setAdapter(spinnerAdapter);
mSpinner.setSelectionWithoutUpdateCallback(spinnerSelectedIndex);
}
@Override
public void onSelectionUpdated(int position) {
Log.d(TAG, "Spinner item click on index " + position);
if (position >= mBoundMappings.size()) {
return;
}
LabeledValue item = mBoundMappings.get(position);
Log.d(TAG, "Spinner onItemSelected found match with " + item.value());
Util.sendItemCommand(mConnection.getAsyncHttpClient(), mBoundItem, item.value());
}
}
public static class SectionSwitchViewHolder extends LabeledItemBaseViewHolder
implements View.OnClickListener {
private final LayoutInflater mInflater;
private final RadioGroup mRadioGroup;
private Item mBoundItem;
SectionSwitchViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent,
R.layout.widgetlist_sectionswitchitem, conn, colorMapper);
mInflater = inflater;
mRadioGroup = itemView.findViewById(R.id.switchgroup);
}
@Override
public void bind(Widget widget) {
super.bind(widget);
mBoundItem = widget.item();
List<LabeledValue> mappings = widget.mappings();
// inflate missing views
for (int i = mRadioGroup.getChildCount(); i < mappings.size(); i++) {
View view = mInflater.inflate(R.layout.widgetlist_sectionswitchitem_button,
mRadioGroup, false);
view.setOnClickListener(this);
mRadioGroup.addView(view);
}
// bind views
final String state = mBoundItem != null && mBoundItem.state() != null
? mBoundItem.state().asString() : null;
for (int i = 0; i < mappings.size(); i++) {
SegmentedControlButton button = (SegmentedControlButton) mRadioGroup.getChildAt(i);
String command = mappings.get(i).value();
button.setText(mappings.get(i).label());
button.setTag(command);
button.setChecked(state != null && TextUtils.equals(state, command));
button.setVisibility(View.VISIBLE);
}
// hide spare views
for (int i = mappings.size(); i < mRadioGroup.getChildCount(); i++) {
mRadioGroup.getChildAt(i).setVisibility(View.GONE);
}
}
@Override
public void onClick(View view) {
final String cmd = (String) view.getTag();
Util.sendItemCommand(mConnection.getAsyncHttpClient(), mBoundItem, cmd);
}
}
public static class RollerShutterViewHolder extends LabeledItemBaseViewHolder
implements View.OnTouchListener {
private Item mBoundItem;
RollerShutterViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent,
R.layout.widgetlist_rollershutteritem, conn, colorMapper);
initButton(R.id.up_button, "UP");
initButton(R.id.down_button, "DOWN");
initButton(R.id.stop_button, "STOP");
}
private void initButton(@IdRes int resId, String command) {
ImageButton button = itemView.findViewById(resId);
button.setOnTouchListener(this);
button.setTag(command);
}
@Override
public void bind(Widget widget) {
super.bind(widget);
mBoundItem = widget.item();
}
@Override
public boolean onTouch(View v, MotionEvent motionEvent) {
if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
final String cmd = (String) v.getTag();
Util.sendItemCommand(mConnection.getAsyncHttpClient(), mBoundItem, cmd);
}
return false;
}
}
public static class SetpointViewHolder extends LabeledItemBaseViewHolder
implements View.OnClickListener {
private final LayoutInflater mInflater;
private Widget mBoundWidget;
SetpointViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_setpointitem, conn, colorMapper);
mValueView.setOnClickListener(this);
mInflater = inflater;
ImageView dropdownArrow = itemView.findViewById(R.id.down_arrow);
dropdownArrow.setOnClickListener(this);
}
@Override
public void bind(Widget widget) {
super.bind(widget);
mBoundWidget = widget;
}
@Override
public void onClick(final View view) {
if (mBoundWidget.state() == null) {
Log.e(TAG, "mBoundWidget.state() is null");
return;
}
ParsedState.NumberState state = mBoundWidget.state().asNumber();
float minValue = mBoundWidget.minValue();
float maxValue = mBoundWidget.maxValue();
// This prevents an exception below, but could lead to
// user confusion if this case is ever encountered.
float stepSize = minValue == maxValue ? 1 : mBoundWidget.step();
final int stepCount = ((int) (Math.abs(maxValue - minValue) / stepSize)) + 1;
final ParsedState.NumberState[] stepValues = new ParsedState.NumberState[stepCount];
final String[] stepValueLabels = new String[stepCount];
int closestIndex = 0;
float closestDelta = Float.MAX_VALUE;
final Float stateValue = state != null ? state.mValue.floatValue() : null;
for (int i = 0; i < stepValues.length; i++) {
float stepValue = minValue + i * stepSize;
stepValues[i] = ParsedState.NumberState.withValue(state, stepValue);
stepValueLabels[i] = stepValues[i].toString();
if (stateValue != null && Math.abs(stateValue - stepValue) < closestDelta) {
closestIndex = i;
closestDelta = Math.abs(stateValue - stepValue);
}
}
final View dialogView = mInflater.inflate(R.layout.dialog_numberpicker, null);
final NumberPicker numberPicker = dialogView.findViewById(R.id.numberpicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(stepValues.length - 1);
numberPicker.setDisplayedValues(stepValueLabels);
numberPicker.setValue(closestIndex);
new AlertDialog.Builder(view.getContext())
.setTitle(mLabelView.getText())
.setView(dialogView)
.setPositiveButton(R.string.set, (dialog, which) -> {
Util.sendItemCommand(mConnection.getAsyncHttpClient(),
mBoundWidget.item(), stepValues[numberPicker.getValue()]);
})
.setNegativeButton(R.string.cancel, null)
.show();
}
}
public static class ChartViewHolder extends ViewHolder {
private final WidgetImageView mImageView;
private final View mParentView;
private final CharSequence mChartTheme;
private final Random mRandom = new Random();
private final SharedPreferences mPrefs;
private int mRefreshRate = 0;
private int mDensity;
ChartViewHolder(LayoutInflater inflater, ViewGroup parent, CharSequence theme,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_chartitem, conn, colorMapper);
mImageView = itemView.findViewById(R.id.chart);
mParentView = parent;
final Context context = itemView.getContext();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
mDensity = metrics.densityDpi;
mChartTheme = theme;
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
}
@Override
public void bind(Widget widget) {
Item item = widget.item();
if (item != null) {
float scalingFactor = mPrefs.getFloat(Constants.PREFERENCE_CHART_SCALING,
1.0f);
boolean requestHighResChart = mPrefs.getBoolean(PREFERENCE_CHART_HQ, true);
float actualDensity = (float) mDensity / scalingFactor;
StringBuilder chartUrl = new StringBuilder("chart?")
.append(item.type() == Item.Type.Group ? "groups=" : "items=")
.append(item.name())
.append("&period=").append(widget.period())
.append("&random=").append(mRandom.nextInt())
.append("&dpi=").append(requestHighResChart ? (int) actualDensity :
(int) actualDensity / 2);
if (!TextUtils.isEmpty(widget.service())) {
chartUrl.append("&service=").append(widget.service());
}
if (mChartTheme != null) {
chartUrl.append("&theme=").append(mChartTheme);
}
if (widget.legend() != null) {
chartUrl.append("&legend=").append(widget.legend());
}
int parentWidth = mParentView.getWidth();
if (parentWidth > 0) {
chartUrl.append("&w=").append(requestHighResChart ? parentWidth :
parentWidth / 2);
chartUrl.append("&h=").append(requestHighResChart ? parentWidth / 2 :
parentWidth / 4);
}
Log.d(TAG, "Chart url = " + chartUrl);
mImageView.setImageUrl(mConnection, chartUrl.toString(), parentWidth, true);
mRefreshRate = widget.refresh();
} else {
Log.e(TAG, "Chart item is null");
mImageView.setImageDrawable(null);
mRefreshRate = 0;
}
}
@Override
public void start() {
if (mRefreshRate > 0) {
mImageView.setRefreshRate(mRefreshRate);
} else {
mImageView.cancelRefresh();
}
}
@Override
public void stop() {
mImageView.cancelRefresh();
}
}
public static class VideoViewHolder extends ViewHolder {
private final VideoView mVideoView;
VideoViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_videoitem, conn, colorMapper);
mVideoView = itemView.findViewById(R.id.video);
}
@Override
public void bind(Widget widget) {
// FIXME: check for URL changes here
if (!mVideoView.isPlaying()) {
final String videoUrl;
Item videoItem = widget.item();
if ("hls".equalsIgnoreCase(widget.encoding())
&& videoItem != null
&& videoItem.type() == Item.Type.StringItem
&& videoItem.state() != null) {
videoUrl = videoItem.state().asString();
} else {
videoUrl = widget.url();
}
Log.d(TAG, "Opening video at " + videoUrl);
mVideoView.setVideoURI(Uri.parse(videoUrl));
}
}
@Override
public void start() {
mVideoView.start();
}
@Override
public void stop() {
mVideoView.stopPlayback();
}
}
public static class WebViewHolder extends ViewHolder {
private final WebView mWebView;
private final int mRowHeightPixels;
WebViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_webitem, conn, colorMapper);
mWebView = itemView.findViewById(R.id.webview);
final Resources res = itemView.getContext().getResources();
mRowHeightPixels = res.getDimensionPixelSize(R.dimen.row_height);
}
@SuppressLint("SetJavaScriptEnabled")
@Override
public void bind(Widget widget) {
mWebView.loadUrl("about:blank");
ViewGroup.LayoutParams lp = mWebView.getLayoutParams();
int desiredHeightPixels = widget.height() > 0
? widget.height() * mRowHeightPixels : ViewGroup.LayoutParams.WRAP_CONTENT;
if (lp.height != desiredHeightPixels) {
lp.height = desiredHeightPixels;
mWebView.setLayoutParams(lp);
}
String url = mConnection.getAsyncHttpClient().buildUrl(widget.url()).toString();
Util.applyAuthentication(mWebView, mConnection, url);
mWebView.setWebViewClient(new AnchorWebViewClient(url,
mConnection.getUsername(), mConnection.getPassword()));
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
}
}
public static class ColorViewHolder extends LabeledItemBaseViewHolder implements
View.OnTouchListener, Handler.Callback, ColorPicker.OnColorChangedListener {
private Item mBoundItem;
private final LayoutInflater mInflater;
private final Handler mHandler = new Handler(this);
ColorViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_coloritem, conn, colorMapper);
mInflater = inflater;
initButton(R.id.up_button, "ON");
initButton(R.id.down_button, "OFF");
itemView.findViewById(R.id.select_color_button).setOnTouchListener(this);
}
private void initButton(@IdRes int resId, String command) {
ImageButton button = itemView.findViewById(resId);
button.setOnTouchListener(this);
button.setTag(command);
}
@Override
public void bind(Widget widget) {
super.bind(widget);
mBoundItem = widget.item();
}
@Override
public boolean onTouch(View v, MotionEvent motionEvent) {
if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
if (v.getTag() instanceof String) {
final String cmd = (String) v.getTag();
Util.sendItemCommand(mConnection.getAsyncHttpClient(), mBoundItem, cmd);
} else {
showColorPickerDialog();
}
}
return false;
}
@Override
public boolean handleMessage(Message msg) {
final float[] hsv = new float[3];
Color.RGBToHSV(Color.red(msg.arg1), Color.green(msg.arg1), Color.blue(msg.arg1), hsv);
Log.d(TAG, "New color HSV = " + hsv[0] + ", " + hsv[1] + ", " + hsv[2]);
final String newColorValue = String.format(Locale.US, "%f,%f,%f",
hsv[0], hsv[1] * 100, hsv[2] * 100);
Util.sendItemCommand(mConnection.getAsyncHttpClient(), mBoundItem, newColorValue);
return true;
}
@Override
public void onColorChanged(int color) {
mHandler.removeMessages(0);
mHandler.sendMessageDelayed(mHandler.obtainMessage(0, color, 0), 100);
}
private void showColorPickerDialog() {
View contentView = mInflater.inflate(R.layout.color_picker_dialog, null);
ColorPicker colorPicker = contentView.findViewById(R.id.picker);
SaturationBar saturationBar = contentView.findViewById(R.id.saturation_bar);
ValueBar valueBar = contentView.findViewById(R.id.value_bar);
colorPicker.addSaturationBar(saturationBar);
colorPicker.addValueBar(valueBar);
colorPicker.setOnColorChangedListener(this);
colorPicker.setShowOldCenterColor(false);
float[] initialColor = mBoundItem != null && mBoundItem.state() != null
? mBoundItem.state().asHsv() : null;
if (initialColor != null) {
colorPicker.setColor(Color.HSVToColor(initialColor));
}
new AlertDialog.Builder(contentView.getContext())
.setView(contentView)
.setNegativeButton(R.string.close, null)
.show();
}
}
public static class MjpegVideoViewHolder extends ViewHolder {
private final ImageView mImageView;
private MjpegStreamer mStreamer;
MjpegVideoViewHolder(LayoutInflater inflater, ViewGroup parent,
Connection conn, ColorMapper colorMapper) {
super(inflater, parent, R.layout.widgetlist_videomjpegitem, conn, colorMapper);
mImageView = itemView.findViewById(R.id.mjpegimage);
}
@Override
public void bind(Widget widget) {
mStreamer = new MjpegStreamer(mImageView, mConnection, widget.url());
}
@Override
public void start() {
if (mStreamer != null) {
mStreamer.start();
}
}
@Override
public void stop() {
if (mStreamer != null) {
mStreamer.stop();
}
}
}
public static class WidgetItemDecoration extends DividerItemDecoration {
public WidgetItemDecoration(Context context) {
super(context);
}
@Override
protected boolean suppressDividerForChild(View child, RecyclerView parent) {
if (super.suppressDividerForChild(child, parent)) {
return true;
}
int position = parent.getChildAdapterPosition(child);
if (position == RecyclerView.NO_POSITION) {
return false;
}
// hide dividers before and after frame widgets
if (parent.getAdapter().getItemViewType(position) == TYPE_FRAME) {
return true;
}
if (position < parent.getAdapter().getItemCount() - 1) {
if (parent.getAdapter().getItemViewType(position + 1) == TYPE_FRAME) {
return true;
}
}
return false;
}
}
@VisibleForTesting
public static class ColorMapper {
private final Map<String, Integer> mColorMap = new HashMap<>();
ColorMapper(Context context) {
String[] colorNames = context.getResources().getStringArray(R.array.valueColorNames);
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(R.attr.valueColors, tv, false);
TypedArray ta = context.getResources().obtainTypedArray(tv.data);
for (int i = 0; i < ta.length() && i < colorNames.length; i++) {
mColorMap.put(colorNames[i], ta.getColor(i, 0));
}
ta.recycle();
}
public Integer mapColor(String colorName) {
if (colorName == null) {
return null;
}
if (colorName.startsWith("
try {
return Color.parseColor(colorName);
} catch (IllegalArgumentException e) {
return null;
}
} else {
return mColorMap.get(colorName);
}
}
}
} |
package org.alex.accesodatos.gui.tabs;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import org.alex.accesodatos.beans.LabelPropio;
import org.alex.accesodatos.beans.TextPropio;
import org.alex.accesodatos.beans.tablas.TablaClientes;
import org.alex.accesodatos.gui.JConfirmacion;
import org.alex.accesodatos.hibernate.Clientes;
import org.alex.accesodatos.util.Constantes;
import org.alex.accesodatos.util.HibernateUtil;
import org.alex.libs.RestrictedSimple;
import org.alex.libs.Util;
import org.freixas.jcalendar.JCalendarCombo;
/**
* JPanel con los componentes necesarios para guardar, editar, borrar y buscar
* clientes.
*
* @author Alex Gracia
*
*/
public class TabClientes extends JPanel {
// Variables
private static final long serialVersionUID = 1L;
private boolean esNuevo = true;
// Variables graficas
private TextPropio tfNombre, tfDni, tfTelefono, tfDireccion, tfApellidos;
private JCalendarCombo calendarNacimiento, calendarCarnet;
private TablaClientes tablaCliente;
/**
* Constructor que prepara el interfaz.
*
* @param tabbedPane
*/
public TabClientes(JTabbedPane tabbedPane) {
byte i = 0;
tabbedPane.addTab(Constantes.TEXTO_CLIENTES[i++], this);
setLayout(null);
JLabel lblNombre = new JLabel(Constantes.TEXTO_CLIENTES[i++]);
lblNombre.setFont(Constantes.FUENTE_NEGRITA);
lblNombre.setBounds(11, 24, 99, 14);
add(lblNombre);
LabelPropio lblApellidos = new LabelPropio(
Constantes.TEXTO_CLIENTES[i++]);
lblApellidos.setBounds(11, 70, 99, 20);
add(lblApellidos);
JLabel lblDni = new JLabel(Constantes.TEXTO_CLIENTES[i++]);
lblDni.setFont(Constantes.FUENTE_NEGRITA);
lblDni.setBounds(11, 125, 99, 14);
add(lblDni);
LabelPropio lblTelefono = new LabelPropio(
Constantes.TEXTO_CLIENTES[i++]);
lblTelefono.setBounds(11, 174, 99, 14);
add(lblTelefono);
LabelPropio lblNacimiento = new LabelPropio(
Constantes.TEXTO_CLIENTES[i++]);
lblNacimiento.setBounds(11, 223, 135, 14);
add(lblNacimiento);
LabelPropio lblCarnet = new LabelPropio(Constantes.TEXTO_CLIENTES[i++]);
lblCarnet.setBounds(11, 267, 135, 14);
add(lblCarnet);
LabelPropio lblDireccion = new LabelPropio(Constantes.TEXTO_CLIENTES[i]);
lblDireccion.setBounds(11, 313, 99, 14);
add(lblDireccion);
tfNombre = new TextPropio();
RestrictedSimple.soloTextoConLimite(tfNombre, 50);
tfNombre.setBounds(181, 18, 120, 26);
add(tfNombre);
tfNombre.setColumns(10);
tfApellidos = new TextPropio();
RestrictedSimple.soloTextoConLimite(tfApellidos, 100);
tfApellidos.setBounds(181, 65, 120, 26);
add(tfApellidos);
tfDni = new TextPropio();
RestrictedSimple.setLimite(tfDni, 9);
tfDni.setBounds(181, 116, 120, 26);
add(tfDni);
tfDni.setColumns(10);
tfTelefono = new TextPropio();
RestrictedSimple.soloNumeros(tfTelefono);
tfTelefono.setBounds(181, 164, 120, 26);
add(tfTelefono);
tfTelefono.setColumns(10);
calendarNacimiento = new JCalendarCombo();
calendarNacimiento.setBounds(181, 213, 120, 26);
add(calendarNacimiento);
calendarCarnet = new JCalendarCombo();
calendarCarnet.setBounds(181, 263, 120, 26);
add(calendarCarnet);
tfDireccion = new TextPropio();
RestrictedSimple.setLimite(tfDireccion, 200);
tfDireccion.setBounds(181, 307, 120, 26);
add(tfDireccion);
tfDireccion.setColumns(10);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(355, 18, 625, 271);
add(scrollPane);
tablaCliente = new TablaClientes(tfNombre, tfApellidos, tfDni,
tfTelefono, calendarNacimiento, calendarCarnet, tfDireccion);
scrollPane.setViewportView(tablaCliente);
}
public void mBuscarCliente(String filtro) {
if (filtro.equals(""))
tablaCliente.listar();
else
tablaCliente.listar(filtro);
}
public boolean mEliminar() {
if (!clienteSeleccionado() || !new JConfirmacion("Borrar").isAceptar())
return false;
Clientes cliente = tablaCliente.getClienteSeleccionado();
if (!HibernateUtil.setData("borrar", cliente)) {
int idCliente = cliente.getIdClientes();
List<?> queryPolizas = HibernateUtil.getQuery(
"select p.idPolizas from Polizas p where p.clientes.idClientes = "
+ idCliente).list();
List<?> querySiniestros = HibernateUtil.getQuery(
"select s.idSiniestros from Siniestros s where s.clientes.idClientes = "
+ idCliente).list();
Util.setMensajeError("Debe borrar antes la/s pliza/s n "
+ queryPolizas + "," + "\n y el/los siniestro/s n "
+ querySiniestros + ".");
}
tablaCliente.listar();
mVaciarCliente();
return true;
}
public boolean mGuardar() {
// Variables
String nombre = tfNombre.getText();
String dni = tfDni.getText();
if (nombre.equals("") || dni.equals("")) {
Util.setMensajeInformacion("Rellene los campos obligatorios (*)");
return false;
}
Clientes cliente;
if (esNuevo) {
String dniSQL = (String) HibernateUtil
.getCurrentSession()
.createQuery(
"select c.dni from Clientes c where c.dni = '"
+ dni + "'").uniqueResult();
if (dni.equals(dniSQL)) {
Util.setMensajeInformacion("DNI ya existente, cmbielo");
tfDni.setText("");
return false;
}
cliente = new Clientes();
} else
cliente = tablaCliente.getClienteSeleccionado();
cliente.setNombre(nombre);
cliente.setApellidos(tfApellidos.getText());
cliente.setDni(dni);
String telefono = tfTelefono.getText();
if (telefono.equals(""))
cliente.setTelefono(0);
else
cliente.setTelefono(Integer.parseInt(telefono));
cliente.setFechaNacimiento(calendarNacimiento.getDate());
cliente.setFechaCarnet(calendarCarnet.getDate());
cliente.setDireccion(tfDireccion.getText());
if (esNuevo)
HibernateUtil.setData("guardar", cliente);
else {
HibernateUtil.setData("actualizar", cliente);
esNuevo = true;
tfNombre.setEnabled(true);
}
tablaCliente.listar();
mVaciarCliente();
return true;
}
public boolean mEditar() {
if (!clienteSeleccionado())
return false;
tfNombre.setEnabled(false);
esNuevo = false;
return true;
}
public void mCancelar() {
esNuevo = true;
mVaciarCliente();
tfNombre.setEnabled(true);
}
private void mVaciarCliente() {
tfNombre.setText("");
tfApellidos.setText("");
tfDni.setText("");
tfTelefono.setText("");
Date date = Calendar.getInstance().getTime();
calendarNacimiento.setDate(date);
calendarCarnet.setDate(date);
tfDireccion.setText("");
}
public TablaClientes getTablaClientes() {
return tablaCliente;
}
private boolean clienteSeleccionado() {
if (tablaCliente.getClienteSeleccionado() == null) {
Util.setMensajeInformacion("Seleccione una fila.");
return false;
}
return true;
}
} |
package com.sims.topaz.adapter;
import java.sql.Date;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.util.LruCache;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sims.topaz.R;
import com.sims.topaz.network.modele.Message;
import com.sims.topaz.utils.CameraUtils;
import com.sims.topaz.utils.MyTypefaceSingleton;
import com.sims.topaz.utils.SimsContext;
public class UserMessageAdapter extends ArrayAdapter<Message> {
private int count = 0;
private byte[] image;
private Bitmap mImageBitmap = null;
public UserMessageAdapter(Context mDelegate, int resource, List<Message> messagesList,byte[] mImage) {
super(mDelegate, resource, messagesList);
this.image = mImage;
count = messagesList.size();
}
@Override
public int getCount() {
return count;
}
@SuppressWarnings("deprecation")
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
ViewHolder holder = null;
if(view == null){
holder=new ViewHolder();
LayoutInflater inflater =
(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.fragment_message_item, null);
holder.mUserName = (TextView) view.findViewById(R.id.message_item_person_name);
holder.mUserName.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace());
holder.mUserMessage = (TextView) view.findViewById(R.id.message_item_text);
holder.mUserMessage.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace());
holder.mMessageDate = (TextView) view.findViewById(R.id.message_item_time);
holder.mMessageDate.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace());
holder.mUserImage = (ImageView) view.findViewById(R.id.message_item_image);
if(image!=null){
if(mImageBitmap==null){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = CameraUtils.calculateInSampleSize(options, 32, 32);
mImageBitmap = BitmapFactory.decodeByteArray(image, 0, image.length,options);
}
holder.mUserImage.setBackgroundDrawable(new BitmapDrawable(SimsContext.getContext().getResources(),mImageBitmap));
}
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
if(position >= 0){
if(getItem(position)!=null){
Message m = getItem(position);
holder.mUserName.setText(m.getUserName());
holder.mUserMessage.setText(m.getText());
holder.mMessageDate.setText(DateFormat.format
(getContext().getString(R.string.date_format),
new Date( m.getTimestamp()) ) );
}
}
return view;
}
class ViewHolder {
TextView mUserName;
TextView mUserMessage;
TextView mMessageDate;
ImageView mUserImage;
}
} |
package com.peel.react;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class TcpSocketsModule implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<NativeModule>();
modules.add(new TcpSockets(reactContext));
return modules;
}
// Deprecated RN 0.47
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(
ReactApplicationContext reactContext) {
return Collections.emptyList();
}
} |
package org.videolan.jvlc;
import org.videolan.jvlc.internal.LibVlc.libvlc_exception_t;
public class Audio
{
private final JVLC jvlc;
/**
* Constant for left channel audio
*/
public static final int LEFT_CHANNEL = 3;
/**
* Constant for right channel audio
*/
public static final int RIGHT_CHANNEL = 4;
/**
* Constant for reverse channel audio
*/
public static final int REVERSE_CHANNEL = 2;
/**
* Constant for stereo channel audio
*/
public static final int STEREO_CHANNEL = 1;
/**
* Constant for dolby channel audio
*/
public final int DOLBY_CHANNEL = 5;
public Audio(JVLC jvlc)
{
this.jvlc = jvlc;
}
public int getTrack(MediaPlayer mediaInstance)
{
libvlc_exception_t exception = new libvlc_exception_t();
return jvlc.getLibvlc().libvlc_audio_get_track(mediaInstance.getInstance(), exception);
}
public int getTrackCount(MediaPlayer mediaInstance)
{
libvlc_exception_t exception = new libvlc_exception_t();
return jvlc.getLibvlc().libvlc_audio_get_track_count(mediaInstance.getInstance(), exception);
}
public void setTrack(MediaPlayer mediaInstance, int track)
{
libvlc_exception_t exception = new libvlc_exception_t();
jvlc.getLibvlc().libvlc_audio_set_track(mediaInstance.getInstance(), track, exception);
}
public int getChannel()
{
libvlc_exception_t exception = new libvlc_exception_t();
return jvlc.getLibvlc().libvlc_audio_get_channel(jvlc.getInstance(), exception);
}
public void setChannel(int channel)
{
libvlc_exception_t exception = new libvlc_exception_t();
jvlc.getLibvlc().libvlc_audio_set_channel(jvlc.getInstance(), channel, exception);
}
public boolean getMute()
{
libvlc_exception_t exception = new libvlc_exception_t();
return jvlc.getLibvlc().libvlc_audio_get_mute(jvlc.getInstance(), exception) == 1 ? true : false;
}
public void setMute(boolean value)
{
libvlc_exception_t exception = new libvlc_exception_t();
jvlc.getLibvlc().libvlc_audio_set_mute(jvlc.getInstance(), value ? 1 : 0, exception);
}
public void toggleMute()
{
libvlc_exception_t exception = new libvlc_exception_t();
jvlc.getLibvlc().libvlc_audio_toggle_mute(jvlc.getInstance(), exception);
}
public int getVolume()
{
libvlc_exception_t exception = new libvlc_exception_t();
return jvlc.getLibvlc().libvlc_audio_get_volume(jvlc.getInstance(), exception);
}
public void setVolume(int volume)
{
libvlc_exception_t exception = new libvlc_exception_t();
jvlc.getLibvlc().libvlc_audio_set_volume(jvlc.getInstance(), volume, exception);
}
} |
package com.allyants.boardview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.Scroller;
import java.util.ArrayList;
public class BoardView extends FrameLayout {
private static final float GLOBAL_SCALE = 0.6f;
private static final int SCROLL_ANIMATION_DURATION = 325;
private boolean mCellIsMobile = false;
private BitmapDrawable mHoverCell;
private Rect mHoverCellCurrentBounds;
private Rect mHoverCellOriginalBounds;
private HorizontalScrollView mRootLayout;
private LinearLayout mParentLayout;
private int originalPosition = -1;
private int originalItemPosition = -1;
private DragColumnStartCallback mDragColumnStartCallback = new DragColumnStartCallback() {
@Override
public void startDrag(View itemView, int originalPosition) {
}
@Override
public void changedPosition(View itemView, int originalPosition, int newPosition) {
}
@Override
public void endDrag(View itemView, int originalPosition, int newPosition) {
}
};
private DragItemStartCallback mDragItemStartCallback = new DragItemStartCallback() {
@Override
public void startDrag(View itemView, int originalPosition,int originalColumn) {
}
@Override
public void changedPosition(View itemView, int originalPosition,int originalColumn, int newPosition, int newColumn) {
}
@Override
public void endDrag(View itemView, int originalPosition,int originalColumn, int newPosition, int newColumn) {
}
};
public boolean constWidth = true;
private final int LINE_THICKNESS = 15;
private boolean can_scroll = false;
private int mLastEventX = -1;
private int mLastEventY = -1;
private Scroller mScroller;
public interface DragColumnStartCallback{
void startDrag(View itemView, int originalPosition);
void changedPosition(View itemView, int originalPosition, int newPosition);
void endDrag(View itemView, int originalPosition, int newPosition);
}
public interface DragItemStartCallback{
void startDrag(View itemView, int originalPosition,int originalColumn);
void changedPosition(View itemView, int originalPosition,int originalColumn, int newPosition, int newColumn);
void endDrag(View itemView, int originalPosition,int originalColumn, int newPosition, int newColumn);
}
public void setOnDragColumnListener(DragColumnStartCallback dragStartCallback){
mDragColumnStartCallback = dragStartCallback;
}
public void setOnDragItemListener(DragItemStartCallback dragStartCallback){
mDragItemStartCallback = dragStartCallback;
}
long last_swap = System.currentTimeMillis();
long last_swap_item = System.currentTimeMillis();
final long ANIM_TIME = 300;
long mDelaySwap = 400;
long mDelaySwapItem = 400;
private int mLastSwap = -1;
private int mDownY = -1;
private int mDownX = -1;
private boolean mSwapped = false;
private boolean canDragHorizontal = true;
private boolean canDragVertical = true;
private boolean mCellSubIsMobile = false;
private int mTotalOffsetX = 0;
private int mTotalOffsetY = 0;
private View mobileView;
public BoardView(Context context) {
super(context);
}
public BoardView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BoardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mRootLayout = new HorizontalScrollView(getContext());
mRootLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
mParentLayout = new LinearLayout(getContext());
mParentLayout.setOrientation(LinearLayout.HORIZONTAL);
mScroller = new Scroller(mRootLayout.getContext(), new DecelerateInterpolator(1.2f));
mParentLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
mRootLayout.addView(mParentLayout);
addView(mRootLayout);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if(mHoverCell != null){
mHoverCell.draw(canvas);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean colValue = handleColumnDragEvent(event);
return colValue || super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean colValue = handleColumnDragEvent(event);
return colValue || super.onTouchEvent(event);
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
public void scrollToColumn(int column,boolean animate){
if(column >= 0) {
View childView = mParentLayout.getChildAt(column);
int newX = childView.getLeft() - (int) (((getMeasuredWidth() - childView.getMeasuredWidth()) / 2));
if (animate) {
mRootLayout.smoothScrollTo(newX, 0);
} else {
mRootLayout.scrollTo(newX, 0);
}
}
}
public boolean handleColumnDragEvent(MotionEvent event){
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mDownX = (int)event.getX();
mDownY = (int)event.getY();
break;
case MotionEvent.ACTION_MOVE:
if(mDownY == -1){
mDownY = (int)event.getY();
}
if(mDownX == -1){
mDownX = (int)event.getX();
}
mLastEventX = (int) event.getX();
mLastEventY = (int) event.getY();
int deltaX = mLastEventX - mDownX;
int deltaY = mLastEventY - mDownY;
if(mCellSubIsMobile){
int offsetX = 0;
if(canDragHorizontal){
offsetX = deltaX;
}
int offsetY = mHoverCellOriginalBounds.top;
if(canDragVertical){
offsetY = mHoverCellOriginalBounds.top + deltaY + mTotalOffsetY;
}
mHoverCellCurrentBounds.offsetTo(offsetX,
offsetY);
mHoverCell.setBounds(rotatedBounds(mHoverCellCurrentBounds,0.0523599f));
invalidate();
handleItemSwitchHorizontal();
return true;
}else if (mCellIsMobile) {
int offsetX = 0;
if(canDragHorizontal){
offsetX = deltaX;
}
int offsetY = mHoverCellOriginalBounds.top;
if(canDragVertical){
offsetY = mHoverCellOriginalBounds.top + deltaY + mTotalOffsetY;
}
mHoverCellCurrentBounds.offsetTo(offsetX,
offsetY);
mHoverCell.setBounds(rotatedBounds(mHoverCellCurrentBounds,0.0523599f));
invalidate();
handleColumnSwitchHorizontal();
return true;
}
break;
case MotionEvent.ACTION_UP:
touchEventsCancelled();
break;
case MotionEvent.ACTION_CANCEL:
touchEventsCancelled();
break;
case MotionEvent.ACTION_POINTER_UP:
/* If a multitouch event took place and the original touch dictating
* the movement of the hover cell has ended, then the dragging event
* ends and the hover cell is animated to its corresponding position
* in the listview. */
// pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
// MotionEvent.ACTION_POINTER_INDEX_SHIFT;
// final int pointerId = event.getPointerId(pointerIndex);
// if (pointerId == mActivePointerId) {
break;
default:
break;
}
return false;
}
@Override
public void computeScroll() {
if (!mScroller.isFinished() && mScroller.computeScrollOffset()) {
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (getScrollX() != x || getScrollY() != y) {
scrollTo(x, y);
}
ViewCompat.postInvalidateOnAnimation(this);
} else {
super.computeScroll();
}
}
private void handleItemSwitchHorizontal(){
int itemPos = ((LinearLayout)(mobileView.getParent())).indexOfChild(mobileView) - 1;
View aboveView = ((LinearLayout)(mobileView.getParent())).getChildAt(itemPos - 1);
if(itemPos == 0){
aboveView = null;
}
View belowView = ((LinearLayout)(mobileView.getParent())).getChildAt(itemPos + 1);
//swapping above
if(aboveView != null){
int[] locationAbove = new int[2];
aboveView.getLocationOnScreen(locationAbove);
if(locationAbove[1]-aboveView.getHeight() > mLastEventY){
switchItemFromPosition(-1,mobileView);
}
}
//swapping below
if(belowView != null){
int[] locationBelow = new int[2];
belowView.getLocationOnScreen(locationBelow);
if(locationBelow[1]-belowView.getHeight() < mLastEventY){
switchItemFromPosition(1,mobileView);
}
}
int columnPos = mParentLayout.indexOfChild((View)(mobileView.getParent().getParent()));
View leftView = mParentLayout.getChildAt(columnPos - 1);
View currentView = mParentLayout.getChildAt(columnPos);
View rightView = mParentLayout.getChildAt(columnPos + 1);
if(leftView != null){
int[] locationLeft = new int[2];
leftView.getLocationOnScreen(locationLeft);
if (locationLeft[0] + leftView.getWidth() > mLastEventX) {
int pos = ((LinearLayout)mobileView.getParent()).indexOfChild(mobileView);
if(last_swap_item <= System.currentTimeMillis() - mDelaySwapItem) {
last_swap_item = System.currentTimeMillis();
if(((LinearLayout)mobileView.getParent()) != null) {
((LinearLayout) mobileView.getParent()).removeViewAt(pos);
((LinearLayout)((ViewGroup)leftView).getChildAt(0)).addView(mobileView);
scrollToColumn(columnPos-1,true);
int newItemPos = ((LinearLayout)((ViewGroup)rightView).getChildAt(0)).indexOfChild(mobileView)-1;
int newColumnPos = columnPos-1;
mDragItemStartCallback.changedPosition(mobileView,originalItemPosition,originalPosition,newItemPos,newColumnPos);
}
}
}
}
if(rightView != null){
int[] locationRight = new int[2];
rightView.getLocationOnScreen(locationRight);
if (locationRight[0] < mLastEventX) {
int pos = ((LinearLayout)mobileView.getParent()).indexOfChild(mobileView);
if(last_swap_item <= System.currentTimeMillis() - mDelaySwapItem) {
last_swap_item = System.currentTimeMillis();
if(((LinearLayout)mobileView.getParent()) != null) {
((LinearLayout) mobileView.getParent()).removeViewAt(pos);
((LinearLayout)((ViewGroup)rightView).getChildAt(0)).addView(mobileView);
scrollToColumn(columnPos+1,true);
int newItemPos = ((LinearLayout)((ViewGroup)rightView).getChildAt(0)).indexOfChild(mobileView)-1;
int newColumnPos = columnPos+1;
mDragItemStartCallback.changedPosition(mobileView,originalItemPosition,originalPosition,newItemPos,newColumnPos);
}
}
}
}
}
private void switchItemFromPosition(int change,View view){
LinearLayout parentLayout = (LinearLayout)(view.getParent());
int columnPos = parentLayout.indexOfChild(view);
if(columnPos+change >= 0 && columnPos+change < parentLayout.getChildCount()) {
parentLayout.removeView(view);
parentLayout.addView(view, columnPos + change);
if(mDragItemStartCallback != null){
int newPos = parentLayout.indexOfChild(view);
last_swap = System.currentTimeMillis();
mLastSwap = newPos;
int newColumnPos = mParentLayout.indexOfChild((View)(mobileView.getParent().getParent()))-1;
mDragItemStartCallback.changedPosition(view,originalItemPosition,originalPosition,newPos,newColumnPos);
}
}
}
private void handleColumnSwitchHorizontal(){
if(can_scroll && last_swap <= System.currentTimeMillis()-mDelaySwap) {
int columnPos = mParentLayout.indexOfChild(mobileView);
View leftView = mParentLayout.getChildAt(columnPos - 1);
View rightView = mParentLayout.getChildAt(columnPos + 1);
int[] locationRight = new int[2];
if (rightView != null) {
rightView.getLocationOnScreen(locationRight);
if (locationRight[0] < mLastEventX) {
//Scroll to the right
switchColumnFromPosition(1,mobileView);
if (locationRight[0] + (rightView.getWidth() / 2) < mLastEventX) {
}
}
}
int[] locationLeft = new int[2];
if (leftView != null) {
leftView.getLocationOnScreen(locationLeft);
if (locationLeft[0] + leftView.getWidth() > mLastEventX) {
//Scroll to the right
switchColumnFromPosition(-1,mobileView);
//mRootLayout.scrollBy(-1 * 2, 0);
if (locationLeft[0] + (leftView.getWidth() / 2) > mLastEventX) {
}
}
}
}
}
private void switchColumnFromPosition(int change,View view){
int columnPos = mParentLayout.indexOfChild(view);
if(columnPos+change >= 0 && last_swap <= System.currentTimeMillis()-mDelaySwap) {
mParentLayout.removeView(view);
mParentLayout.addView(view, columnPos + change);
if(mDragColumnStartCallback != null){
int newPos = mParentLayout.indexOfChild(view);
last_swap = System.currentTimeMillis();
mLastSwap = newPos;
Handler handlerTimer = new Handler();
handlerTimer.postDelayed(new Runnable(){
public void run() {
scrollToColumn(mLastSwap,true);
}}, 0);
mDragColumnStartCallback.changedPosition(((LinearLayout)view).getChildAt(0),originalPosition,newPos);
}
}
}
private void touchEventsCancelled() {
if(mCellSubIsMobile){
mobileView.setVisibility(VISIBLE);
mHoverCell = null;
invalidate();
}else if(mCellIsMobile){
for (int i = 0; i < mParentLayout.getChildCount(); i++) {
BoardItem parentView = (BoardItem) mParentLayout.getChildAt(i);//Gets the parent layout
View childView = ((LinearLayout) parentView).getChildAt(0);
scaleView(childView, parentView, GLOBAL_SCALE, 1f);
}
mobileView.setVisibility(VISIBLE);
mHoverCell = null;
invalidate();
if(mDragColumnStartCallback != null){
int columnPos = mParentLayout.indexOfChild(mobileView);
scrollToColumn(columnPos,true);
mDragColumnStartCallback.endDrag(((LinearLayout)mobileView).getChildAt(0),originalPosition,columnPos);
}
if(mDragItemStartCallback != null){
int columnPos = mParentLayout.indexOfChild(mobileView);
//Subtract one because the first view is the header
int pos = ((LinearLayout)mobileView.getParent()).indexOfChild(mobileView)-1;
mDragItemStartCallback.endDrag(mobileView,originalPosition,originalItemPosition,pos,columnPos);
}
}
mDownX = -1;
mDownY = -1;
mCellSubIsMobile = false;
mCellIsMobile = false;
}
Handler handler = new Handler();
public void scaleView(final View v, final BoardItem parent, final float startScale, final float endScale) {
final Animation anim = new ScaleAnimation(
startScale, endScale, // Start and end values for the X axis scaling
startScale, endScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF,0f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 0f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setFillBefore(false);
anim.setFillEnabled(true);
anim.setDuration(ANIM_TIME);
v.startAnimation(anim);
final long startTime = System.currentTimeMillis();
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
handler.post(createRunnable(parent,startTime,startScale,endScale));
can_scroll = false;
}
@Override
public void onAnimationEnd(Animation animation) {
parent.scale = endScale;
scrollToColumn(mLastSwap,true);
parent.requestLayout();
parent.invalidate();
can_scroll = true;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
private Runnable createRunnable(final BoardItem parent, final long startTime, final float startScale, final float endScale){
Runnable runnable = new Runnable() {
@Override
public void run() {
long time = System.currentTimeMillis()-startTime;
float scale_time = time/(float)ANIM_TIME;
if(scale_time > 1){
scale_time = 1;
}
scrollToColumn(mLastSwap,true);
parent.scale = startScale + (endScale - startScale)*scale_time;
parent.requestLayout();
parent.invalidate();
if(scale_time != 1) {
handler.postDelayed(this,10);
}
}
};
return runnable;
}
public void addColumnList(@Nullable View header, ArrayList<View> items, @Nullable View footer){
final BoardItem parent_layout = new BoardItem(getContext());
final LinearLayout layout = new LinearLayout(getContext());
layout.setOrientation(LinearLayout.VERTICAL);
parent_layout.setOrientation(LinearLayout.VERTICAL);
if(constWidth) {
int margin = calculatePixelFromDensity(5);
LayoutParams params = new LayoutParams(calculatePixelFromDensity(240), LayoutParams.WRAP_CONTENT);
params.setMargins(margin,margin,margin,margin);
layout.setLayoutParams(params);
parent_layout.setLayoutParams(params);
}else {
int margin = calculatePixelFromDensity(5);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(margin,margin,margin,margin);
layout.setLayoutParams(params);
parent_layout.setLayoutParams(params);
}
parent_layout.addView(layout);
if(header != null){
layout.addView(header);
header.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int pos = mParentLayout.indexOfChild(parent_layout);
scrollToColumn(pos,true);
}
});
header.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mDragColumnStartCallback == null) {
return false;
}
originalPosition = mParentLayout.indexOfChild(parent_layout);
mDragColumnStartCallback.startDrag(layout,originalPosition);
mLastSwap = originalPosition;
for(int i = 0;i < mParentLayout.getChildCount();i++){
BoardItem parentView = (BoardItem)mParentLayout.getChildAt(i);//Gets the parent layout
View childView = ((LinearLayout)parentView).getChildAt(0);
scrollToColumn(originalPosition,true);
scaleView(childView,parentView,1f,GLOBAL_SCALE);
}
scrollToColumn(originalPosition,false);
mCellIsMobile = true;
mobileView = (View)(parent_layout);
mHoverCell = getAndAddHoverView(mobileView,GLOBAL_SCALE);
mobileView.setVisibility(INVISIBLE);
return false;
}
});
}
if(items.size() > 0){
for(int i = 0;i < items.size();i++){
final View view = items.get(i);
layout.addView(view);
view.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mDragItemStartCallback == null) {
return false;
}
originalPosition = mParentLayout.indexOfChild(parent_layout);
originalItemPosition = ((LinearLayout)view.getParent()).indexOfChild(view);
mDragItemStartCallback.startDrag(layout,originalPosition,originalItemPosition);
mCellSubIsMobile = true;
mobileView = (View)(view);
mHoverCell = getAndAddHoverView(mobileView,1);
mobileView.setVisibility(INVISIBLE);
return false;
}
});
}
}
if(footer != null) {
layout.addView(footer);
}
mParentLayout.addView(parent_layout);
}
private int calculatePixelFromDensity(float dp){
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
float fpixels = metrics.density * dp;
int pixels = (int) (fpixels + 0.5f);
return pixels;
}
private BitmapDrawable getAndAddHoverView(View v, float scale){
int w = v.getWidth();
int h = v.getHeight();
int top = v.getTop();
int left = v.getLeft();
Bitmap b = getBitmapWithBorder(v,scale);
BitmapDrawable drawable = new BitmapDrawable(getResources(),b);
mHoverCellOriginalBounds = new Rect(left,top,left+w,top+h);
mHoverCellCurrentBounds = new Rect(mHoverCellOriginalBounds);
drawable.setBounds(mHoverCellCurrentBounds);
return drawable;
}
private Bitmap getBitmapWithBorder(View v, float scale) {
Bitmap bitmap = getBitmapFromView(v,0);
Bitmap b = getBitmapFromView(v,1);
Canvas can = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAlpha(150);
can.scale(scale,scale,mDownX,mDownY);
can.rotate(3);
can.drawBitmap(b,0,0,paint);
return bitmap;
}
private Bitmap getBitmapFromView(View v, float scale){
double radians = 0.0523599f;
double s = Math.abs(Math.sin(radians));
double c = Math.abs(Math.cos(radians));
int width = (int)(v.getHeight()*s + v.getWidth()*c);
int height = (int)(v.getWidth()*s + v.getHeight()*c);
Bitmap bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.scale(scale,scale);
v.draw(canvas);
return bitmap;
}
private Rect rotatedBounds(Rect tmp,double radians){
double s = Math.abs(Math.sin(radians));
double c = Math.abs(Math.cos(radians));
int width = (int)(tmp.height()*s + tmp.width()*c);
int height = (int)(tmp.width()*s + tmp.height()*c);
return new Rect(tmp.left,tmp.top,tmp.left+width,tmp.top+height);
}
} |
package com.ayuget.redface.ui;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.ayuget.redface.R;
import com.ayuget.redface.account.UserManager;
import com.ayuget.redface.data.DataService;
import com.ayuget.redface.data.api.MDEndpoints;
import com.ayuget.redface.data.api.MDService;
import com.ayuget.redface.data.api.model.Response;
import com.ayuget.redface.data.api.model.Smiley;
import com.ayuget.redface.data.api.model.Topic;
import com.ayuget.redface.data.api.model.User;
import com.ayuget.redface.data.rx.EndlessObserver;
import com.ayuget.redface.data.rx.SubscriptionHandler;
import com.ayuget.redface.data.state.ResponseStore;
import com.ayuget.redface.network.HTTPClientProvider;
import com.ayuget.redface.ui.event.SmileySelectedEvent;
import com.ayuget.redface.ui.misc.BindableAdapter;
import com.ayuget.redface.ui.misc.UiUtils;
import com.ayuget.redface.ui.template.SmileysTemplate;
import com.ayuget.redface.ui.view.SmileySelectorView;
import com.ayuget.redface.util.UserUtils;
import com.google.common.base.Optional;
import com.squareup.otto.Subscribe;
import com.squareup.picasso.Picasso;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import butterknife.InjectView;
import butterknife.OnClick;
public class ReplyActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener {
private static final String LOG_TAG = ReplyActivity.class.getSimpleName();
private static final String ARG_TOPIC = "topic";
/**
* @todo fix this, ugly...
*/
private static final List<Smiley> DEFAULT_SMILEYS = Arrays.asList(
Smiley.make(":O", "http://forum-images.hardware.fr/icones/redface.gif"),
Smiley.make(":)", "http://forum-images.hardware.fr/icones/smile.gif"),
Smiley.make(":(", "http://forum-images.hardware.fr/icones/frown.gif"),
Smiley.make(":D", "http://forum-images.hardware.fr/icones/biggrin.gif"),
Smiley.make(";)", "http://forum-images.hardware.fr/icones/wink.gif"),
Smiley.make(":ouch:", "http://forum-images.hardware.fr/icones/smilies/ouch.gif"),
Smiley.make(":??:", "http://forum-images.hardware.fr/icones/confused.gif"),
Smiley.make(":p", "http://forum-images.hardware.fr/icones/tongue.gif"),
Smiley.make(":pfff:", "http://forum-images.hardware.fr/icones/smilies/pfff.gif"),
Smiley.make(":ange:", "http://forum-images.hardware.fr/icones/smilies/ange.gif"),
Smiley.make(":non:", "http://forum-images.hardware.fr/icones/smilies/non.gif"),
Smiley.make(":bounce:", "http://forum-images.hardware.fr/icones/smilies/bounce.gif"),
Smiley.make(":fou:", "http://forum-images.hardware.fr/icones/smilies/fou.gif"),
Smiley.make(":jap:", "http://forum-images.hardware.fr/icones/smilies/jap.gif"),
Smiley.make(":lol:", "http://forum-images.hardware.fr/icones/smilies/lol.gif"),
Smiley.make(":wahoo:", "http://forum-images.hardware.fr/icones/smilies/wahoo.gif"),
Smiley.make(":kaola:", "http://forum-images.hardware.fr/icones/smilies/kaola.gif"),
Smiley.make(":love:", "http://forum-images.hardware.fr/icones/smilies/love.gif"),
Smiley.make(":heink:", "http://forum-images.hardware.fr/icones/smilies/heink.gif"),
Smiley.make(":cry:", "http://forum-images.hardware.fr/icones/smilies/cry.gif"),
Smiley.make(":whistle:", "http://forum-images.hardware.fr/icones/smilies/whistle.gif"),
Smiley.make(":sol:", "http://forum-images.hardware.fr/icones/smilies/sol.gif"),
Smiley.make(":pt1cable:", "http://forum-images.hardware.fr/icones/smilies/pt1cable.gif"),
Smiley.make(":sleep:", "http://forum-images.hardware.fr/icones/smilies/sleep.gif"),
Smiley.make(":sweat:", "http://forum-images.hardware.fr/icones/smilies/sweat.gif"),
Smiley.make(":hello:", "http://forum-images.hardware.fr/icones/smilies/hello.gif"),
Smiley.make(":na:", "http://forum-images.hardware.fr/icones/smilies/na.gif"),
Smiley.make(":sarcastic:", "http://forum-images.hardware.fr/icones/smilies/sarcastic.gif")
);
/**
* The active pointer is the one currently use to move the smiley view
*/
private int activePointerId = UIConstants.INVALID_POINTER_ID;
/**
* Top offset (margin) in pixels for the smiley selector. Marks its default position on the
* y-axis.
*/
private int smileySelectorTopOffset;
/**
* Reply window max height in pixels
*/
private int replyWindowMaxHeight;
private int screenHeight;
private float lastTouchY;
private boolean isUpwardMovement;
private int toolbarHeight;
private boolean smileysToolbarAnimationInProgress;
/**
* Main reply window (with user picker, toolbars, ...)
*/
@InjectView(R.id.main_reply_frame)
RelativeLayout mainReplyFrame;
/**
* Primary dialog toolbar, with user selection and send button
*/
@InjectView(R.id.toolbar_reply_actions)
Toolbar actionsToolbar;
/**
* Secondary action toolbar (bold, italic, links, ...)
*/
@InjectView(R.id.toolbar_reply_extra)
Toolbar extrasToolbar;
/**
* Finger draggable view to select smileys
*/
@InjectView(R.id.smiley_selector_view)
View smileysSelector;
/**
* Toolbar to switch between popular / recent / favorite smileys
*/
@InjectView(R.id.smileys_toolbar)
Toolbar smileysToolbar;
/**
* Reply text box
*/
@InjectView(R.id.reply_text)
EditText replyEditText;
/**
* Smiley list
*/
@InjectView(R.id.smileyList)
SmileySelectorView smileyList;
/**
* Root ViewGroup for the reply window
*/
@InjectView(R.id.reply_window_root)
FrameLayout replyWindowRoot;
/**
* Smileys search box
*/
@InjectView(R.id.smileys_search)
SearchView smileysSearch;
@Inject
UserManager userManager;
@Inject
SmileysTemplate smileysTemplate;
@Inject
MDEndpoints mdEndpoints;
@Inject
DataService dataService;
@Inject
HTTPClientProvider httpClientProvider;
@Inject
MDService mdService;
@Inject
ResponseStore responseStore;
private Topic currentTopic;
private String initialReplyContent;
private SubscriptionHandler<User, Response> replySubscriptionHandler = new SubscriptionHandler<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_reply);
Intent intent = getIntent();
if (intent != null) {
currentTopic = intent.getParcelableExtra(ARG_TOPIC);
initialReplyContent = intent.getStringExtra(UIConstants.ARG_REPLY_CONTENT);
if (currentTopic == null) {
throw new IllegalStateException("Current topic is null");
}
if (initialReplyContent != null) {
replyEditText.setText(initialReplyContent);
replyEditText.setSelection(replyEditText.getText().length());
}
}
DisplayMetrics metrics = getResources().getDisplayMetrics();
screenHeight = metrics.heightPixels;
smileySelectorTopOffset = (int) (metrics.heightPixels * 0.75);
replyWindowMaxHeight = (int) (metrics.heightPixels * 0.70);
toolbarHeight = getToolbarHeight();
setupSmileySelector();
actionsToolbar.inflateMenu(R.menu.menu_reply);
actionsToolbar.setOnMenuItemClickListener(this);
setupUserSwitcher(getLayoutInflater(), userManager.getRealUsers());
// Dirty hack to set a maximum height on the reply window frame. Should leave enough room for the smiley
// picker when the soft keyboard is hidden, and hide the smiley picker otherwise. Activity is resized thanks
// to the adjustResize windowSoftInputMode set in the manifest, and the extra bottom toolbar stays visible
// and usable.
// As any hack, this method is probably very buggy...
replyWindowRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
replyWindowRoot.getWindowVisibleDisplayFrame(r);
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mainReplyFrame.getLayoutParams();
boolean keyboardIsOpen = r.height() < replyWindowMaxHeight;
if (keyboardIsOpen) {
if (lp.height != ViewGroup.LayoutParams.MATCH_PARENT) {
lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
mainReplyFrame.setLayoutParams(lp);
}
}
else {
if (lp.height != replyWindowMaxHeight) {
lp.height = replyWindowMaxHeight;
mainReplyFrame.setLayoutParams(lp);
}
}
}
});
styleToolbarButtons(extrasToolbar);
styleToolbarButtons(smileysToolbar);
styleToolbarMenu(actionsToolbar);
styleSmileySearchView();
smileysSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
if (s.trim().length() > 0) {
subscribe(dataService.searchForSmileys(s.trim(), new EndlessObserver<List<Smiley>>() {
@Override
public void onNext(List<Smiley> smileys) {
smileyList.setSmileys(smileys);
}
}));
}
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
// Load default smileys
loadDefaultSmileys();
}
@Override
protected void onPause() {
super.onPause();
if (replyEditText != null) {
if(replyEditText.getText().toString().length() > 0) {
responseStore.storeResponse(userManager.getActiveUser(), currentTopic, replyEditText.getText().toString());
}
else {
responseStore.removeResponse(userManager.getActiveUser(), currentTopic);
}
}
}
@Override
protected void onResume() {
super.onResume();
String storedResponse = responseStore.getResponse(userManager.getActiveUser(), currentTopic);
if (storedResponse != null && replyEditText.getText().length() == 0) {
replyEditText.setText(storedResponse);
replyEditText.setSelection(replyEditText.getText().length());
}
}
/**
* Loads default smileys in the smiley selector
*/
@OnClick(R.id.default_smileys)
protected void loadDefaultSmileys() {
smileyList.setSmileys(DEFAULT_SMILEYS);
}
/**
* Loads recently used smileys in the smiley selector
*/
@OnClick(R.id.recent_smileys)
protected void loadRecentSmileys() {
subscribe(dataService.getRecentlyUsedSmileys(userManager.getActiveUser(), new EndlessObserver<List<Smiley>>() {
@Override
public void onNext(List<Smiley> smileys) {
smileyList.setSmileys(smileys);
}
}));
}
/**
* Loads popular smileys in the smiley selector
*/
@OnClick(R.id.popular_smileys)
protected void loadPopularSmileys() {
subscribe(dataService.getPopularSmileys(new EndlessObserver<List<Smiley>>() {
@Override
public void onNext(List<Smiley> smileys) {
smileyList.setSmileys(smileys);
}
}));
}
/**
* Initializes both the smiley selector
*/
protected void setupSmileySelector() {
smileyList.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int action = MotionEventCompat.getActionMasked(event);
switch (action) {
case MotionEvent.ACTION_DOWN: {
final int pointerIndex = MotionEventCompat.getActionIndex(event);
lastTouchY = MotionEventCompat.getY(event, pointerIndex);
activePointerId = MotionEventCompat.getPointerId(event, 0);
break;
}
case MotionEvent.ACTION_MOVE: {
if (smileyList.getScrollY() == 0) {
final int pointerIndex = MotionEventCompat.findPointerIndex(event, activePointerId);
final float y = MotionEventCompat.getY(event, pointerIndex);
// Distance
float dy = y - lastTouchY;
isUpwardMovement = dy < 0;
float targetY = smileysSelector.getY() + dy;
if (targetY < toolbarHeight) {
float difference = toolbarHeight - targetY;
dy += difference;
} else if (targetY > smileySelectorTopOffset) {
float difference = targetY - smileySelectorTopOffset;
dy -= difference;
}
smileysSelector.setY(smileysSelector.getY() + dy);
// Show or hide the smileys toolbar based on current position
if (isUpwardMovement && smileysSelector.getY() < replyWindowMaxHeight) {
showSmileysToolbar();
} else {
hideSmileysToolbar();
}
break;
}
}
case MotionEvent.ACTION_UP: {
int upAnimationThreshold = replyWindowMaxHeight - toolbarHeight;
float yTranslation;
ViewPropertyAnimator viewPropertyAnimator = smileysSelector.animate();
if (isUpwardMovement && smileysSelector.getY() == upAnimationThreshold) {
// Do not move in that case
yTranslation = 0;
} else if (isUpwardMovement && smileysSelector.getY() < upAnimationThreshold) {
// Moving too far, let's avoid this
yTranslation = -(smileysSelector.getY() - toolbarHeight);
} else {
// Replace the smiley selector at its original position
yTranslation = smileySelectorTopOffset - smileysSelector.getY();
}
if (yTranslation != 0) {
viewPropertyAnimator
.translationYBy(yTranslation)
.setDuration(150)
.start();
}
break;
}
}
if (smileysSelector.getY() != smileySelectorTopOffset) {
return (smileysSelector.getY() != toolbarHeight);
}
else {
return false;
}
}
});
}
/**
* Smoothly hides the smileys toolbar
*/
protected void hideSmileysToolbar() {
Log.d(LOG_TAG, "Hiding smileys toolbar");
smileysToolbar.animate().translationY(-toolbarHeight).setInterpolator(new AccelerateDecelerateInterpolator()).start();
}
/**
* Smoothly shows the smiley toolbar
*/
protected void showSmileysToolbar() {
Log.d(LOG_TAG, "Showing smileys toolbar");
smileysToolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();
}
@Override
protected void initializeTheme() {
setTheme(themeManager.getReplyWindowStyle());
}
protected boolean canSwitchUser() {
return false;
}
protected void setupUserSwitcher(LayoutInflater inflater, List<User> users) {
if (users.size() == 0) {
Log.e(LOG_TAG, "Empty user list");
}
else if (users.size() == 1 || !canSwitchUser()) {
View userView = setupUserView(inflater, canSwitchUser() ? users.get(0) : userManager.getActiveUser());
actionsToolbar.addView(userView);
}
else {
// Setup spinner for user selection
Log.d(LOG_TAG, String.format("Initializing spinner for '%d' users", users.size()));
View spinnerContainer = inflater.inflate(R.layout.reply_user_spinner, actionsToolbar, false);
ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
actionsToolbar.addView(spinnerContainer, 0, lp);
Spinner spinner = (Spinner) spinnerContainer.findViewById(R.id.reply_user_spinner);
final UserAdapter userAdapter = new UserAdapter(this, users);
spinner.setAdapter(userAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
User user = userAdapter.getItem(position);
userManager.setActiveUser(user);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
protected View setupUserView(LayoutInflater inflater, User user) {
View userView = inflater.inflate(R.layout.dialog_reply_spinner_item, actionsToolbar, false);
ImageView avatarView = (ImageView) userView.findViewById(R.id.user_avatar);
TextView usernameView = (TextView) userView.findViewById(R.id.user_username);
avatarView.setImageResource(R.drawable.profile_background_red);
usernameView.setText(user.getUsername());
if (! user.isGuest()) {
loadUserAvatarInto(user, avatarView);
}
return userView;
}
@Subscribe public void smileySelected(SmileySelectedEvent event) {
insertText(String.format(" %s ", event.getSmileyCode()));
replaceSmileySelector();
hideSmileysToolbar();
}
protected void loadUserAvatarInto(User user, ImageView imageView) {
Optional<Integer> userId = UserUtils.getLoggedInUserId(user, httpClientProvider.getClientForUser(user));
if (userId.isPresent()) {
Picasso.with(this)
.load(mdEndpoints.userAvatar(userId.get()))
.into(imageView);
}
}
/**
* Returns toolbar height, in px
*/
protected int getToolbarHeight() {
TypedValue tv = new TypedValue();
getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
return getResources().getDimensionPixelSize(tv.resourceId);
}
/**
* Inserts a text at current caret position
* @param text text to insert
*/
protected void insertText(String text) {
int selectionStart = replyEditText.getSelectionStart();
int selectionEnd = replyEditText.getSelectionEnd();
if (selectionStart != -1 && selectionEnd != -1) {
replyEditText.getText().replace(selectionStart, selectionEnd, text);
}
else if (selectionStart != -1) {
replyEditText.getText().insert(selectionStart, text);
}
}
protected void insertTag(String tag) {
int selectionStart = replyEditText.getSelectionStart();
String tagOpen = String.format("[%s]", tag);
String tagClose = String.format("[/%s]", tag);
insertText(tagOpen + tagClose);
replyEditText.setSelection(selectionStart + tagOpen.length());
}
@Override
protected void onStart() {
super.onStart();
// Move the smiley picker to the bottom and resize it properly
smileysSelector.setMinimumHeight(screenHeight - getToolbarHeight());
smileysSelector.setY(smileySelectorTopOffset);
// Hide the smileys toolbar
smileysToolbar.setTranslationY(-getToolbarHeight());
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_reply:
// Disable button to prevent user from clicking the button twice and posting the
// same reply multiple times. This could happen often because there is a small delay
// between the click and the activity being closed.
menuItem.setEnabled(false);
postReply();
break;
}
return false;
}
@OnClick({R.id.make_text_bold_button, R.id.make_text_italic_button, R.id.insert_quote_button, R.id.insert_link_button, R.id.insert_spoiler_button})
public void onExtraToolbarButtonClicked(ImageButton button) {
Log.d(LOG_TAG, "Button clicked !");
switch (button.getId()) {
case R.id.insert_spoiler_button:
insertTag("spoiler");
break;
case R.id.insert_link_button:
insertTag("url");
break;
case R.id.insert_quote_button:
insertTag("quote");
break;
case R.id.make_text_bold_button:
insertTag("b");
break;
case R.id.make_text_italic_button:
insertTag("i");
break;
}
}
/**
* Posts the reply on the server
*/
protected void postReply() {
User activeUser = userManager.getActiveUser();
String message = replyEditText.getText().toString();
subscribe(replySubscriptionHandler.load(activeUser, mdService.replyToTopic(activeUser, currentTopic, message, true), new EndlessObserver<Response>() {
@Override
public void onNext(Response response) {
if (response.isSuccessful()) {
onReplySuccess();
} else {
onReplyFailure();
}
}
@Override
public void onError(Throwable throwable) {
Log.e(LOG_TAG, "Unknown exception while replying", throwable);
onReplyFailure();
}
}));
}
protected void onReplySuccess() {
clearResponseFromCache(userManager.getActiveUser());
replyToActivity(RESULT_OK, false);
}
protected void onReplyFailure() {
replyToActivity(UIConstants.REPLY_RESULT_KO, false);
}
protected void replyToActivity(int returnCode, boolean wasEdit) {
Intent returnIntent = new Intent();
returnIntent.putExtra(UIConstants.ARG_REPLY_TOPIC, currentTopic);
returnIntent.putExtra(UIConstants.ARG_REPLY_WAS_EDIT, wasEdit);
setResult(returnCode, returnIntent);
finish();
}
/**
* Animates the smiley selector back to its original position
*/
private void replaceSmileySelector() {
smileysSelector.animate()
.translationYBy(smileySelectorTopOffset - smileysSelector.getY())
.setDuration(150)
.start();
}
private void styleToolbarButtons(Toolbar toolbar) {
for (int i = 0; i < toolbar.getChildCount(); i++) {
View childView = toolbar.getChildAt(i);
if (childView instanceof ImageButton) {
ImageButton imageButton = (ImageButton) childView;
UiUtils.setDrawableColor(imageButton.getDrawable(), UiUtils.getReplyToolbarIconsColor(this));
}
}
}
private void styleToolbarMenu(Toolbar toolbar) {
for (int i = 0; i < toolbar.getMenu().size(); i++) {
MenuItem menuItem = toolbar.getMenu().getItem(i);
Drawable itemIcon = menuItem.getIcon();
if (itemIcon != null) {
UiUtils.setDrawableColor(itemIcon, UiUtils.getReplyToolbarIconsColor(ReplyActivity.this));
}
}
}
private void styleSmileySearchView() {
ImageView searchButton = (ImageView) smileysSearch.findViewById(R.id.search_button);
ImageView searchMagButton = (ImageView) smileysSearch.findViewById(R.id.search_mag_icon);
ImageView closeButton = (ImageView) smileysSearch.findViewById(R.id.search_close_btn);
ImageView searchGoButton = (ImageView) smileysSearch.findViewById(R.id.search_go_btn);
ImageView voiceSearchButton = (ImageView) smileysSearch.findViewById(R.id.search_voice_btn);
UiUtils.setDrawableColor(searchButton.getDrawable(), UiUtils.getReplyToolbarIconsColor(ReplyActivity.this));
UiUtils.setDrawableColor(searchMagButton.getDrawable(), UiUtils.getReplyToolbarIconsColor(ReplyActivity.this));
UiUtils.setDrawableColor(closeButton.getDrawable(), UiUtils.getReplyToolbarIconsColor(ReplyActivity.this));
UiUtils.setDrawableColor(searchGoButton.getDrawable(), UiUtils.getReplyToolbarIconsColor(ReplyActivity.this));
UiUtils.setDrawableColor(voiceSearchButton.getDrawable(), UiUtils.getReplyToolbarIconsColor(ReplyActivity.this));
}
public Topic getCurrentTopic() {
return currentTopic;
}
protected void clearResponseFromCache(User user) {
responseStore.removeResponse(user, currentTopic);
}
protected void storeResponseInCache(User user, String message) {
responseStore.storeResponse(user, currentTopic, message);
}
protected String loadResponseFromCache(User user) {
return responseStore.getResponse(user, currentTopic);
}
private static class UserViewHolder {
public TextView username;
public ImageView avatar;
}
private class UserAdapter extends BindableAdapter<User> {
private final List<User> users;
private UserAdapter(Context context, List<User> users) {
super(context);
this.users = users;
}
@Override
public View newView(LayoutInflater inflater, int position, ViewGroup container) {
View convertView = getLayoutInflater().inflate(R.layout.dialog_reply_spinner_item, container, false);
UserViewHolder viewHolder = new UserViewHolder();
viewHolder.username = (TextView) convertView.findViewById(R.id.user_username);
viewHolder.avatar = (ImageView) convertView.findViewById(R.id.user_avatar);
convertView.setTag(viewHolder);
return convertView;
}
@Override
public void bindView(User user, int position, View view) {
UserViewHolder viewHolder = (UserViewHolder) view.getTag();
viewHolder.username.setText(user.getUsername());
viewHolder.avatar.setImageResource(R.drawable.profile_background_red);
if (! user.isGuest()) {
loadUserAvatarInto(user, viewHolder.avatar);
}
}
@Override
public int getCount() {
return users.size();
}
@Override
public User getItem(int position) {
return users.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
} |
package com.bizbeam.s3.uploader;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.apache.log4j.Logger;
import java.io.File;
public class S3Connector {
private String mAWS_S3_BUCKET;
private String mAWS_ACCESS_KEY;
private String mAWS_SECRET_KEY;
private AmazonS3 mAmazonS3;
private boolean mInitialized = false;
public S3Connector(String s3Bucket, String s3AccessKey, String s3SecretKey) {
mAWS_S3_BUCKET = s3Bucket;
mAWS_ACCESS_KEY = s3AccessKey;
mAWS_SECRET_KEY = s3SecretKey;
}
public void initialize() throws Exception {
if ((mAWS_ACCESS_KEY != null) && (mAWS_SECRET_KEY != null)) {
AWSCredentials awsCredentials = new BasicAWSCredentials(mAWS_ACCESS_KEY, mAWS_SECRET_KEY);
mAmazonS3 = new AmazonS3Client(awsCredentials);
try {
mAmazonS3.listBuckets();
} catch (AmazonS3Exception exc) {
if (exc.getErrorCode().equals("SignatureDoesNotMatch"))
throw new Exception("WRONG AWS KEY OR PASSWORD!");
}
LOGGER.info("Using S3 Bucket: " + mAWS_S3_BUCKET);
mInitialized = true;
}
}
public void uploadFile(File file) throws Exception {
if (!mInitialized)
throw new Exception(CONNECTOR_NOT_INITIAZLIED_ERROR_MSG);
PutObjectRequest putObjectRequest = new PutObjectRequest(mAWS_S3_BUCKET, file.getName(), file);
putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead);
mAmazonS3.putObject(putObjectRequest);
}
public void createNewBucket(String bucketName) throws Exception {
if (!mInitialized)
throw new Exception(CONNECTOR_NOT_INITIAZLIED_ERROR_MSG);
mAmazonS3.createBucket(bucketName);
}
public void removeFile(String objectKey) throws Exception {
if (!mInitialized)
throw new Exception(CONNECTOR_NOT_INITIAZLIED_ERROR_MSG);
mAmazonS3.deleteObject(mAWS_S3_BUCKET, objectKey);
}
private static String CONNECTOR_NOT_INITIAZLIED_ERROR_MSG = "Connector not initialized";
private static final Logger LOGGER = Logger.getLogger(S3Connector.class);
} |
package com.czbix.xposed.wifipassword;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Resources;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.UserHandle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
public class Patch implements IXposedHookLoadPackage {
private static final String PKG_NAME = "com.android.settings";
private static final boolean IS_ABOVE_N = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
private static final boolean IS_ABOVE_M = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
private static final boolean IS_SAMSUNG = Build.BRAND.equals("samsung");
private static final boolean IS_HTC = Build.BRAND.equals("htc");
public void handleLoadPackage(LoadPackageParam param) throws Throwable {
if (param.packageName.equals("android")) {
ServerPatch.hookWifiStore(param.classLoader);
} else if (param.packageName.equals(PKG_NAME)) {
hookWifiController(param.classLoader);
}
}
private void hookWifiController(ClassLoader loader) {
final Class<?> controller = XposedHelpers.findClass("com.android.settings.wifi.WifiConfigController", loader);
do {
if (IS_ABOVE_N) {
if (tryHookConstructor(controller,
"Hook N constructor",
"com.android.settings.wifi.WifiConfigUiBase",
View.class,
"com.android.settingslib.wifi.AccessPoint",
int.class,
methodHook)) {
break;
}
if (IS_SAMSUNG && tryHookConstructor(controller,
"Hook Samsung N constructor",
"com.android.settings.wifi.WifiConfigUiBase",
View.class,
"com.android.settingslib.wifi.AccessPoint",
int.class,
Bundle.class,
methodHook)) {
break;
}
}
if (IS_ABOVE_M && tryHookConstructor(controller,
"Hook M constructor",
"com.android.settings.wifi.WifiConfigUiBase",
View.class,
"com.android.settingslib.wifi.AccessPoint",
boolean.class,
boolean.class,
methodHook)) {
break;
}
if (tryHookConstructor(controller,
"Hook L constructor",
"com.android.settings.wifi.WifiConfigUiBase",
View.class,
"com.android.settings.wifi.AccessPoint",
boolean.class,
methodHook)) {
break;
}
if (IS_SAMSUNG && tryHookConstructor(controller,
"Hook Samsung constructor",
"com.android.settings.wifi.WifiConfigUiBase",
View.class,
"com.android.settings.wifi.AccessPoint",
boolean.class,
boolean.class,
methodHook)) {
break;
}
if (IS_HTC && tryHookConstructor(controller,
"Hook HTC constructor",
"com.android.settings.wifi.WifiConfigUiBase",
View.class,
"com.android.settings.wifi.AccessPoint",
int.class,
methodHook)) {
break;
}
XposedBridge.log("All constructor hook failed!");
}
while (false);
}
private static boolean tryHookConstructor(Class<?> clazz, String msg,
Object... parameterTypesAndCallback) {
try {
XposedHelpers.findAndHookConstructor(clazz, parameterTypesAndCallback);
} catch (Error e) {
return false;
}
XposedBridge.log(msg + " success");
return true;
}
private final XC_MethodHook methodHook = new XC_MethodHook() {
private Context mContext;
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
if (!isOwner()) {
// only show password for owner
return;
}
final Object mAccessPoint = XposedHelpers.getObjectField(param.thisObject, "mAccessPoint");
if (mAccessPoint == null) {
return;
}
final int networkId = XposedHelpers.getIntField(mAccessPoint, "networkId");
if (networkId == -1) {
return;
}
if (IS_ABOVE_N) {
final int mMode = XposedHelpers.getIntField(param.thisObject, "mMode");
// WifiConfigUiBase.MODE_VIEW
if (mMode != 0) {
return;
}
} else if (IS_HTC) {
final int mEdit = XposedHelpers.getIntField(param.thisObject, "mEdit");
if (mEdit != 0) {
return;
}
} else {
final boolean mEdit = XposedHelpers.getBooleanField(param.thisObject, "mEdit");
if (mEdit) {
return;
}
}
final View mView = (View) XposedHelpers.getObjectField(param.thisObject, "mView");
final Context context = mView.getContext();
mContext = context.createPackageContext(BuildConfig.APPLICATION_ID,
Context.CONTEXT_RESTRICTED);
final Resources resources = context.getResources();
final int idInfo = resources.getIdentifier("info", "id", PKG_NAME);
final int idPwd = resources.getIdentifier("wifi_password", "string", PKG_NAME);
final ViewGroup group = (ViewGroup) mView.findViewById(idInfo);
final int mSecurity = XposedHelpers.getIntField(param.thisObject, "mAccessPointSecurity");
final String emptyPassword = mContext.getString(R.string.empty_password);
String pwd;
if (mSecurity != 1 && mSecurity != 2) {
// not WEP/PSK
pwd = emptyPassword;
} else {
pwd = getWiFiPassword(context, networkId);
// more check, more safe
if (pwd == null) {
pwd = emptyPassword;
}
}
final String ssid = (String) XposedHelpers.getObjectField(mAccessPoint, "ssid");
addRow(param, idPwd, group, ssid, pwd);
}
private void addRow(MethodHookParam param, int idPwd, ViewGroup group, final String ssid, final String pwd) {
String defaultPwd = mContext.getString(R.string.empty_password);
if (!pwd.equals(defaultPwd)) {
defaultPwd = new String(new char[pwd.length()]).replace("\0", "·");
}
XposedHelpers.callMethod(param.thisObject, "addRow", group, idPwd, defaultPwd);
final View view = group.getChildAt(group.getChildCount() - 1);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Context context = v.getContext();
final int idValue = context.getResources().getIdentifier("value", "id", PKG_NAME);
final TextView textView = (TextView) view.findViewById(idValue);
if (textView == null) {
if (IS_HTC) {
// I hate HTC
final int idItem = context.getResources().getIdentifier("item", "id", PKG_NAME);
XposedHelpers.callMethod(view.findViewById(idItem), "setSecondaryText", pwd);
} else {
// show password in toast as alternative
Toast.makeText(context, pwd, Toast.LENGTH_LONG).show();
}
} else {
textView.setText(pwd);
}
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
final Context context = v.getContext();
final ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setPrimaryClip(ClipData.newPlainText(null,
mContext.getString(R.string.clip_info_format, ssid, pwd)));
Toast.makeText(context, mContext.getString(R.string.toast_wifi_info_copied), Toast.LENGTH_SHORT).show();
return false;
}
});
}
private String getWiFiPassword(Context context, int networkId) {
final WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
@SuppressWarnings("unchecked")
final List<WifiConfiguration> list = (List<WifiConfiguration>) XposedHelpers.callMethod(wifiManager, "getPrivilegedConfiguredNetworks");
String pwd;
for (WifiConfiguration config : list) {
if (config.networkId == networkId) {
if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
pwd = config.preSharedKey;
} else {
pwd = config.wepKeys[config.wepTxKeyIndex];
}
if (pwd != null) {
return pwd.replaceAll("^\"|\"$", "");
}
}
}
return null;
}
};
private static boolean isOwner() {
final int currentUser = (int) XposedHelpers.callStaticMethod(ActivityManager.class, "getCurrentUser");
return currentUser == XposedHelpers.getStaticIntField(UserHandle.class, "USER_OWNER");
}
} |
package com.hyphenate.chatuidemo;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.util.Log;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chatuidemo.call.CallManager;
import com.hyphenate.chatuidemo.call.CallReceiver;
import com.hyphenate.chatuidemo.call.VideoCallActivity;
import com.hyphenate.chatuidemo.call.VoiceCallActivity;
import com.hyphenate.chatuidemo.chat.ChatActivity;
import com.hyphenate.chatuidemo.chat.MessageNotifier;
import com.hyphenate.chatuidemo.group.GroupChangeListener;
import com.hyphenate.chatuidemo.ui.MainActivity;
import com.hyphenate.chatuidemo.user.ContactsChangeListener;
import com.hyphenate.chatuidemo.user.model.UserEntity;
import com.hyphenate.chatuidemo.user.model.UserProfileManager;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.model.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.util.EMLog;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class DemoHelper {
protected static final String TAG = DemoHelper.class.getSimpleName();
private static DemoHelper instance;
// context
private Context mContext;
// Call broadcast receiver
private CallReceiver mCallReceiver = null;
// Contacts listener
private ContactsChangeListener mContactListener = null;
private DefaultGroupChangeListener mGroupListener = null;
private UserProfileManager mUserManager;
//whether in calling
public boolean isVoiceCalling;
public boolean isVideoCalling;
private ExecutorService executor = null;
/**
* save foreground Activity which registered message listeners
*/
private List<Activity> activityList = new ArrayList<Activity>();
private MessageNotifier mNotifier = new MessageNotifier();
private DemoHelper() {
this.executor = Executors.newCachedThreadPool();
}
public synchronized static DemoHelper getInstance() {
if (instance == null) {
instance = new DemoHelper();
}
return instance;
}
public void execute(Runnable runnable) {
executor.execute(runnable);
}
/**
* init helper
*
* @param context application context
*/
public void init(Context context) {
mContext = context;
if (isMainProcess()) {
EMLog.d(TAG, "
//init hyphenate sdk with options
EMClient.getInstance().init(context, initOptions());
// init call options
initCallOptions();
// set debug mode open:true, close:false
EMClient.getInstance().setDebugMode(true);
//init EaseUI if you want to use it
EaseUI.getInstance().init(context);
PreferenceManager.init(context);
//init user manager
getUserManager().init(context);
//init message notifier
mNotifier.init(context);
//set events listeners
setGlobalListener();
setEaseUIProviders();
// init call
CallManager.getInstance().init(context);
EMLog.d(TAG, "
}
}
/**
* init sdk options
*/
private EMOptions initOptions() {
// set init sdk options
EMOptions options = new EMOptions();
// change to need confirm contact invitation
options.setAcceptInvitationAlways(false);
// set if need read ack
options.setRequireAck(true);
// set if need delivery ack
options.setRequireDeliveryAck(false);
// set auto accept group invitation
SharedPreferences preferences =
android.preference.PreferenceManager.getDefaultSharedPreferences(mContext);
options.setAutoAcceptGroupInvitation(preferences.getBoolean(
mContext.getString(R.string.em_pref_key_accept_group_invite_automatically), false));
//set gcm project number
options.setGCMNumber("324169311137");
return options;
}
/**
* init call options
*/
private void initCallOptions() {
// set video call bitrate, default(150)
EMClient.getInstance().callManager().getCallOptions().setMaxVideoKbps(800);
// set video call resolution, default(320, 240)
EMClient.getInstance().callManager().getCallOptions().setVideoResolution(640, 480);
// send push notification when user offline
EMClient.getInstance().callManager().getCallOptions().setIsSendPushIfOffline(true);
}
/**
* init global listener
*/
private void setGlobalListener() {
// set call listener
setCallReceiverListener();
// set connection listener
setConnectionListener();
// register message listener
registerMessageListener();
// register contacts listener
registerContactsListener();
registerGroupListener();
}
private void registerGroupListener() {
if (mGroupListener == null) {
mGroupListener = new DefaultGroupChangeListener();
}
EMClient.getInstance().groupManager().addGroupChangeListener(mGroupListener);
}
private class DefaultGroupChangeListener extends GroupChangeListener {
@Override public void onInvitationReceived(String s, String s1, String s2, String s3) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON,
" receive invitation to join the group" + s1);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, "");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body =
new EMTextMessageBody(" receive invitation to join the group" + s1);
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s2);
message.setAttribute(Constant.MESSAGE_ATTR_REASON,
" receive invitation to join the group" + s1);
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 0);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setMsgId(msgId);
// save message to db
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onRequestToJoinReceived(String s, String s1, String s2, String s3) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON, " Apply to join group" + s1);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, "");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body = new EMTextMessageBody(s2 + " Apply to join group" + s1);
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s2);
message.setAttribute(Constant.MESSAGE_ATTR_REASON,
s2 + " Apply to join public group" + s1);
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 1);
message.setMsgId(msgId);
// save message to db
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onRequestToJoinAccepted(String s, String s1, String s2) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s2 + " Accepted your group apply ");
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s2 + "Agreed");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body = new EMTextMessageBody(s2 + " Accepted your group apply ");
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s1);
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s2 + " Accepted your group apply ");
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 1);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s2 + " Agreed");
message.setStatus(EMMessage.Status.SUCCESS);
message.setMsgId(msgId);
// save accept message
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onRequestToJoinDeclined(String s, String s1, String s2, String s3) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s2 + " Declined your group apply ");
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s2 + " Declined");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body = new EMTextMessageBody(s2 + " Declined your group apply ");
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s1);
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s2 + " Declined your group apply ");
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 1);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s2 + " Declined");
message.setStatus(EMMessage.Status.SUCCESS);
message.setMsgId(msgId);
// save accept message
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onInvitationAccepted(String s, String s1, String s2) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s1 + " Accepted your group invite ");
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s1 + " Accepted");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body = new EMTextMessageBody(s2 + " Accepted your group invite ");
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s1);
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s1 + " Accepted your group invite ");
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 0);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s1 + " Accepted");
message.setStatus(EMMessage.Status.SUCCESS);
message.setMsgId(msgId);
// save accept message
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onInvitationDeclined(String s, String s1, String s2) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s1 + " Declined your group invite ");
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s1 + " Declined");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body = new EMTextMessageBody(s1 + " Declined your group invite ");
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s1);
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s1 + " Declined your group invite ");
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 0);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s1 + " Declined");
message.setStatus(EMMessage.Status.SUCCESS);
message.setMsgId(msgId);
// save accept message
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onUserRemoved(String s, String s1) {
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onGroupDestroyed(String s, String s1) {
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onAutoAcceptInvitationFromGroup(String s, String s1, String s2) {
EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
msg.setChatType(EMMessage.ChatType.GroupChat);
msg.setFrom(s1);
msg.setTo(s);
msg.setMsgId(UUID.randomUUID().toString());
msg.addBody(new EMTextMessageBody(s1 + " Invite you to join this group "));
msg.setStatus(EMMessage.Status.SUCCESS);
// save invitation as messages
EMClient.getInstance().chatManager().saveMessage(msg);
getNotifier().vibrateAndPlayTone(null);
}
}
protected void setEaseUIProviders() {
// set profile provider if you want easeUI to handle avatar and nickname
EaseUI.getInstance().setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {
@Override public EaseUser getUser(String username) {
return getUserInfo(username);
}
});
//set notification options, will use default if you don't set it
getNotifier().setNotificationInfoProvider(
new MessageNotifier.EaseNotificationInfoProvider() {
@Override public String getTitle(EMMessage message) {
//you can update title here
return null;
}
@Override public int getSmallIcon(EMMessage message) {
//you can update icon here
return 0;
}
@Override public String getDisplayedText(EMMessage message) {
// be used on notification bar, different text according the message type.
String ticker = EaseCommonUtils.getMessageDigest(message, mContext);
if (message.getType() == EMMessage.Type.TXT) {
ticker = ticker.replaceAll("\\[.{2,3}\\]", "[Emoticon]");
}
EaseUser user = getUserInfo(message.getFrom());
if (user != null) {
return user.getEaseNickname() + ": " + ticker;
} else {
return message.getFrom() + ": " + ticker;
}
}
@Override public String getLatestText(EMMessage message, int fromUsersNum,
int messageNum) {
// here you can customize the text.
// return fromUsersNum + "contacts send " + messageNum + "messages to you";
return null;
}
@Override public Intent getLaunchIntent(EMMessage message) {
// you can set what activity you want display when user click the notification
Intent intent = new Intent(mContext, ChatActivity.class);
// open calling activity if there is call
if (isVideoCalling) {
intent = new Intent(mContext, VideoCallActivity.class);
} else if (isVoiceCalling) {
intent = new Intent(mContext, VoiceCallActivity.class);
} else {
ChatType chatType = message.getChatType();
if (chatType == ChatType.Chat) { // single chat message
intent.putExtra("userId", message.getFrom());
intent.putExtra("chatType", Constant.CHATTYPE_SINGLE);
} else { // group chat message
// message.getTo() is the group id
intent.putExtra("userId", message.getTo());
if (chatType == ChatType.GroupChat) {
intent.putExtra("chatType", Constant.CHATTYPE_GROUP);
} else {
intent.putExtra("chatType", Constant.CHATTYPE_CHATROOM);
}
}
}
return intent;
}
});
EaseUI.getInstance().setSettingsProvider(new EaseUI.EaseSettingsProvider() {
@Override public boolean isMsgNotifyAllowed(EMMessage message) {
return DemoModel.getInstance(mContext).isNotification();
}
@Override public boolean isMsgSoundAllowed(EMMessage message) {
return DemoModel.getInstance(mContext).isSoundNotification();
}
@Override public boolean isMsgVibrateAllowed(EMMessage message) {
return DemoModel.getInstance(mContext).isVibrateNotification();
}
@Override public boolean isSpeakerOpened() {
return false;
}
});
}
private EaseUser getUserInfo(String username) {
EaseUser user;
if (username.equals(EMClient.getInstance().getCurrentUser())) {
return getUserManager().getCurrentUserInfo();
}
user = mUserManager.getContactList().get(username);
//TODO Get not in the buddy list of group members in the specific information, that stranger information, demo not implemented
// if user is not in your contacts, set initial letter for him/her
if (user == null) {
user = new UserEntity(username);
}
return user;
}
/**
* Set call broadcast listener
*/
private void setCallReceiverListener() {
// Set the call broadcast listener to filter the action
IntentFilter callFilter = new IntentFilter(
EMClient.getInstance().callManager().getIncomingCallBroadcastAction());
if (mCallReceiver == null) {
mCallReceiver = new CallReceiver();
}
// Register the call receiver
mContext.registerReceiver(mCallReceiver, callFilter);
}
/**
* Set Connection Listener
*/
private void setConnectionListener() {
EMConnectionListener mConnectionListener = new EMConnectionListener() {
/**
* The connection to the server is successful
*/
@Override public void onConnected() {
EMLog.d(TAG, "onConnected");
}
/**
* Disconnected from the server
*
* @param errorCode Disconnected error code
*/
@Override public void onDisconnected(int errorCode) {
EMLog.d(TAG, "onDisconnected: " + errorCode);
if (errorCode == EMError.USER_LOGIN_ANOTHER_DEVICE) {
onConnectionConflict();
}
}
};
EMClient.getInstance().addConnectionListener(mConnectionListener);
}
/**
* new messages listener
* If this event already handled by an activity, you don't need handle it again
* activityList.size() <= 0 means all activities already in background or not in Activity Stack
*/
private void registerMessageListener() {
EMMessageListener messageListener = new EMMessageListener() {
@Override public void onMessageReceived(List<EMMessage> messages) {
for (EMMessage message : messages) {
EMLog.d(TAG, "onMessageReceived id : " + message.getMsgId());
// in background, do not refresh UI, notify it in notification bar
if (!hasForegroundActivities()) {
if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_CALL_PUSH, false)) {
EMClient.getInstance().chatManager().getConversation(message.getFrom()).removeMessage(message.getMsgId());
} else {
// FIXME: conflict with group push notification if it's turned off, push still come in when phone is unlocked as the app is woken up by the phone to run in the background
// getNotifier().onNewMsg(message);
}
}
}
}
@Override public void onCmdMessageReceived(List<EMMessage> messages) {
for (EMMessage message : messages) {
EMLog.d(TAG, "onCmdMessageReceived");
//get message body
EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
final String action = cmdMsgBody.action();
//get extension attribute if you need
//message.getStringAttribute("");
EMLog.d(TAG, String.format("CmdMessageaction:%s,message:%s", action,
message.toString()));
}
}
@Override public void onMessageRead(List<EMMessage> messages) {
}
@Override public void onMessageDelivered(List<EMMessage> message) {
}
@Override public void onMessageChanged(EMMessage message, Object change) {
}
};
EMClient.getInstance().chatManager().addMessageListener(messageListener);
}
/**
* Register contacts listener
* Listen for changes to contacts
*/
private void registerContactsListener() {
if (mContactListener == null) {
mContactListener = new DefaultContactsChangeListener();
}
EMClient.getInstance().contactManager().setContactListener(mContactListener);
}
private class DefaultContactsChangeListener extends ContactsChangeListener {
@Override public void onContactAdded(String username) {
super.onContactAdded(username);
}
@Override public void onContactDeleted(String username) {
super.onContactDeleted(username);
}
@Override public void onContactInvited(String username, String reason) {
super.onContactInvited(username, reason);
}
@Override public void onFriendRequestAccepted(String username) {
super.onFriendRequestAccepted(username);
}
@Override public void onFriendRequestDeclined(String username) {
super.onFriendRequestDeclined(username);
}
}
private boolean hasForegroundActivities() {
return activityList.size() != 0;
}
public void pushActivity(Activity activity) {
if (!activityList.contains(activity)) {
activityList.add(0, activity);
}
}
public void popActivity(Activity activity) {
activityList.remove(activity);
}
public MessageNotifier getNotifier() {
return mNotifier;
}
public UserProfileManager getUserManager() {
if (mUserManager == null) {
mUserManager = new UserProfileManager();
}
return mUserManager;
}
/**
* Sign out account
*
* @param callback to receive the result of the logout
*/
public void signOut(boolean unbindDeviceToken, final EMCallBack callback) {
Log.d(TAG, "Sign out: " + unbindDeviceToken);
EMClient.getInstance().logout(unbindDeviceToken, new EMCallBack() {
@Override public void onSuccess() {
Log.d(TAG, "Sign out: onSuccess");
if (callback != null) {
callback.onSuccess();
}
reset();
}
@Override public void onProgress(int progress, String status) {
if (callback != null) {
callback.onProgress(progress, status);
}
}
@Override public void onError(int code, String error) {
Log.d(TAG, "Sign out: onSuccess");
if (callback != null) {
callback.onError(code, error);
}
}
});
}
/**
* user has logged into another device
*/
protected void onConnectionConflict() {
Intent intent = new Intent(mContext, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Constant.ACCOUNT_CONFLICT, true);
mContext.startActivity(intent);
}
private synchronized void reset() {
getUserManager().reset();
}
/**
* check the application process name if process name is not qualified, then we think it is a
* service process and we will not init SDK
*/
private boolean isMainProcess() {
int pid = android.os.Process.myPid();
String processAppName = getAppName(pid);
Log.d(TAG, "process app name : " + processAppName);
// if there is application has remote service, application:onCreate() maybe called twice
// this check is to make sure SDK will initialized only once
// return if process name is not application's name since the package name is the default process name
if (processAppName == null || !processAppName.equalsIgnoreCase(mContext.getPackageName())) {
Log.e(TAG, "enter the service process!");
return false;
}
return true;
}
/**
* According to Pid to obtain the name of the current process, the general is the current app
* package name,
*
* @param pID Process ID
* @return Process name
*/
private String getAppName(int pID) {
String processName;
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = mContext.getPackageManager();
while (i.hasNext()) {
ActivityManager.RunningAppProcessInfo info =
(ActivityManager.RunningAppProcessInfo) (i.next());
try {
if (info.pid == pID) {
CharSequence c = pm.getApplicationLabel(
pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
// Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
// info.processName +" Label: "+c.toString());
// processName = c.toString();
processName = info.processName;
return processName;
}
} catch (Exception e) {
// Log.d("Process", "Error>> :"+ e.toString());
}
}
return null;
}
} |
package com.hyphenate.chatuidemo;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.util.Log;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chatuidemo.call.CallManager;
import com.hyphenate.chatuidemo.call.CallReceiver;
import com.hyphenate.chatuidemo.call.VideoCallActivity;
import com.hyphenate.chatuidemo.call.VoiceCallActivity;
import com.hyphenate.chatuidemo.chat.ChatActivity;
import com.hyphenate.chatuidemo.chat.MessageNotifier;
import com.hyphenate.chatuidemo.group.GroupChangeListener;
import com.hyphenate.chatuidemo.ui.MainActivity;
import com.hyphenate.chatuidemo.user.ContactsChangeListener;
import com.hyphenate.chatuidemo.user.model.UserEntity;
import com.hyphenate.chatuidemo.user.model.UserProfileManager;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.model.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.util.EMLog;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class DemoHelper {
protected static final String TAG = DemoHelper.class.getSimpleName();
private static DemoHelper instance;
// context
private Context mContext;
// Call broadcast receiver
private CallReceiver mCallReceiver = null;
// Contacts listener
private ContactsChangeListener mContactListener = null;
private DefaultGroupChangeListener mGroupListener = null;
private UserProfileManager mUserManager;
//whether in calling
public boolean isVoiceCalling;
public boolean isVideoCalling;
private ExecutorService executor = null;
/**
* save foreground Activity which registered message listeners
*/
private List<Activity> activityList = new ArrayList<Activity>();
private MessageNotifier mNotifier = new MessageNotifier();
private DemoHelper() {
this.executor = Executors.newCachedThreadPool();
}
public synchronized static DemoHelper getInstance() {
if (instance == null) {
instance = new DemoHelper();
}
return instance;
}
public void execute(Runnable runnable) {
executor.execute(runnable);
}
/**
* init helper
*
* @param context application context
*/
public void init(Context context) {
mContext = context;
if (isMainProcess()) {
EMLog.d(TAG, "
//init hyphenate sdk with options
EMClient.getInstance().init(context, initOptions());
// init call options
initCallOptions();
// set debug mode open:true, close:false
EMClient.getInstance().setDebugMode(true);
//init EaseUI if you want to use it
EaseUI.getInstance().init(context);
PreferenceManager.init(context);
//init user manager
getUserManager().init(context);
//init message notifier
mNotifier.init(context);
//set events listeners
setGlobalListener();
setEaseUIProviders();
// init call
CallManager.getInstance().init(context);
EMLog.d(TAG, "
}
}
/**
* init sdk options
*/
private EMOptions initOptions() {
// set init sdk options
EMOptions options = new EMOptions();
// change to need confirm contact invitation
options.setAcceptInvitationAlways(false);
// set if need read ack
options.setRequireAck(true);
// set if need delivery ack
options.setRequireDeliveryAck(false);
// set auto accept group invitation
SharedPreferences preferences =
android.preference.PreferenceManager.getDefaultSharedPreferences(mContext);
options.setAutoAcceptGroupInvitation(preferences.getBoolean(
mContext.getString(R.string.em_pref_key_accept_group_invite_automatically), false));
//set gcm project number
options.setGCMNumber("324169311137");
return options;
}
/**
* init call options
*/
private void initCallOptions() {
// set video call bitrate, default(150)
EMClient.getInstance().callManager().getCallOptions().setMaxVideoKbps(800);
// set video call resolution, default(320, 240)
EMClient.getInstance().callManager().getCallOptions().setVideoResolution(640, 480);
// send push notification when user offline
EMClient.getInstance().callManager().getCallOptions().setIsSendPushIfOffline(true);
}
/**
* init global listener
*/
private void setGlobalListener() {
// set call listener
setCallReceiverListener();
// set connection listener
setConnectionListener();
// register message listener
registerMessageListener();
// register contacts listener
registerContactsListener();
registerGroupListener();
}
private void registerGroupListener() {
if (mGroupListener == null) {
mGroupListener = new DefaultGroupChangeListener();
}
EMClient.getInstance().groupManager().addGroupChangeListener(mGroupListener);
}
private class DefaultGroupChangeListener extends GroupChangeListener {
@Override public void onInvitationReceived(String s, String s1, String s2, String s3) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON,
" receive invitation to join the group" + s1);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, "");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body =
new EMTextMessageBody(" receive invitation to join the group" + s1);
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s2);
message.setAttribute(Constant.MESSAGE_ATTR_REASON,
" receive invitation to join the group" + s1);
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 0);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setMsgId(msgId);
// save message to db
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onRequestToJoinReceived(String s, String s1, String s2, String s3) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON, " Apply to join group" + s1);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, "");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body = new EMTextMessageBody(s2 + " Apply to join group" + s1);
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s2);
message.setAttribute(Constant.MESSAGE_ATTR_REASON,
s2 + " Apply to join public group" + s1);
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 1);
message.setMsgId(msgId);
// save message to db
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onRequestToJoinAccepted(String s, String s1, String s2) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s2 + " Accepted your group apply ");
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s2 + "Agreed");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body = new EMTextMessageBody(s2 + " Accepted your group apply ");
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s1);
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s2 + " Accepted your group apply ");
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 1);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s2 + " Agreed");
message.setStatus(EMMessage.Status.SUCCESS);
message.setMsgId(msgId);
// save accept message
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onRequestToJoinDeclined(String s, String s1, String s2, String s3) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s2 + " Declined your group apply ");
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s2 + " Declined");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body = new EMTextMessageBody(s2 + " Declined your group apply ");
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s1);
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s2 + " Declined your group apply ");
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 1);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s2 + " Declined");
message.setStatus(EMMessage.Status.SUCCESS);
message.setMsgId(msgId);
// save accept message
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onInvitationAccepted(String s, String s1, String s2) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s1 + " Accepted your group invite ");
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s1 + " Accepted");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body = new EMTextMessageBody(s2 + " Accepted your group invite ");
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s1);
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s1 + " Accepted your group invite ");
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 0);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s1 + " Accepted");
message.setStatus(EMMessage.Status.SUCCESS);
message.setMsgId(msgId);
// save accept message
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onInvitationDeclined(String s, String s1, String s2) {
String msgId = s2 + s + EMClient.getInstance().getCurrentUser();
EMMessage message = EMClient.getInstance().chatManager().getMessage(msgId);
if (message != null) {
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s1 + " Declined your group invite ");
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s1 + " Declined");
message.setMsgTime(System.currentTimeMillis());
message.setLocalTime(message.getMsgTime());
message.setUnread(true);
// update message
EMClient.getInstance().chatManager().updateMessage(message);
} else {
// Create message save application info
message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
EMTextMessageBody body = new EMTextMessageBody(s1 + " Declined your group invite ");
message.addBody(body);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_ID, s);
message.setAttribute(Constant.MESSAGE_ATTR_USERNAME, s1);
message.setAttribute(Constant.MESSAGE_ATTR_REASON, s1 + " Declined your group invite ");
message.setAttribute(Constant.MESSAGE_ATTR_TYPE, 1);
message.setFrom(Constant.CONVERSATION_NAME_APPLY);
message.setAttribute(Constant.MESSAGE_ATTR_GROUP_TYPE, 0);
message.setAttribute(Constant.MESSAGE_ATTR_STATUS, s1 + " Declined");
message.setStatus(EMMessage.Status.SUCCESS);
message.setMsgId(msgId);
// save accept message
EMClient.getInstance().chatManager().saveMessage(message);
}
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onUserRemoved(String s, String s1) {
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onGroupDestroyed(String s, String s1) {
getNotifier().vibrateAndPlayTone(null);
}
@Override public void onAutoAcceptInvitationFromGroup(String s, String s1, String s2) {
EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
msg.setChatType(EMMessage.ChatType.GroupChat);
msg.setFrom(s1);
msg.setTo(s);
msg.setMsgId(UUID.randomUUID().toString());
msg.addBody(new EMTextMessageBody(s1 + " Invite you to join this group "));
msg.setStatus(EMMessage.Status.SUCCESS);
// save invitation as messages
EMClient.getInstance().chatManager().saveMessage(msg);
getNotifier().vibrateAndPlayTone(null);
}
}
protected void setEaseUIProviders() {
// set profile provider if you want easeUI to handle avatar and nickname
EaseUI.getInstance().setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {
@Override public EaseUser getUser(String username) {
return getUserInfo(username);
}
});
//set notification options, will use default if you don't set it
getNotifier().setNotificationInfoProvider(
new MessageNotifier.EaseNotificationInfoProvider() {
@Override public String getTitle(EMMessage message) {
//you can update title here
return null;
}
@Override public int getSmallIcon(EMMessage message) {
//you can update icon here
return 0;
}
@Override public String getDisplayedText(EMMessage message) {
// be used on notification bar, different text according the message type.
String ticker = EaseCommonUtils.getMessageDigest(message, mContext);
if (message.getType() == EMMessage.Type.TXT) {
ticker = ticker.replaceAll("\\[.{2,3}\\]", "[Emoticon]");
}
EaseUser user = getUserInfo(message.getFrom());
if (user != null) {
return user.getEaseNickname() + ": " + ticker;
} else {
return message.getFrom() + ": " + ticker;
}
}
@Override public String getLatestText(EMMessage message, int fromUsersNum,
int messageNum) {
// here you can customize the text.
// return fromUsersNum + "contacts send " + messageNum + "messages to you";
return null;
}
@Override public Intent getLaunchIntent(EMMessage message) {
// you can set what activity you want display when user click the notification
Intent intent = new Intent(mContext, ChatActivity.class);
// open calling activity if there is call
if (isVideoCalling) {
intent = new Intent(mContext, VideoCallActivity.class);
} else if (isVoiceCalling) {
intent = new Intent(mContext, VoiceCallActivity.class);
} else {
ChatType chatType = message.getChatType();
if (chatType == ChatType.Chat) { // single chat message
intent.putExtra("userId", message.getFrom());
intent.putExtra("chatType", Constant.CHATTYPE_SINGLE);
} else { // group chat message
// message.getTo() is the group id
intent.putExtra("userId", message.getTo());
if (chatType == ChatType.GroupChat) {
intent.putExtra("chatType", Constant.CHATTYPE_GROUP);
} else {
intent.putExtra("chatType", Constant.CHATTYPE_CHATROOM);
}
}
}
return intent;
}
});
EaseUI.getInstance().setSettingsProvider(new EaseUI.EaseSettingsProvider() {
@Override public boolean isMsgNotifyAllowed(EMMessage message) {
return DemoModel.getInstance(mContext).isNotification();
}
@Override public boolean isMsgSoundAllowed(EMMessage message) {
return DemoModel.getInstance(mContext).isSoundNotification();
}
@Override public boolean isMsgVibrateAllowed(EMMessage message) {
return DemoModel.getInstance(mContext).isVibrateNotification();
}
@Override public boolean isSpeakerOpened() {
return false;
}
});
}
private EaseUser getUserInfo(String username) {
EaseUser user;
if (username.equals(EMClient.getInstance().getCurrentUser())) {
return getUserManager().getCurrentUserInfo();
}
user = mUserManager.getContactList().get(username);
//TODO Get not in the buddy list of group members in the specific information, that stranger information, demo not implemented
// if user is not in your contacts, set initial letter for him/her
if (user == null) {
user = new UserEntity(username);
}
return user;
}
/**
* Set call broadcast listener
*/
private void setCallReceiverListener() {
// Set the call broadcast listener to filter the action
IntentFilter callFilter = new IntentFilter(
EMClient.getInstance().callManager().getIncomingCallBroadcastAction());
if (mCallReceiver == null) {
mCallReceiver = new CallReceiver();
}
// Register the call receiver
mContext.registerReceiver(mCallReceiver, callFilter);
}
/**
* Set Connection Listener
*/
private void setConnectionListener() {
EMConnectionListener mConnectionListener = new EMConnectionListener() {
/**
* The connection to the server is successful
*/
@Override public void onConnected() {
EMLog.d(TAG, "onConnected");
}
/**
* Disconnected from the server
*
* @param errorCode Disconnected error code
*/
@Override public void onDisconnected(int errorCode) {
EMLog.d(TAG, "onDisconnected: " + errorCode);
if (errorCode == EMError.USER_LOGIN_ANOTHER_DEVICE) {
onConnectionConflict();
}
}
};
EMClient.getInstance().addConnectionListener(mConnectionListener);
}
/**
* new messages listener
* If this event already handled by an activity, you don't need handle it again
* activityList.size() <= 0 means all activities already in background or not in Activity Stack
*/
private void registerMessageListener() {
EMMessageListener messageListener = new EMMessageListener() {
@Override public void onMessageReceived(List<EMMessage> messages) {
for (EMMessage message : messages) {
EMLog.d(TAG, "onMessageReceived id : " + message.getMsgId());
// in background, do not refresh UI, notify it in notification bar
if (!hasForegroundActivities()) {
if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_CALL_PUSH, false)) {
EMClient.getInstance().chatManager().getConversation(message.getFrom()).removeMessage(message.getMsgId());
} else {
// FIXME: conflict with group push notification if it's turned off, push still come in when phone is unlocked as the app is woken up by the phone to run in the background
getNotifier().onNewMsg(message);
}
}
}
}
@Override public void onCmdMessageReceived(List<EMMessage> messages) {
for (EMMessage message : messages) {
EMLog.d(TAG, "onCmdMessageReceived");
//get message body
EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
final String action = cmdMsgBody.action();
//get extension attribute if you need
//message.getStringAttribute("");
EMLog.d(TAG, String.format("CmdMessageaction:%s,message:%s", action,
message.toString()));
}
}
@Override public void onMessageRead(List<EMMessage> messages) {
}
@Override public void onMessageDelivered(List<EMMessage> message) {
}
@Override public void onMessageRecalled(List<EMMessage> messages) {
}
@Override public void onMessageChanged(EMMessage message, Object change) {
}
};
EMClient.getInstance().chatManager().addMessageListener(messageListener);
}
/**
* Register contacts listener
* Listen for changes to contacts
*/
private void registerContactsListener() {
if (mContactListener == null) {
mContactListener = new DefaultContactsChangeListener();
}
EMClient.getInstance().contactManager().setContactListener(mContactListener);
}
private class DefaultContactsChangeListener extends ContactsChangeListener {
@Override public void onContactAdded(String username) {
super.onContactAdded(username);
}
@Override public void onContactDeleted(String username) {
super.onContactDeleted(username);
}
@Override public void onContactInvited(String username, String reason) {
super.onContactInvited(username, reason);
}
@Override public void onFriendRequestAccepted(String username) {
super.onFriendRequestAccepted(username);
}
@Override public void onFriendRequestDeclined(String username) {
super.onFriendRequestDeclined(username);
}
}
private boolean hasForegroundActivities() {
return activityList.size() != 0;
}
public void pushActivity(Activity activity) {
if (!activityList.contains(activity)) {
activityList.add(0, activity);
}
}
public void popActivity(Activity activity) {
activityList.remove(activity);
}
public MessageNotifier getNotifier() {
return mNotifier;
}
public UserProfileManager getUserManager() {
if (mUserManager == null) {
mUserManager = new UserProfileManager();
}
return mUserManager;
}
/**
* Sign out account
*
* @param callback to receive the result of the logout
*/
public void signOut(boolean unbindDeviceToken, final EMCallBack callback) {
Log.d(TAG, "Sign out: " + unbindDeviceToken);
EMClient.getInstance().logout(unbindDeviceToken, new EMCallBack() {
@Override public void onSuccess() {
Log.d(TAG, "Sign out: onSuccess");
if (callback != null) {
callback.onSuccess();
}
reset();
}
@Override public void onProgress(int progress, String status) {
if (callback != null) {
callback.onProgress(progress, status);
}
}
@Override public void onError(int code, String error) {
Log.d(TAG, "Sign out: onSuccess");
if (callback != null) {
callback.onError(code, error);
}
}
});
}
/**
* user has logged into another device
*/
protected void onConnectionConflict() {
Intent intent = new Intent(mContext, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Constant.ACCOUNT_CONFLICT, true);
mContext.startActivity(intent);
}
private synchronized void reset() {
getUserManager().reset();
}
/**
* check the application process name if process name is not qualified, then we think it is a
* service process and we will not init SDK
*/
private boolean isMainProcess() {
int pid = android.os.Process.myPid();
String processAppName = getAppName(pid);
Log.d(TAG, "process app name : " + processAppName);
// if there is application has remote service, application:onCreate() maybe called twice
// this check is to make sure SDK will initialized only once
// return if process name is not application's name since the package name is the default process name
if (processAppName == null || !processAppName.equalsIgnoreCase(mContext.getPackageName())) {
Log.e(TAG, "enter the service process!");
return false;
}
return true;
}
/**
* According to Pid to obtain the name of the current process, the general is the current app
* package name,
*
* @param pID Process ID
* @return Process name
*/
private String getAppName(int pID) {
String processName;
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = mContext.getPackageManager();
while (i.hasNext()) {
ActivityManager.RunningAppProcessInfo info =
(ActivityManager.RunningAppProcessInfo) (i.next());
try {
if (info.pid == pID) {
CharSequence c = pm.getApplicationLabel(
pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
// Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
// info.processName +" Label: "+c.toString());
// processName = c.toString();
processName = info.processName;
return processName;
}
} catch (Exception e) {
// Log.d("Process", "Error>> :"+ e.toString());
}
}
return null;
}
} |
package com.renard.ocr.install;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import java.util.concurrent.ExecutionException;
/**
* This Fragment manages a single background task and retains
* itself across configuration changes.
*/
public class TaskFragment extends Fragment {
/**
* Callback interface through which the fragment will report the
* task's progress and results back to the Activity.
*/
interface TaskCallbacks {
void onPreExecute();
void onProgressUpdate(int percent);
void onCancelled();
void onPostExecute(InstallResult result);
}
private InstallTask mTask;
/**
* Hold a reference to the parent Activity so we can report the
* task's current progress and results. The Android framework
* will pass us a reference to the newly created Activity after
* each configuration change.
*/
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mTask.setTaskCallbacks((TaskCallbacks) getActivity());
}
/**
* This method will only be called once when the retained
* Fragment is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retain this fragment across configuration changes.
setRetainInstance(true);
// Create and execute the background task.
mTask = new InstallTask((TaskCallbacks) getActivity(), getActivity().getAssets());
mTask.execute();
}
/**
* Set the callback to null so we don't accidentally leak the
* Activity instance.
*/
@Override
public void onDetach() {
super.onDetach();
mTask.setTaskCallbacks(null);
}
@Nullable
public InstallResult getInstallResult() {
final AsyncTask.Status status = mTask.getStatus();
if (status == AsyncTask.Status.FINISHED) {
try {
return mTask.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return new InstallResult(InstallResult.Result.UNSPECIFIED_ERROR);
} else {
return null;
}
}
} |
package com.samourai.wallet;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.android.Contents;
import com.google.zxing.client.android.encode.QRCodeEncoder;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.service.WebSocketHandler;
import com.samourai.wallet.service.WebSocketService;
import com.samourai.wallet.util.AddressFactory;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.ExchangeRateFactory;
import com.samourai.wallet.util.MonetaryUtil;
import com.samourai.wallet.util.PrefsUtil;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.Coin;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.uri.BitcoinURI;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class ReceiveActivity extends Activity {
private static Display display = null;
private static int imgWidth = 0;
private ImageView ivQR = null;
private TextView tvAddress = null;
private LinearLayout addressLayout = null;
private EditText edAmountBTC = null;
private EditText edAmountFiat = null;
private TextWatcher textWatcherBTC = null;
private TextWatcher textWatcherFiat = null;
private Switch swSegwit = null;
private CheckBox cbBech32 = null;
private String defaultSeparator = null;
private String strFiat = null;
private double btc_fx = 286.0;
private TextView tvFiatSymbol = null;
private String addr = null;
private String addr44 = null;
private String addr49 = null;
private String addr84 = null;
private boolean canRefresh44 = false;
private boolean canRefresh49 = false;
private boolean canRefresh84 = false;
private Menu _menu = null;
public static final String ACTION_INTENT = "com.samourai.wallet.ReceiveFragment.REFRESH";
protected BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
if(extras != null && extras.containsKey("received_on")) {
String in_addr = extras.getString("received_on");
if(in_addr.equals(addr) || in_addr.equals(addr44) || in_addr.equals(addr49)) {
ReceiveActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
ReceiveActivity.this.finish();
}
});
}
}
}
}
};
public ReceiveActivity() {
;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ReceiveActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
display = (ReceiveActivity.this).getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
imgWidth = Math.max(size.x - 460, 150);
swSegwit = (Switch)findViewById(R.id.segwit);
swSegwit.setChecked(PrefsUtil.getInstance(ReceiveActivity.this).getValue(PrefsUtil.USE_SEGWIT, true));
swSegwit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked && cbBech32.isChecked()) {
addr = addr84;
cbBech32.setVisibility(View.VISIBLE);
}
else if(isChecked && !cbBech32.isChecked()) {
addr = addr49;
cbBech32.setVisibility(View.VISIBLE);
}
else {
addr = addr44;
cbBech32.setVisibility(View.GONE);
}
displayQRCode();
}
});
cbBech32 = (CheckBox)findViewById(R.id.bech32);
cbBech32.setVisibility(PrefsUtil.getInstance(ReceiveActivity.this).getValue(PrefsUtil.USE_SEGWIT, true) == true ? View.VISIBLE : View.GONE);
cbBech32.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
addr = addr84;
}
else {
addr = addr49;
}
displayQRCode();
}
});
addr84 = AddressFactory.getInstance(ReceiveActivity.this).getBIP84(AddressFactory.RECEIVE_CHAIN).getBech32AsString();
addr49 = AddressFactory.getInstance(ReceiveActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString();
addr44 = AddressFactory.getInstance(ReceiveActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString();
if(PrefsUtil.getInstance(ReceiveActivity.this).getValue(PrefsUtil.USE_SEGWIT, true) == true && cbBech32.isChecked()) {
addr = addr84;
}
else if(PrefsUtil.getInstance(ReceiveActivity.this).getValue(PrefsUtil.USE_SEGWIT, true) == true && !cbBech32.isChecked()) {
addr = addr49;
}
else {
addr = addr44;
}
addressLayout = (LinearLayout)findViewById(R.id.receive_address_layout);
addressLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
new AlertDialog.Builder(ReceiveActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.receive_address_to_clipboard)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager)ReceiveActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = null;
clip = android.content.ClipData.newPlainText("Receive address", addr);
clipboard.setPrimaryClip(clip);
Toast.makeText(ReceiveActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
return false;
}
});
tvAddress = (TextView)findViewById(R.id.receive_address);
ivQR = (ImageView)findViewById(R.id.qr);
ivQR.setMaxWidth(imgWidth);
ivQR.setOnTouchListener(new OnSwipeTouchListener(ReceiveActivity.this) {
@Override
public void onSwipeLeft() {
if(swSegwit.isChecked() && cbBech32.isChecked() && canRefresh84) {
addr84 = AddressFactory.getInstance(ReceiveActivity.this).getBIP84(AddressFactory.RECEIVE_CHAIN).getBech32AsString();
addr = addr84;
canRefresh84 = false;
_menu.findItem(R.id.action_refresh).setVisible(false);
displayQRCode();
}
else if(swSegwit.isChecked() && !cbBech32.isChecked() && canRefresh49) {
addr49 = AddressFactory.getInstance(ReceiveActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString();
addr = addr49;
canRefresh49 = false;
_menu.findItem(R.id.action_refresh).setVisible(false);
displayQRCode();
}
else if(!swSegwit.isChecked() && canRefresh44) {
addr44 = AddressFactory.getInstance(ReceiveActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString();
addr = addr44;
canRefresh44 = false;
_menu.findItem(R.id.action_refresh).setVisible(false);
displayQRCode();
}
else {
;
}
}
});
DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols=format.getDecimalFormatSymbols();
defaultSeparator = Character.toString(symbols.getDecimalSeparator());
strFiat = PrefsUtil.getInstance(ReceiveActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD");
btc_fx = ExchangeRateFactory.getInstance(ReceiveActivity.this).getAvgPrice(strFiat);
tvFiatSymbol = (TextView)findViewById(R.id.fiatSymbol);
tvFiatSymbol.setText(getDisplayUnits() + "-" + strFiat);
edAmountBTC = (EditText)findViewById(R.id.amountBTC);
edAmountFiat = (EditText)findViewById(R.id.amountFiat);
textWatcherBTC = new TextWatcher() {
public void afterTextChanged(Editable s) {
edAmountBTC.removeTextChangedListener(this);
edAmountFiat.removeTextChangedListener(textWatcherFiat);
int max_len = 8;
NumberFormat btcFormat = NumberFormat.getInstance(Locale.US);
btcFormat.setMaximumFractionDigits(max_len + 1);
btcFormat.setMinimumFractionDigits(0);
double d = 0.0;
try {
d = NumberFormat.getInstance(Locale.US).parse(s.toString()).doubleValue();
String s1 = btcFormat.format(d);
if (s1.indexOf(defaultSeparator) != -1) {
String dec = s1.substring(s1.indexOf(defaultSeparator));
if (dec.length() > 0) {
dec = dec.substring(1);
if (dec.length() > max_len) {
edAmountBTC.setText(s1.substring(0, s1.length() - 1));
edAmountBTC.setSelection(edAmountBTC.getText().length());
s = edAmountBTC.getEditableText();
}
}
}
} catch (NumberFormatException nfe) {
;
}
catch(ParseException pe) {
;
}
if(d > 21000000.0) {
edAmountFiat.setText("0.00");
edAmountFiat.setSelection(edAmountFiat.getText().length());
edAmountBTC.setText("0");
edAmountBTC.setSelection(edAmountBTC.getText().length());
Toast.makeText(ReceiveActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show();
}
else {
edAmountFiat.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(d * btc_fx));
edAmountFiat.setSelection(edAmountFiat.getText().length());
}
edAmountFiat.addTextChangedListener(textWatcherFiat);
edAmountBTC.addTextChangedListener(this);
displayQRCode();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
;
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
;
}
};
edAmountBTC.addTextChangedListener(textWatcherBTC);
textWatcherFiat = new TextWatcher() {
public void afterTextChanged(Editable s) {
edAmountFiat.removeTextChangedListener(this);
edAmountBTC.removeTextChangedListener(textWatcherBTC);
int max_len = 2;
NumberFormat fiatFormat = NumberFormat.getInstance(Locale.US);
fiatFormat.setMaximumFractionDigits(max_len + 1);
fiatFormat.setMinimumFractionDigits(0);
double d = 0.0;
try {
d = NumberFormat.getInstance(Locale.US).parse(s.toString()).doubleValue();
String s1 = fiatFormat.format(d);
if(s1.indexOf(defaultSeparator) != -1) {
String dec = s1.substring(s1.indexOf(defaultSeparator));
if(dec.length() > 0) {
dec = dec.substring(1);
if(dec.length() > max_len) {
edAmountFiat.setText(s1.substring(0, s1.length() - 1));
edAmountFiat.setSelection(edAmountFiat.getText().length());
}
}
}
}
catch(NumberFormatException nfe) {
;
}
catch(ParseException pe) {
;
}
if((d / btc_fx) > 21000000.0) {
edAmountFiat.setText("0.00");
edAmountFiat.setSelection(edAmountFiat.getText().length());
edAmountBTC.setText("0");
edAmountBTC.setSelection(edAmountBTC.getText().length());
Toast.makeText(ReceiveActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show();
}
else {
edAmountBTC.setText(MonetaryUtil.getInstance().getBTCFormat().format(d / btc_fx));
edAmountBTC.setSelection(edAmountBTC.getText().length());
}
edAmountBTC.addTextChangedListener(textWatcherBTC);
edAmountFiat.addTextChangedListener(this);
displayQRCode();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
;
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
;
}
};
edAmountFiat.addTextChangedListener(textWatcherFiat);
displayQRCode();
}
@Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(ReceiveActivity.this).registerReceiver(receiver, filter);
AppUtil.getInstance(ReceiveActivity.this).checkTimeOut();
}
@Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(ReceiveActivity.this).unregisterReceiver(receiver);
}
@Override
public void onDestroy() {
ReceiveActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
menu.findItem(R.id.action_settings).setVisible(false);
menu.findItem(R.id.action_sweep).setVisible(false);
menu.findItem(R.id.action_backup).setVisible(false);
menu.findItem(R.id.action_scan_qr).setVisible(false);
menu.findItem(R.id.action_utxo).setVisible(false);
menu.findItem(R.id.action_tor).setVisible(false);
menu.findItem(R.id.action_ricochet).setVisible(false);
menu.findItem(R.id.action_empty_ricochet).setVisible(false);
menu.findItem(R.id.action_sign).setVisible(false);
menu.findItem(R.id.action_fees).setVisible(false);
menu.findItem(R.id.action_batch).setVisible(false);
_menu = menu;
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.action_share_receive) {
new AlertDialog.Builder(ReceiveActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.receive_address_to_share)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String strFileName = AppUtil.getInstance(ReceiveActivity.this).getReceiveQRFilename();
File file = new File(strFileName);
if(!file.exists()) {
try {
file.createNewFile();
}
catch(Exception e) {
Toast.makeText(ReceiveActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
file.setReadable(true, false);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
}
catch(FileNotFoundException fnfe) {
;
}
android.content.ClipboardManager clipboard = (android.content.ClipboardManager)ReceiveActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = null;
clip = android.content.ClipData.newPlainText("Receive address", addr);
clipboard.setPrimaryClip(clip);
if(file != null && fos != null) {
Bitmap bitmap = ((BitmapDrawable)ivQR.getDrawable()).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos);
try {
fos.close();
}
catch(IOException ioe) {
;
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
startActivity(Intent.createChooser(intent, ReceiveActivity.this.getText(R.string.send_payment_code)));
}
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
else if (id == R.id.action_refresh) {
if(swSegwit.isChecked() && cbBech32.isChecked() && canRefresh84) {
addr84 = AddressFactory.getInstance(ReceiveActivity.this).getBIP84(AddressFactory.RECEIVE_CHAIN).getBech32AsString();
addr = addr84;
canRefresh84 = false;
item.setVisible(false);
displayQRCode();
}
else if(swSegwit.isChecked() && !cbBech32.isChecked() && canRefresh49) {
addr49 = AddressFactory.getInstance(ReceiveActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString();
addr = addr49;
canRefresh49 = false;
item.setVisible(false);
displayQRCode();
}
else if(!swSegwit.isChecked() && canRefresh44) {
addr44 = AddressFactory.getInstance(ReceiveActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString();
addr = addr44;
canRefresh44 = false;
item.setVisible(false);
displayQRCode();
}
else {
;
}
}
else if (id == R.id.action_support) {
doSupport();
}
else {
;
}
return super.onOptionsItemSelected(item);
}
private void doSupport() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/section/7-receiving-bitcoin"));
startActivity(intent);
}
private void displayQRCode() {
try {
double amount = NumberFormat.getInstance(Locale.US).parse(edAmountBTC.getText().toString()).doubleValue();
long lamount = (long)(amount * 1e8);
if(lamount != 0L) {
ivQR.setImageBitmap(generateQRCode(BitcoinURI.convertToBitcoinURI(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr), Coin.valueOf(lamount), null, null)));
}
else {
ivQR.setImageBitmap(generateQRCode(addr));
}
}
catch(NumberFormatException nfe) {
ivQR.setImageBitmap(generateQRCode(addr));
}
catch(ParseException pe) {
ivQR.setImageBitmap(generateQRCode(addr));
}
tvAddress.setText(addr);
checkPrevUse();
new Thread(new Runnable() {
@Override
public void run() {
if(AppUtil.getInstance(ReceiveActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(ReceiveActivity.this.getApplicationContext(), WebSocketService.class));
}
startService(new Intent(ReceiveActivity.this.getApplicationContext(), WebSocketService.class));
}
}).start();
}
private Bitmap generateQRCode(String uri) {
Bitmap bitmap = null;
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(uri, null, Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), imgWidth);
try {
bitmap = qrCodeEncoder.encodeAsBitmap();
} catch (WriterException e) {
e.printStackTrace();
}
return bitmap;
}
private void checkPrevUse() {
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
try {
final JSONObject jsonObject = APIFactory.getInstance(ReceiveActivity.this).getAddressInfo(addr);
handler.post(new Runnable() {
@Override
public void run() {
try {
if(jsonObject != null && jsonObject.has("addresses") && jsonObject.getJSONArray("addresses").length() > 0) {
JSONArray addrs = jsonObject.getJSONArray("addresses");
JSONObject _addr = addrs.getJSONObject(0);
if(_addr.has("n_tx") && _addr.getLong("n_tx") > 0L) {
Toast.makeText(ReceiveActivity.this, R.string.address_used_previously, Toast.LENGTH_SHORT).show();
if(swSegwit.isChecked() && cbBech32.isChecked()) {
canRefresh84 = true;
}
else if(swSegwit.isChecked() && !cbBech32.isChecked()) {
canRefresh49 = true;
}
else {
canRefresh44 = true;
}
if(_menu != null) {
_menu.findItem(R.id.action_refresh).setVisible(true);
}
}
else {
if(swSegwit.isChecked() && cbBech32.isChecked()) {
canRefresh84 = false;
}
else if(swSegwit.isChecked() && !cbBech32.isChecked()) {
canRefresh49 = false;
}
else {
canRefresh44 = false;
}
if(_menu != null) {
_menu.findItem(R.id.action_refresh).setVisible(false);
}
}
}
} catch (Exception e) {
if(swSegwit.isChecked() && cbBech32.isChecked()) {
canRefresh84 = false;
}
else if(swSegwit.isChecked() && !cbBech32.isChecked()) {
canRefresh49 = false;
}
else {
canRefresh44 = false;
}
if(_menu != null) {
_menu.findItem(R.id.action_refresh).setVisible(false);
}
e.printStackTrace();
}
}
});
} catch (Exception e) {
if(swSegwit.isChecked() && cbBech32.isChecked()) {
canRefresh84 = false;
}
else if(swSegwit.isChecked() && !cbBech32.isChecked()) {
canRefresh49 = false;
}
else {
canRefresh44 = false;
}
if(_menu != null) {
_menu.findItem(R.id.action_refresh).setVisible(false);
}
e.printStackTrace();
}
}
}).start();
}
public String getDisplayUnits() {
return MonetaryUtil.getInstance().getBTCUnits();
}
} |
package date.kojuro.dooraccess;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import org.greenrobot.greendao.query.QueryBuilder;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LocationService.LocationCallback {
private final static String TAG = "MainActivity";
private FragmentManager fragmentManager = getSupportFragmentManager();
private Intent locationIntent;
private ServiceConnection mServiceConnection;
private boolean serviceAttached = false;
private Location mLocation;
private LocationService mLocationService;
private SwitchCompat vAutoSwitch;
private UIDLocationRelationDao mULRDao;
private List<UIDLocationRelation> mULRList;
private ReaderLocationDao mRLDao;
private List<ReaderLocation> mLList;
private TagDao mTagDao;
private DaemonConfiguration mDaemon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Fragment fragment = new SetUIDFragment();
fragmentManager.beginTransaction().replace(R.id.content_main_activity, fragment).commit();
/* Start Location Service */
locationIntent = new Intent(this, LocationService.class);
startService(locationIntent);
mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocationService.LocationBinder binder = (LocationService.LocationBinder)service;
mLocationService = binder.getService();
mLocationService.setGlobalLocationCallback(MainActivity.this);
serviceAttached = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
serviceAttached = false;
}
};
bindService(locationIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
NavigationView view = (NavigationView) findViewById(R.id.nav_view);
vAutoSwitch = (SwitchCompat) view.getMenu().findItem(R.id.nav_auto).getActionView().findViewById(R.id.auto_switch);
vAutoSwitch.setChecked(true);
vAutoSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i(TAG, "auto switch to " + isChecked);
}
});
mULRDao = DBService.getInstance(this).getUIDLocationRelationDao();
mTagDao = DBService.getInstance(this).getTagDao();
mRLDao = DBService.getInstance(this).getReaderLocationDao();
mDaemon = DaemonConfiguration.getInstance();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
switch(id) {
case R.id.nav_setuid:
fragment = new SetUIDFragment();
break;
case R.id.nav_location:
fragment = new LocationFragment();
break;
default:
return true;
}
fragmentManager.beginTransaction().replace(R.id.content_main_activity, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
protected void onDestroy() {
if(serviceAttached) {
serviceAttached = false;
unbindService(mServiceConnection);
}
super.onDestroy();
}
@Override
public void updateLocation(Location location) {
Log.i(TAG, "updateLocation");
/* maybe save the location for create location-tag relationship */
mLocation = location;
/* TODO if `auto` is disable, dont execute to below */
/* find out the nearest record, and need in URL record */
QueryBuilder<ReaderLocation> queryLocation = mRLDao.queryBuilder();
queryLocation
.join(UIDLocationRelation.class, UIDLocationRelationDao.Properties.ReaderLocationId)
.where(UIDLocationRelationDao.Properties.TagId.isNotNull());
mLList = queryLocation.list();
Log.i(TAG, "updateLocation queryLocation: " + mLList.toString());
/* no location record */
if(mLList == null || mLList.isEmpty()) {
return;
}
ReaderLocation nearestLocation = mLList.get(0);
float minDistance = location.distanceTo(mLList.get(0).getLocation());
for(ReaderLocation rLocation : mLList) {
float distance = location.distanceTo(rLocation.getLocation());
if(distance < minDistance) {
minDistance = distance;
nearestLocation = rLocation;
}
}
Log.i(TAG, "updateLocation nearestLocation: " + nearestLocation.getDescription());
/* join 3 tables */
QueryBuilder<Tag> queryBuilder = mTagDao.queryBuilder();
queryBuilder
.join(UIDLocationRelation.class, UIDLocationRelationDao.Properties.TagId)
.where(UIDLocationRelationDao.Properties.ReaderLocationId.eq(nearestLocation.getId()));
List<Tag> result = queryBuilder.list();
Log.i(TAG, "tag result: " + result.toString());
/* TODO need check the result ? */
if(result != null && !result.isEmpty()) {
enableTag(result.get(0));
}
}
public Location getLocation() {
return mLocation;
}
public LocationService getLocationService() {
return mLocationService;
}
public void enableTag(Tag tag) {
/* It will execute by service be for MainActivity onCreate */
if(mDaemon == null) {
mDaemon = DaemonConfiguration.getInstance();
}
mDaemon.disablePatch();
mDaemon.uploadConfiguration(
SetUIDFragment.ATQA,
SetUIDFragment.SAK,
SetUIDFragment.HIST,
SetUIDFragment.HexToBytes(tag.getUID())
);
mDaemon.enablePatch();
}
} |
package in.guanjia.demo.app;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import in.guanjia.demo.listener.ApiInterface;
import in.guanjia.demo.util.GsonConverterFactory;
import retrofit.Retrofit;
public class AppClientConfig {
// public static final String APP_BASE_URL = "";
public static final String APP_BASE_URL = "http://guanjia.in";
private static ApiInterface mApiInterface = null;
public static ApiInterface getApiClient() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
if (mApiInterface == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APP_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
mApiInterface = retrofit.create(ApiInterface.class);
}
return mApiInterface;
}
} |
package net.idoun.simplebanner;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditActivity extends AppCompatActivity {
private static final String TAG = "EditActivity";
public static final String ACTION_APPWIDGET_UPDATE = "net.idoun.intent.action.APPWIDGET_UPDATE";
public static final String EXTRA_WIDGET_ID = "WIDGET_ID";
public static final String PREF_USER_TEXT = "USER_TEXT_";
private EditText inputEditText;
private String text = "";
private SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
inputEditText = (EditText)findViewById(R.id.edit_input);
int appWidgetId = getIntent().getIntExtra(EXTRA_WIDGET_ID, -1);
final String widgetKey = EditActivity.PREF_USER_TEXT + appWidgetId;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.contains(widgetKey)) {
text = prefs.getString(widgetKey, "");
inputEditText.setText(text);
inputEditText.setSelection(text.length());
}
Button cancelButton = (Button)findViewById(R.id.cancel_button);
Button saveButton = (Button)findViewById(R.id.save_button);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String currentText = inputEditText.getText().toString();
Log.d(TAG, "onClick: " + currentText);
if (!currentText.isEmpty() && !text.equals(currentText)) {
prefs.edit().putString(widgetKey, currentText).apply();
updateMyWidgets(EditActivity.this);
finish();
}
}
});
}
private void updateMyWidgets(Context context) {
Intent updateIntent = new Intent();
updateIntent.setAction(ACTION_APPWIDGET_UPDATE);
context.sendBroadcast(updateIntent);
}
} |
package nfiniteloop.net.loqale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import net.nfiniteloop.loqale.backend.checkins.Checkins;
import net.nfiniteloop.loqale.backend.places.Places;
import net.nfiniteloop.loqale.backend.places.model.Place;
import net.nfiniteloop.loqale.backend.recommendations.Recommendations;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
public class MainActivity extends Activity {
// Logging for debugging
private Logger log = Logger.getLogger(MainActivity.class.getName());
// aysnchronous support classes
private static LoqaleFeedGetter feedTask;
private static RecommendationGetter recommendationTask;
private static placeGetter placesTask;
private static checkInHelper checkInsTask;
// endpoint client services
private static Checkins checkInService;
private static Places placesService;
private static Recommendations recommendationService;
//container class for places fragment
private TextView placesView;
private ListView placesList;
private List<Place> places = null;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = getTitle();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater= getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
public class LoqaleFeedGetter extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
}
@Override
protected void onCancelled() {
}
}
public class placeGetter extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
if (placesService == null) { // Only do this once
Places.Builder builder = new Places.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
placesService = builder.build();
}
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
}
@Override
protected void onCancelled() {
}
}
public class checkInHelper extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
if (checkInService == null) { // Only do this once
Checkins.Builder builder = new Checkins.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
checkInService = builder.build();
}
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
}
@Override
protected void onCancelled() {
}
}
public class RecommendationGetter extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
if (recommendationService == null) { // Only do this once
Recommendations.Builder builder = new Recommendations.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
recommendationService = builder.build();
}
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
}
@Override
protected void onCancelled() {
}
}
} |
package org.literacyapp;
import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import org.literacyapp.dao.DaoMaster;
import org.literacyapp.dao.DaoSession;
import org.literacyapp.util.Log;
public class LiteracyApplication extends Application {
private SQLiteDatabase db;
private DaoMaster daoMaster;
private DaoSession daoSession;
public static final boolean TEST_MODE = true;
@Override
public void onCreate() {
Log.d(getClass(), "onCreate");
super.onCreate();
// Initialize greenDAO database
DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(getApplicationContext(), "literacyapp-db", null);
db = openHelper.getWritableDatabase();
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
// ScreenOnReceiver screenOnReceiver = new ScreenOnReceiver();
// registerReceiver(screenOnReceiver, new IntentFilter("android.intent.action.SCREEN_ON"));
}
public DaoSession getDaoSession() {
return daoSession;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.